file_name
large_stringlengths
4
69
prefix
large_stringlengths
0
26.7k
suffix
large_stringlengths
0
24.8k
middle
large_stringlengths
0
2.12k
fim_type
large_stringclasses
4 values
decoder.rs
use crate::ebml; use crate::schema::{Schema, SchemaDict}; use crate::vint::{read_vint, UnrepresentableLengthError}; use chrono::{DateTime, NaiveDateTime, Utc}; use err_derive::Error; use log_derive::{logfn, logfn_inputs}; use std::convert::TryFrom; pub trait ReadEbmlExt: std::io::Read { #[logfn(ok = "TRACE", err = "ERROR")] fn read_ebml_to_end<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; let _size = self.read_to_end(&mut buf).map_err(DecodeError::Io)?; let elms = decoder.decode(buf)?; Ok(elms) } } impl<R: std::io::Read +?Sized> ReadEbmlExt for R {} pub trait BufReadEbmlExt: std::io::BufRead { #[logfn(ok = "TRACE", err = "ERROR")] fn read<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; loop { let used = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => return Err(DecodeError::Io(e)), }; buf.append(&mut decoder.decode(available.to_vec())?); available.len() }; self.consume(used); if used == 0 { break; } } Ok(buf) } } impl<R: std::io::BufRead +?Sized> BufReadEbmlExt for R {} #[derive(Debug, Error)] pub enum DecodeError { #[error(display = "{}", _0)] ReadVint(#[error(cause)] UnrepresentableLengthError), #[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)] UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition), #[error(display = "ReadContent")] ReadContent(#[error(cause)] ReadContentError), #[error(display = "UnknownEbmlId: {:?}", _0)] UnknownEbmlId(ebml::EbmlId), #[error(display = "Io")] Io(#[error(cause)] std::io::Error), } impl From<UnrepresentableLengthError> for DecodeError { fn from(o: UnrepresentableLengthError) -> Self { DecodeError::ReadVint(o) } } impl From<ReadContentError> for DecodeError { fn from(o: ReadContentError) -> Self { DecodeError::ReadContent(o) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] enum State { Tag, Size, Content, } pub struct Decoder<'a, D: SchemaDict<'a>> { schema: &'a D, state: State, buffer: Vec<u8>, cursor: usize, total: usize, stack: Vec<ebml::ElementPosition>, queue: Vec<ebml::ElementDetail>, } impl<'a, D: SchemaDict<'a>> Decoder<'a, D> { pub fn new(schema: &'a D) -> Self { Self { schema, state: State::Tag, buffer: vec![], cursor: 0, total: 0, stack: vec![], queue: vec![], } } #[logfn(ok = "TRACE", err = "ERROR")] pub fn decode(&mut self, chunk: Vec<u8>) -> Result<Vec<ebml::ElementDetail>, DecodeError> { self.read_chunk(chunk)?; let mut result = vec![]; std::mem::swap(&mut self.queue, &mut result); Ok(result) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_chunk(&mut self, mut chunk: Vec<u8>) -> Result<(), DecodeError> { // 読みかけの(読めなかった) buffer と 新しい chunk を合わせて読み直す self.buffer.append(&mut chunk); while self.cursor < self.buffer.len() { match self.state { State::Tag => { if!self.read_tag()? { break; } } State::Size => { if!self.read_size()? { break; } } State::Content => { if!self.read_content()? { break; } } } } Ok(()) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_tag(&mut self) -> Result<bool, DecodeError> { // tag is out of buffer if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml id vint without first byte let opt_tag = read_vint(&self.buffer, self.cursor)?; // cannot read tag yet if opt_tag.is_none() { return Ok(false); } let tag_size = opt_tag.unwrap().length; let ebml_id = ebml::EbmlId(opt_tag.unwrap().value); let tag_start = self.total; let size_start = self.total + (tag_size as usize); let content_start = 0; let content_size = 0; let schema = self .schema .get(ebml_id) .ok_or_else(|| DecodeError::UnknownEbmlId(ebml_id))?; let pos = ebml::ElementPosition { level: schema.level(), r#type: schema.r#type(), ebml_id, tag_start, size_start, content_start, content_size, }; self.stack.push(pos); // move cursor self.cursor += tag_size as usize; self.total += tag_size as usize; // change decoder state self.state = State::Size; Ok(true) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_size(&mut self) -> Result<bool, DecodeError> { if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml datasize vint without first byte let opt_size = read_vint(&self.buffer, self.cursor)?; if opt_size.is_none() { return Ok(false); } let size = opt_size.unwrap(); // decide current tag data size let ebml::ElementPosition { ref mut tag_start, ref mut content_start, ref mut content_size, .. } = self.stack.last_mut().unwrap(); *content_start = *tag_start + (size.length as usize); *content_size = size.value; // move cursor and change state self.cursor += size.length as usize; self.total += size.length as usize; self.state = State::Content; Ok(true) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_content(&mut self) -> Result<bool, DecodeError> { let current_pos = self.stack.last().unwrap(); // master element は子要素を持つので生データはない if current_pos.r#type =='m' { let elm = ( ebml::MasterStartElement { ebml_id: current_pos.ebml_id, unknown_size: current_pos.content_size == -1, }, *current_pos, ) .into(); self.queue.push(elm); self.state = State::Tag; // この Mastert Element は空要素か if current_pos.content_size == 0 { // 即座に終了タグを追加 self.queue.push( ( ebml::MasterEndElement { ebml_id: current_pos.ebml_id, }, *current_pos, ) .into(), ); // スタックからこのタグを捨てる self.stack.pop(); } return Ok(true); } // endless master element // waiting for more data if current_pos.content_size < 0 { return Err(DecodeError::UnknwonSizeNotAllowedInChildElement( *current_pos, )); } use std::convert::TryFrom as _; let content_size = usize::try_from(current_pos.content_size).unwrap(); if self.buffer.len() < self.cursor + content_size { return Ok(false); } // タグの中身の生データ let content = self.buffer[self.cursor..self.cursor + content_size].to_vec(); // 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す self.buffer = self.buffer.split_off(self.cursor + content_size); let child_elm = read_child_element( current_pos.ebml_id, current_pos.r#type, std::io::Cursor::new(content), content_size, )?; self.queue.push((child_elm, *current_pos).into()); // ポインタを進める self.total += content_size; // タグ待ちモードに変更 self.state = State::Tag; self.cursor = 0; // remove the object from the stack self.stack.pop(); while!self.stack.is_empty() { let parent_pos = self.stack.last().unwrap(); // 親が不定長サイズなので閉じタグは期待できない if parent_pos.content_size < 0 { self.stack.pop(); // 親タグを捨てる return Ok(true); } // 閉じタグの来るべき場所まで来たかどうか if self.total < parent_pos.content_start + content_size { break; } // 閉じタグを挿入すべきタイミングが来た if parent_pos.r#type!='m' { // throw new Error("parent element is not master element"); unreachable!(); } self.queue.push( ( ebml::MasterEndElement { ebml_id: parent_pos.ebml_id, }, *parent_pos, ) .into(), );
eadContentError { #[error(display = "Date")] Date(#[error(cause)] std::io::Error), #[error(display = "Utf8")] Utf8(#[error(cause)] std::io::Error), #[error(display = "UnsignedInteger")] UnsignedInteger(#[error(cause)] std::io::Error), #[error(display = "Integer")] Integer(#[error(cause)] std::io::Error), #[error(display = "Float")] Float(#[error(cause)] std::io::Error), #[error(display = "Binary")] Binary(#[error(cause)] std::io::Error), #[error(display = "String")] String(#[error(cause)] std::io::Error), #[error(display = "Master")] Master(#[error(cause)] std::io::Error), #[error(display = "Unknown")] Unknown(#[error(cause)] std::io::Error), } #[logfn_inputs(TRACE)] #[logfn(ok = "TRACE", err = "ERROR")] fn read_child_element<C: std::io::Read + std::fmt::Debug>( ebml_id: ebml::EbmlId, r#type: char, mut content: C, content_size: usize, ) -> Result<ebml::ChildElement, ReadContentError> { use byteorder::{BigEndian, ReadBytesExt as _}; use ReadContentError::{String as StringE, *}; match r#type { // Unsigned Integer - Big-endian, any size from 1 to 8 octets 'u' => { let value = content .read_uint::<BigEndian>(content_size) .map_err(UnsignedInteger)?; Ok(ebml::UnsignedIntegerElement { ebml_id, value }.into()) } // Signed Integer - Big-endian, any size from 1 to 8 octets 'i' => { let value = content .read_int::<BigEndian>(content_size) .map_err(Integer)?; Ok(ebml::IntegerElement { ebml_id, value }.into()) } // Float - Big-endian, defined for 4 and 8 octets (32, 64 bits) 'f' => { let value = if content_size == 4 { f64::from(content.read_f32::<BigEndian>().map_err(Float)?) } else if content_size == 8 { content.read_f64::<BigEndian>().map_err(Float)? } else { Err(Float(std::io::Error::new( std::io::ErrorKind::Other, format!("invalid float content_size: {}", content_size), )))? }; Ok(ebml::FloatElement { ebml_id, value }.into()) } // Printable ASCII (0x20 to 0x7E), zero-padded when needed 's' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(StringE)?; Ok(ebml::StringElement { ebml_id, value }.into()) } // Unicode string, zero padded when needed (RFC 2279) '8' => { let mut value = std::string::String::new(); content.read_to_string(&mut value).map_err(Utf8)?; Ok(ebml::Utf8Element { ebml_id, value }.into()) } // Binary - not interpreted by the parser 'b' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(Binary)?; Ok(ebml::BinaryElement { ebml_id, value }.into()) } // nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000 // new Date("2001-01-01T00:00:00.000Z").getTime() = 978307200000 // Date - signed 8 octets integer in nanoseconds with 0 indicating // the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) 'd' => { let nanos = content.read_i64::<BigEndian>().map_err(Date)?; let unix_time_nanos: i64 = nanos - 978_307_200 * 1000 * 1000 * 1000; let unix_time_secs: i64 = unix_time_nanos / 1000 / 1000 / 1000 - 1; let nsecs: u32 = u32::try_from((unix_time_nanos & (1000 * 1000 * 1000)) + (1000 * 1000 * 1000)) .unwrap(); let datetime = NaiveDateTime::from_timestamp(unix_time_secs, nsecs); let value = DateTime::from_utc(datetime, Utc); Ok(ebml::DateElement { ebml_id, value }.into()) } // Master-Element - contains other EBML sub-elements of the next lower level 'm' => Err(Master(std::io::Error::new( std::io::ErrorKind::Other, "cannot read master element as child element".to_string(), )))?, _ => Err(Unknown(std::io::Error::new( std::io::ErrorKind::Other, format!("unknown type: {}", r#type), )))?, } }
// スタックからこのタグを捨てる self.stack.pop(); } Ok(true) } } #[derive(Debug, Error)] pub enum R
conditional_block
decoder.rs
use crate::ebml; use crate::schema::{Schema, SchemaDict}; use crate::vint::{read_vint, UnrepresentableLengthError}; use chrono::{DateTime, NaiveDateTime, Utc}; use err_derive::Error; use log_derive::{logfn, logfn_inputs}; use std::convert::TryFrom; pub trait ReadEbmlExt: std::io::Read { #[logfn(ok = "TRACE", err = "ERROR")] fn read_ebml_to_end<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; let _size = self.read_to_end(&mut buf).map_err(DecodeError::Io)?; let elms = decoder.decode(buf)?; Ok(elms) } } impl<R: std::io::Read +?Sized> ReadEbmlExt for R {} pub trait BufReadEbmlExt: std::io::BufRead { #[logfn(ok = "TRACE", err = "ERROR")] fn read<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; loop { let used = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => return Err(DecodeError::Io(e)), }; buf.append(&mut decoder.decode(available.to_vec())?); available.len() }; self.consume(used); if used == 0 { break; } } Ok(buf) } } impl<R: std::io::BufRead +?Sized> BufReadEbmlExt for R {} #[derive(Debug, Error)] pub enum DecodeError { #[error(display = "{}", _0)] ReadVint(#[error(cause)] UnrepresentableLengthError), #[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)] UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition), #[error(display = "ReadContent")] ReadContent(#[error(cause)] ReadContentError), #[error(display = "UnknownEbmlId: {:?}", _0)] UnknownEbmlId(ebml::EbmlId), #[error(display = "Io")] Io(#[error(cause)] std::io::Error), } impl From<UnrepresentableLengthError> for DecodeError { fn from(o: UnrepresentableLengthError) -> Self
} impl From<ReadContentError> for DecodeError { fn from(o: ReadContentError) -> Self { DecodeError::ReadContent(o) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] enum State { Tag, Size, Content, } pub struct Decoder<'a, D: SchemaDict<'a>> { schema: &'a D, state: State, buffer: Vec<u8>, cursor: usize, total: usize, stack: Vec<ebml::ElementPosition>, queue: Vec<ebml::ElementDetail>, } impl<'a, D: SchemaDict<'a>> Decoder<'a, D> { pub fn new(schema: &'a D) -> Self { Self { schema, state: State::Tag, buffer: vec![], cursor: 0, total: 0, stack: vec![], queue: vec![], } } #[logfn(ok = "TRACE", err = "ERROR")] pub fn decode(&mut self, chunk: Vec<u8>) -> Result<Vec<ebml::ElementDetail>, DecodeError> { self.read_chunk(chunk)?; let mut result = vec![]; std::mem::swap(&mut self.queue, &mut result); Ok(result) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_chunk(&mut self, mut chunk: Vec<u8>) -> Result<(), DecodeError> { // 読みかけの(読めなかった) buffer と 新しい chunk を合わせて読み直す self.buffer.append(&mut chunk); while self.cursor < self.buffer.len() { match self.state { State::Tag => { if!self.read_tag()? { break; } } State::Size => { if!self.read_size()? { break; } } State::Content => { if!self.read_content()? { break; } } } } Ok(()) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_tag(&mut self) -> Result<bool, DecodeError> { // tag is out of buffer if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml id vint without first byte let opt_tag = read_vint(&self.buffer, self.cursor)?; // cannot read tag yet if opt_tag.is_none() { return Ok(false); } let tag_size = opt_tag.unwrap().length; let ebml_id = ebml::EbmlId(opt_tag.unwrap().value); let tag_start = self.total; let size_start = self.total + (tag_size as usize); let content_start = 0; let content_size = 0; let schema = self .schema .get(ebml_id) .ok_or_else(|| DecodeError::UnknownEbmlId(ebml_id))?; let pos = ebml::ElementPosition { level: schema.level(), r#type: schema.r#type(), ebml_id, tag_start, size_start, content_start, content_size, }; self.stack.push(pos); // move cursor self.cursor += tag_size as usize; self.total += tag_size as usize; // change decoder state self.state = State::Size; Ok(true) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_size(&mut self) -> Result<bool, DecodeError> { if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml datasize vint without first byte let opt_size = read_vint(&self.buffer, self.cursor)?; if opt_size.is_none() { return Ok(false); } let size = opt_size.unwrap(); // decide current tag data size let ebml::ElementPosition { ref mut tag_start, ref mut content_start, ref mut content_size, .. } = self.stack.last_mut().unwrap(); *content_start = *tag_start + (size.length as usize); *content_size = size.value; // move cursor and change state self.cursor += size.length as usize; self.total += size.length as usize; self.state = State::Content; Ok(true) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_content(&mut self) -> Result<bool, DecodeError> { let current_pos = self.stack.last().unwrap(); // master element は子要素を持つので生データはない if current_pos.r#type =='m' { let elm = ( ebml::MasterStartElement { ebml_id: current_pos.ebml_id, unknown_size: current_pos.content_size == -1, }, *current_pos, ) .into(); self.queue.push(elm); self.state = State::Tag; // この Mastert Element は空要素か if current_pos.content_size == 0 { // 即座に終了タグを追加 self.queue.push( ( ebml::MasterEndElement { ebml_id: current_pos.ebml_id, }, *current_pos, ) .into(), ); // スタックからこのタグを捨てる self.stack.pop(); } return Ok(true); } // endless master element // waiting for more data if current_pos.content_size < 0 { return Err(DecodeError::UnknwonSizeNotAllowedInChildElement( *current_pos, )); } use std::convert::TryFrom as _; let content_size = usize::try_from(current_pos.content_size).unwrap(); if self.buffer.len() < self.cursor + content_size { return Ok(false); } // タグの中身の生データ let content = self.buffer[self.cursor..self.cursor + content_size].to_vec(); // 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す self.buffer = self.buffer.split_off(self.cursor + content_size); let child_elm = read_child_element( current_pos.ebml_id, current_pos.r#type, std::io::Cursor::new(content), content_size, )?; self.queue.push((child_elm, *current_pos).into()); // ポインタを進める self.total += content_size; // タグ待ちモードに変更 self.state = State::Tag; self.cursor = 0; // remove the object from the stack self.stack.pop(); while!self.stack.is_empty() { let parent_pos = self.stack.last().unwrap(); // 親が不定長サイズなので閉じタグは期待できない if parent_pos.content_size < 0 { self.stack.pop(); // 親タグを捨てる return Ok(true); } // 閉じタグの来るべき場所まで来たかどうか if self.total < parent_pos.content_start + content_size { break; } // 閉じタグを挿入すべきタイミングが来た if parent_pos.r#type!='m' { // throw new Error("parent element is not master element"); unreachable!(); } self.queue.push( ( ebml::MasterEndElement { ebml_id: parent_pos.ebml_id, }, *parent_pos, ) .into(), ); // スタックからこのタグを捨てる self.stack.pop(); } Ok(true) } } #[derive(Debug, Error)] pub enum ReadContentError { #[error(display = "Date")] Date(#[error(cause)] std::io::Error), #[error(display = "Utf8")] Utf8(#[error(cause)] std::io::Error), #[error(display = "UnsignedInteger")] UnsignedInteger(#[error(cause)] std::io::Error), #[error(display = "Integer")] Integer(#[error(cause)] std::io::Error), #[error(display = "Float")] Float(#[error(cause)] std::io::Error), #[error(display = "Binary")] Binary(#[error(cause)] std::io::Error), #[error(display = "String")] String(#[error(cause)] std::io::Error), #[error(display = "Master")] Master(#[error(cause)] std::io::Error), #[error(display = "Unknown")] Unknown(#[error(cause)] std::io::Error), } #[logfn_inputs(TRACE)] #[logfn(ok = "TRACE", err = "ERROR")] fn read_child_element<C: std::io::Read + std::fmt::Debug>( ebml_id: ebml::EbmlId, r#type: char, mut content: C, content_size: usize, ) -> Result<ebml::ChildElement, ReadContentError> { use byteorder::{BigEndian, ReadBytesExt as _}; use ReadContentError::{String as StringE, *}; match r#type { // Unsigned Integer - Big-endian, any size from 1 to 8 octets 'u' => { let value = content .read_uint::<BigEndian>(content_size) .map_err(UnsignedInteger)?; Ok(ebml::UnsignedIntegerElement { ebml_id, value }.into()) } // Signed Integer - Big-endian, any size from 1 to 8 octets 'i' => { let value = content .read_int::<BigEndian>(content_size) .map_err(Integer)?; Ok(ebml::IntegerElement { ebml_id, value }.into()) } // Float - Big-endian, defined for 4 and 8 octets (32, 64 bits) 'f' => { let value = if content_size == 4 { f64::from(content.read_f32::<BigEndian>().map_err(Float)?) } else if content_size == 8 { content.read_f64::<BigEndian>().map_err(Float)? } else { Err(Float(std::io::Error::new( std::io::ErrorKind::Other, format!("invalid float content_size: {}", content_size), )))? }; Ok(ebml::FloatElement { ebml_id, value }.into()) } // Printable ASCII (0x20 to 0x7E), zero-padded when needed 's' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(StringE)?; Ok(ebml::StringElement { ebml_id, value }.into()) } // Unicode string, zero padded when needed (RFC 2279) '8' => { let mut value = std::string::String::new(); content.read_to_string(&mut value).map_err(Utf8)?; Ok(ebml::Utf8Element { ebml_id, value }.into()) } // Binary - not interpreted by the parser 'b' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(Binary)?; Ok(ebml::BinaryElement { ebml_id, value }.into()) } // nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000 // new Date("2001-01-01T00:00:00.000Z").getTime() = 978307200000 // Date - signed 8 octets integer in nanoseconds with 0 indicating // the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) 'd' => { let nanos = content.read_i64::<BigEndian>().map_err(Date)?; let unix_time_nanos: i64 = nanos - 978_307_200 * 1000 * 1000 * 1000; let unix_time_secs: i64 = unix_time_nanos / 1000 / 1000 / 1000 - 1; let nsecs: u32 = u32::try_from((unix_time_nanos & (1000 * 1000 * 1000)) + (1000 * 1000 * 1000)) .unwrap(); let datetime = NaiveDateTime::from_timestamp(unix_time_secs, nsecs); let value = DateTime::from_utc(datetime, Utc); Ok(ebml::DateElement { ebml_id, value }.into()) } // Master-Element - contains other EBML sub-elements of the next lower level 'm' => Err(Master(std::io::Error::new( std::io::ErrorKind::Other, "cannot read master element as child element".to_string(), )))?, _ => Err(Unknown(std::io::Error::new( std::io::ErrorKind::Other, format!("unknown type: {}", r#type), )))?, } }
{ DecodeError::ReadVint(o) }
identifier_body
decoder.rs
use crate::ebml; use crate::schema::{Schema, SchemaDict}; use crate::vint::{read_vint, UnrepresentableLengthError}; use chrono::{DateTime, NaiveDateTime, Utc}; use err_derive::Error; use log_derive::{logfn, logfn_inputs}; use std::convert::TryFrom; pub trait ReadEbmlExt: std::io::Read { #[logfn(ok = "TRACE", err = "ERROR")] fn read_ebml_to_end<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; let _size = self.read_to_end(&mut buf).map_err(DecodeError::Io)?; let elms = decoder.decode(buf)?; Ok(elms) } } impl<R: std::io::Read +?Sized> ReadEbmlExt for R {} pub trait BufReadEbmlExt: std::io::BufRead { #[logfn(ok = "TRACE", err = "ERROR")] fn read<'a, D: SchemaDict<'a>>( &mut self, schema: &'a D, ) -> Result<Vec<ebml::ElementDetail>, DecodeError> { let mut decoder = Decoder::new(schema); let mut buf = vec![]; loop { let used = { let available = match self.fill_buf() { Ok(n) => n, Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue, Err(e) => return Err(DecodeError::Io(e)), }; buf.append(&mut decoder.decode(available.to_vec())?); available.len() }; self.consume(used); if used == 0 { break; } } Ok(buf) } } impl<R: std::io::BufRead +?Sized> BufReadEbmlExt for R {} #[derive(Debug, Error)] pub enum DecodeError { #[error(display = "{}", _0)] ReadVint(#[error(cause)] UnrepresentableLengthError), #[error(display = "UnknwonSizeNotAllowedInChildElement: pos {:?}", _0)] UnknwonSizeNotAllowedInChildElement(ebml::ElementPosition), #[error(display = "ReadContent")] ReadContent(#[error(cause)] ReadContentError), #[error(display = "UnknownEbmlId: {:?}", _0)] UnknownEbmlId(ebml::EbmlId), #[error(display = "Io")] Io(#[error(cause)] std::io::Error), } impl From<UnrepresentableLengthError> for DecodeError { fn from(o: UnrepresentableLengthError) -> Self { DecodeError::ReadVint(o) } } impl From<ReadContentError> for DecodeError { fn
(o: ReadContentError) -> Self { DecodeError::ReadContent(o) } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] enum State { Tag, Size, Content, } pub struct Decoder<'a, D: SchemaDict<'a>> { schema: &'a D, state: State, buffer: Vec<u8>, cursor: usize, total: usize, stack: Vec<ebml::ElementPosition>, queue: Vec<ebml::ElementDetail>, } impl<'a, D: SchemaDict<'a>> Decoder<'a, D> { pub fn new(schema: &'a D) -> Self { Self { schema, state: State::Tag, buffer: vec![], cursor: 0, total: 0, stack: vec![], queue: vec![], } } #[logfn(ok = "TRACE", err = "ERROR")] pub fn decode(&mut self, chunk: Vec<u8>) -> Result<Vec<ebml::ElementDetail>, DecodeError> { self.read_chunk(chunk)?; let mut result = vec![]; std::mem::swap(&mut self.queue, &mut result); Ok(result) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_chunk(&mut self, mut chunk: Vec<u8>) -> Result<(), DecodeError> { // 読みかけの(読めなかった) buffer と 新しい chunk を合わせて読み直す self.buffer.append(&mut chunk); while self.cursor < self.buffer.len() { match self.state { State::Tag => { if!self.read_tag()? { break; } } State::Size => { if!self.read_size()? { break; } } State::Content => { if!self.read_content()? { break; } } } } Ok(()) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_tag(&mut self) -> Result<bool, DecodeError> { // tag is out of buffer if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml id vint without first byte let opt_tag = read_vint(&self.buffer, self.cursor)?; // cannot read tag yet if opt_tag.is_none() { return Ok(false); } let tag_size = opt_tag.unwrap().length; let ebml_id = ebml::EbmlId(opt_tag.unwrap().value); let tag_start = self.total; let size_start = self.total + (tag_size as usize); let content_start = 0; let content_size = 0; let schema = self .schema .get(ebml_id) .ok_or_else(|| DecodeError::UnknownEbmlId(ebml_id))?; let pos = ebml::ElementPosition { level: schema.level(), r#type: schema.r#type(), ebml_id, tag_start, size_start, content_start, content_size, }; self.stack.push(pos); // move cursor self.cursor += tag_size as usize; self.total += tag_size as usize; // change decoder state self.state = State::Size; Ok(true) } /// return false when waiting for more data #[logfn(ok = "TRACE", err = "ERROR")] fn read_size(&mut self) -> Result<bool, DecodeError> { if self.cursor >= self.buffer.len() { return Ok(false); } // read ebml datasize vint without first byte let opt_size = read_vint(&self.buffer, self.cursor)?; if opt_size.is_none() { return Ok(false); } let size = opt_size.unwrap(); // decide current tag data size let ebml::ElementPosition { ref mut tag_start, ref mut content_start, ref mut content_size, .. } = self.stack.last_mut().unwrap(); *content_start = *tag_start + (size.length as usize); *content_size = size.value; // move cursor and change state self.cursor += size.length as usize; self.total += size.length as usize; self.state = State::Content; Ok(true) } #[logfn(ok = "TRACE", err = "ERROR")] fn read_content(&mut self) -> Result<bool, DecodeError> { let current_pos = self.stack.last().unwrap(); // master element は子要素を持つので生データはない if current_pos.r#type =='m' { let elm = ( ebml::MasterStartElement { ebml_id: current_pos.ebml_id, unknown_size: current_pos.content_size == -1, }, *current_pos, ) .into(); self.queue.push(elm); self.state = State::Tag; // この Mastert Element は空要素か if current_pos.content_size == 0 { // 即座に終了タグを追加 self.queue.push( ( ebml::MasterEndElement { ebml_id: current_pos.ebml_id, }, *current_pos, ) .into(), ); // スタックからこのタグを捨てる self.stack.pop(); } return Ok(true); } // endless master element // waiting for more data if current_pos.content_size < 0 { return Err(DecodeError::UnknwonSizeNotAllowedInChildElement( *current_pos, )); } use std::convert::TryFrom as _; let content_size = usize::try_from(current_pos.content_size).unwrap(); if self.buffer.len() < self.cursor + content_size { return Ok(false); } // タグの中身の生データ let content = self.buffer[self.cursor..self.cursor + content_size].to_vec(); // 読み終わったバッファを捨てて読み込んでいる部分のバッファのみ残す self.buffer = self.buffer.split_off(self.cursor + content_size); let child_elm = read_child_element( current_pos.ebml_id, current_pos.r#type, std::io::Cursor::new(content), content_size, )?; self.queue.push((child_elm, *current_pos).into()); // ポインタを進める self.total += content_size; // タグ待ちモードに変更 self.state = State::Tag; self.cursor = 0; // remove the object from the stack self.stack.pop(); while!self.stack.is_empty() { let parent_pos = self.stack.last().unwrap(); // 親が不定長サイズなので閉じタグは期待できない if parent_pos.content_size < 0 { self.stack.pop(); // 親タグを捨てる return Ok(true); } // 閉じタグの来るべき場所まで来たかどうか if self.total < parent_pos.content_start + content_size { break; } // 閉じタグを挿入すべきタイミングが来た if parent_pos.r#type!='m' { // throw new Error("parent element is not master element"); unreachable!(); } self.queue.push( ( ebml::MasterEndElement { ebml_id: parent_pos.ebml_id, }, *parent_pos, ) .into(), ); // スタックからこのタグを捨てる self.stack.pop(); } Ok(true) } } #[derive(Debug, Error)] pub enum ReadContentError { #[error(display = "Date")] Date(#[error(cause)] std::io::Error), #[error(display = "Utf8")] Utf8(#[error(cause)] std::io::Error), #[error(display = "UnsignedInteger")] UnsignedInteger(#[error(cause)] std::io::Error), #[error(display = "Integer")] Integer(#[error(cause)] std::io::Error), #[error(display = "Float")] Float(#[error(cause)] std::io::Error), #[error(display = "Binary")] Binary(#[error(cause)] std::io::Error), #[error(display = "String")] String(#[error(cause)] std::io::Error), #[error(display = "Master")] Master(#[error(cause)] std::io::Error), #[error(display = "Unknown")] Unknown(#[error(cause)] std::io::Error), } #[logfn_inputs(TRACE)] #[logfn(ok = "TRACE", err = "ERROR")] fn read_child_element<C: std::io::Read + std::fmt::Debug>( ebml_id: ebml::EbmlId, r#type: char, mut content: C, content_size: usize, ) -> Result<ebml::ChildElement, ReadContentError> { use byteorder::{BigEndian, ReadBytesExt as _}; use ReadContentError::{String as StringE, *}; match r#type { // Unsigned Integer - Big-endian, any size from 1 to 8 octets 'u' => { let value = content .read_uint::<BigEndian>(content_size) .map_err(UnsignedInteger)?; Ok(ebml::UnsignedIntegerElement { ebml_id, value }.into()) } // Signed Integer - Big-endian, any size from 1 to 8 octets 'i' => { let value = content .read_int::<BigEndian>(content_size) .map_err(Integer)?; Ok(ebml::IntegerElement { ebml_id, value }.into()) } // Float - Big-endian, defined for 4 and 8 octets (32, 64 bits) 'f' => { let value = if content_size == 4 { f64::from(content.read_f32::<BigEndian>().map_err(Float)?) } else if content_size == 8 { content.read_f64::<BigEndian>().map_err(Float)? } else { Err(Float(std::io::Error::new( std::io::ErrorKind::Other, format!("invalid float content_size: {}", content_size), )))? }; Ok(ebml::FloatElement { ebml_id, value }.into()) } // Printable ASCII (0x20 to 0x7E), zero-padded when needed 's' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(StringE)?; Ok(ebml::StringElement { ebml_id, value }.into()) } // Unicode string, zero padded when needed (RFC 2279) '8' => { let mut value = std::string::String::new(); content.read_to_string(&mut value).map_err(Utf8)?; Ok(ebml::Utf8Element { ebml_id, value }.into()) } // Binary - not interpreted by the parser 'b' => { let mut value = vec![0; content_size]; content.read_exact(&mut value).map_err(Binary)?; Ok(ebml::BinaryElement { ebml_id, value }.into()) } // nano second; Date.UTC(2001,1,1,0,0,0,0) === 980985600000 // new Date("2001-01-01T00:00:00.000Z").getTime() = 978307200000 // Date - signed 8 octets integer in nanoseconds with 0 indicating // the precise beginning of the millennium (at 2001-01-01T00:00:00,000000000 UTC) 'd' => { let nanos = content.read_i64::<BigEndian>().map_err(Date)?; let unix_time_nanos: i64 = nanos - 978_307_200 * 1000 * 1000 * 1000; let unix_time_secs: i64 = unix_time_nanos / 1000 / 1000 / 1000 - 1; let nsecs: u32 = u32::try_from((unix_time_nanos & (1000 * 1000 * 1000)) + (1000 * 1000 * 1000)) .unwrap(); let datetime = NaiveDateTime::from_timestamp(unix_time_secs, nsecs); let value = DateTime::from_utc(datetime, Utc); Ok(ebml::DateElement { ebml_id, value }.into()) } // Master-Element - contains other EBML sub-elements of the next lower level 'm' => Err(Master(std::io::Error::new( std::io::ErrorKind::Other, "cannot read master element as child element".to_string(), )))?, _ => Err(Unknown(std::io::Error::new( std::io::ErrorKind::Other, format!("unknown type: {}", r#type), )))?, } }
from
identifier_name
string_pool.rs
use crate::expat_external_h::XML_Char; use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert}; use crate::lib::xmltok::{ENCODING, XML_Convert_Result}; use bumpalo::Bump; use bumpalo::collections::vec::Vec as BumpVec; use fallible_collections::FallibleBox; use libc::c_int; use std::cell::{Cell, RefCell}; use std::convert::TryInto; use std::mem::swap; pub const INIT_BLOCK_SIZE: usize = 1024; rental! { mod rental_pool { use super::*; #[rental(debug)] pub(crate) struct InnerStringPool { // The rental crate requires that all fields but the last one // implement `StableDeref`, which means we need to wrap it // in a `Box` bump: Box<Bump>, current_bump_vec: RefCell<RentedBumpVec<'bump>>, } } } use rental_pool::InnerStringPool; /// A StringPool has the purpose of allocating distinct strings and then /// handing them off to be referenced either temporarily or for the entire length /// of the pool. pub(crate) struct StringPool(Option<InnerStringPool>); impl StringPool { pub(crate) fn
() -> Result<Self, ()> { let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?; let boxed_bump = Box::try_new(bump).map_err(|_| ())?; Ok(StringPool(Some(InnerStringPool::new( boxed_bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )))) } /// # Safety /// /// The inner type is only ever None in middle of the clear() /// method. Therefore it is safe to use anywhere else. fn inner(&self) -> &InnerStringPool { self.0.as_ref().unwrap_or_else(|| unsafe { std::hint::unreachable_unchecked() }) } /// Determines whether or not the current BumpVec is empty. pub(crate) fn is_empty(&self) -> bool { self.inner().rent(|vec| vec.borrow().0.is_empty()) } /// Determines whether or not the current BumpVec is full. pub(crate) fn is_full(&self) -> bool { self.inner().rent(|vec| vec.borrow().is_full()) } /// Gets the current vec, converts it into an immutable slice, /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string(&self) -> &[XML_Char] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); pool.current_bump_vec.replace(vec).0.into_bump_slice() }) } /// Gets the current vec, converts it into a slice of cells (with interior mutability), /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string_cells(&self) -> &[Cell<XML_Char>] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); let sl = pool.current_bump_vec.replace(vec).0.into_bump_slice_mut(); Cell::from_mut(sl).as_slice_of_cells() }) } /// Resets the current bump vec to the beginning pub(crate) fn clear_current(&self) { self.inner().rent(|v| v.borrow_mut().0.clear()) } /// Obtains the length of the current BumpVec. pub(crate) fn len(&self) -> usize { self.inner().rent(|vec| vec.borrow().0.len()) } /// Call callback with an immutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&[XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow().0.as_slice())) } /// Call callback with a mutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_mut_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&mut [XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow_mut().0.as_mut_slice())) } /// Unsafe temporary version of `current_slice()`. This needs to be removed /// when callers are made safe. pub(crate) unsafe fn current_start(&self) -> *const XML_Char { self.inner().rent(|v| v.borrow().0.as_ptr()) } /// Appends a char to the current BumpVec. pub(crate) fn append_char(&self, c: XML_Char) -> bool { self.inner().rent(|vec| vec.borrow_mut().append_char(c)) } /// Overwrites the last char in the current BumpVec. /// Note that this will panic if empty. This is not an insert /// operation as it does not shift bytes afterwards. pub(crate) fn replace_last_char(&self, c: XML_Char) { self.inner().rent(|buf| { *buf.borrow_mut() .0 .last_mut() .expect("Called replace_last_char() when string was empty") = c; }) } /// Decrements the length, panicing if len is 0 pub(crate) fn backtrack(&self) { self.inner().rent(|vec| vec.borrow_mut().0.pop().expect("Called backtrack() on empty BumpVec")); } /// Gets the last character, panicing if len is 0 pub(crate) fn get_last_char(&self) -> XML_Char { self.inner().rent(|buf| *buf.borrow().0.last().expect("Called get_last_char() when string was empty")) } /// Appends an entire C String to the current BumpVec. pub(crate) unsafe fn append_c_string(&self, mut s: *const XML_Char) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); while *s!= 0 { if!vec.append_char(*s) { return false; } s = s.offset(1) } true }) } /// Resets the current Bump and deallocates its contents. /// The `inner` method must never be called here as it assumes /// self.0 is never `None` pub(crate) fn clear(&mut self) { let mut inner_pool = self.0.take(); let mut bump = inner_pool.unwrap().into_head(); bump.reset(); inner_pool = Some(InnerStringPool::new( bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )); swap(&mut self.0, &mut inner_pool); } pub(crate) fn store_c_string( &self, enc: &ENCODING, buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); if!vec.append(enc, buf) { return false; } if!vec.append_char('\0' as XML_Char) { return false; } true }) } pub(crate) fn append( &self, enc: &ENCODING, read_buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| vec.borrow_mut().append(enc, read_buf)) } pub(crate) unsafe fn copy_c_string( &self, mut s: *const XML_Char, ) -> Option<&[XML_Char]> { // self.append_c_string(s);? let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); loop { if!vec.append_char(*s) { return false; } if *s == 0 { break; } s = s.offset(1); } true }); if!successful { return None; } Some(self.finish_string()) } pub(crate) unsafe fn copy_c_string_n( &self, mut s: *const XML_Char, mut n: c_int, ) -> Option<&[XML_Char]> { let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); let mut n = n.try_into().unwrap(); if vec.0.try_reserve_exact(n).is_err() { return false; }; while n > 0 { if!vec.append_char(*s) { return false; } n -= 1; s = s.offset(1) } true }); if!successful { return None; } Some(self.finish_string()) } } #[derive(Debug)] pub(crate) struct RentedBumpVec<'bump>(BumpVec<'bump, XML_Char>); impl<'bump> RentedBumpVec<'bump> { fn is_full(&self) -> bool { self.0.len() == self.0.capacity() } fn append<'a>( &mut self, enc: &ENCODING, mut read_buf: ExpatBufRef<'a>, ) -> bool { loop { // REXPAT: always reserve at least 4 bytes, // so at least one character gets converted every iteration if self.0.try_reserve(read_buf.len().max(4)).is_err() { return false; } let start_len = self.0.len(); let cap = self.0.capacity(); self.0.resize(cap, 0); let mut write_buf = ExpatBufRefMut::from(&mut self.0[start_len..]); let write_buf_len = write_buf.len(); let convert_res = XmlConvert!(enc, &mut read_buf, &mut write_buf); // The write buf shrinks by how much was written to it let written_size = write_buf_len - write_buf.len(); self.0.truncate(start_len + written_size); if convert_res == XML_Convert_Result::COMPLETED || convert_res == XML_Convert_Result::INPUT_INCOMPLETE { return true; } } } fn append_char(&mut self, c: XML_Char) -> bool { if self.0.try_reserve(1).is_err() { false } else { self.0.push(c); true } } } #[cfg(test)] mod consts { use super::XML_Char; pub const A: XML_Char = 'a' as XML_Char; pub const B: XML_Char = 'b' as XML_Char; pub const C: XML_Char = 'c' as XML_Char; pub const D: XML_Char = 'd' as XML_Char; pub const NULL: XML_Char = '\0' as XML_Char; pub static S: [XML_Char; 5] = [C, D, D, C, NULL]; } #[test] fn test_append_char() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [A, B])); // New BumpVec pool.finish_string(); assert!(pool.append_char(C)); pool.current_slice(|s| assert_eq!(s, [C])); } #[test] fn test_append_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); let mut string = [A, B, C, NULL]; unsafe { assert!(pool.append_c_string(string.as_mut_ptr())); } pool.current_slice(|s| assert_eq!(s, [A, B, C])); } #[test] fn test_copy_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); let new_string = unsafe { pool.copy_c_string(S.as_ptr()) }; assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [B])); let new_string2 = unsafe { pool.copy_c_string_n(S.as_ptr(), 4) }; assert_eq!(new_string2.unwrap(), [B, C, D, D, C]); } #[test] fn test_store_c_string() { use consts::*; use crate::lib::xmlparse::XmlGetInternalEncoding; let mut pool = StringPool::try_new().unwrap(); let enc = XmlGetInternalEncoding(); let read_buf = unsafe { ExpatBufRef::new(S.as_ptr(), S.as_ptr().add(3)) }; assert!(pool.store_c_string(enc, read_buf)); let string = pool.finish_string(); assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); // No overlap between buffers: assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A, A])); // Force reallocation: pool.inner().rent(|v| v.borrow_mut().0.resize(2, 0)); assert!(pool.store_c_string(enc, read_buf)); let s = pool.finish_string(); assert_eq!(s, [A, A, C, D, D, NULL]); }
try_new
identifier_name
string_pool.rs
use crate::expat_external_h::XML_Char; use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert}; use crate::lib::xmltok::{ENCODING, XML_Convert_Result}; use bumpalo::Bump; use bumpalo::collections::vec::Vec as BumpVec; use fallible_collections::FallibleBox; use libc::c_int; use std::cell::{Cell, RefCell}; use std::convert::TryInto; use std::mem::swap; pub const INIT_BLOCK_SIZE: usize = 1024; rental! { mod rental_pool { use super::*; #[rental(debug)] pub(crate) struct InnerStringPool { // The rental crate requires that all fields but the last one // implement `StableDeref`, which means we need to wrap it // in a `Box` bump: Box<Bump>, current_bump_vec: RefCell<RentedBumpVec<'bump>>, } } } use rental_pool::InnerStringPool; /// A StringPool has the purpose of allocating distinct strings and then /// handing them off to be referenced either temporarily or for the entire length /// of the pool. pub(crate) struct StringPool(Option<InnerStringPool>); impl StringPool { pub(crate) fn try_new() -> Result<Self, ()> { let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?; let boxed_bump = Box::try_new(bump).map_err(|_| ())?; Ok(StringPool(Some(InnerStringPool::new( boxed_bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )))) } /// # Safety /// /// The inner type is only ever None in middle of the clear() /// method. Therefore it is safe to use anywhere else. fn inner(&self) -> &InnerStringPool { self.0.as_ref().unwrap_or_else(|| unsafe { std::hint::unreachable_unchecked() }) } /// Determines whether or not the current BumpVec is empty. pub(crate) fn is_empty(&self) -> bool { self.inner().rent(|vec| vec.borrow().0.is_empty()) } /// Determines whether or not the current BumpVec is full. pub(crate) fn is_full(&self) -> bool { self.inner().rent(|vec| vec.borrow().is_full()) } /// Gets the current vec, converts it into an immutable slice, /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string(&self) -> &[XML_Char] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); pool.current_bump_vec.replace(vec).0.into_bump_slice() }) } /// Gets the current vec, converts it into a slice of cells (with interior mutability), /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string_cells(&self) -> &[Cell<XML_Char>] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); let sl = pool.current_bump_vec.replace(vec).0.into_bump_slice_mut(); Cell::from_mut(sl).as_slice_of_cells() }) } /// Resets the current bump vec to the beginning pub(crate) fn clear_current(&self) { self.inner().rent(|v| v.borrow_mut().0.clear()) } /// Obtains the length of the current BumpVec. pub(crate) fn len(&self) -> usize { self.inner().rent(|vec| vec.borrow().0.len()) } /// Call callback with an immutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&[XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow().0.as_slice())) } /// Call callback with a mutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_mut_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&mut [XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow_mut().0.as_mut_slice())) } /// Unsafe temporary version of `current_slice()`. This needs to be removed /// when callers are made safe. pub(crate) unsafe fn current_start(&self) -> *const XML_Char { self.inner().rent(|v| v.borrow().0.as_ptr()) } /// Appends a char to the current BumpVec. pub(crate) fn append_char(&self, c: XML_Char) -> bool { self.inner().rent(|vec| vec.borrow_mut().append_char(c)) } /// Overwrites the last char in the current BumpVec. /// Note that this will panic if empty. This is not an insert /// operation as it does not shift bytes afterwards. pub(crate) fn replace_last_char(&self, c: XML_Char) { self.inner().rent(|buf| { *buf.borrow_mut() .0 .last_mut() .expect("Called replace_last_char() when string was empty") = c; }) } /// Decrements the length, panicing if len is 0 pub(crate) fn backtrack(&self) { self.inner().rent(|vec| vec.borrow_mut().0.pop().expect("Called backtrack() on empty BumpVec")); } /// Gets the last character, panicing if len is 0 pub(crate) fn get_last_char(&self) -> XML_Char { self.inner().rent(|buf| *buf.borrow().0.last().expect("Called get_last_char() when string was empty")) } /// Appends an entire C String to the current BumpVec. pub(crate) unsafe fn append_c_string(&self, mut s: *const XML_Char) -> bool
/// Resets the current Bump and deallocates its contents. /// The `inner` method must never be called here as it assumes /// self.0 is never `None` pub(crate) fn clear(&mut self) { let mut inner_pool = self.0.take(); let mut bump = inner_pool.unwrap().into_head(); bump.reset(); inner_pool = Some(InnerStringPool::new( bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )); swap(&mut self.0, &mut inner_pool); } pub(crate) fn store_c_string( &self, enc: &ENCODING, buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); if!vec.append(enc, buf) { return false; } if!vec.append_char('\0' as XML_Char) { return false; } true }) } pub(crate) fn append( &self, enc: &ENCODING, read_buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| vec.borrow_mut().append(enc, read_buf)) } pub(crate) unsafe fn copy_c_string( &self, mut s: *const XML_Char, ) -> Option<&[XML_Char]> { // self.append_c_string(s);? let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); loop { if!vec.append_char(*s) { return false; } if *s == 0 { break; } s = s.offset(1); } true }); if!successful { return None; } Some(self.finish_string()) } pub(crate) unsafe fn copy_c_string_n( &self, mut s: *const XML_Char, mut n: c_int, ) -> Option<&[XML_Char]> { let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); let mut n = n.try_into().unwrap(); if vec.0.try_reserve_exact(n).is_err() { return false; }; while n > 0 { if!vec.append_char(*s) { return false; } n -= 1; s = s.offset(1) } true }); if!successful { return None; } Some(self.finish_string()) } } #[derive(Debug)] pub(crate) struct RentedBumpVec<'bump>(BumpVec<'bump, XML_Char>); impl<'bump> RentedBumpVec<'bump> { fn is_full(&self) -> bool { self.0.len() == self.0.capacity() } fn append<'a>( &mut self, enc: &ENCODING, mut read_buf: ExpatBufRef<'a>, ) -> bool { loop { // REXPAT: always reserve at least 4 bytes, // so at least one character gets converted every iteration if self.0.try_reserve(read_buf.len().max(4)).is_err() { return false; } let start_len = self.0.len(); let cap = self.0.capacity(); self.0.resize(cap, 0); let mut write_buf = ExpatBufRefMut::from(&mut self.0[start_len..]); let write_buf_len = write_buf.len(); let convert_res = XmlConvert!(enc, &mut read_buf, &mut write_buf); // The write buf shrinks by how much was written to it let written_size = write_buf_len - write_buf.len(); self.0.truncate(start_len + written_size); if convert_res == XML_Convert_Result::COMPLETED || convert_res == XML_Convert_Result::INPUT_INCOMPLETE { return true; } } } fn append_char(&mut self, c: XML_Char) -> bool { if self.0.try_reserve(1).is_err() { false } else { self.0.push(c); true } } } #[cfg(test)] mod consts { use super::XML_Char; pub const A: XML_Char = 'a' as XML_Char; pub const B: XML_Char = 'b' as XML_Char; pub const C: XML_Char = 'c' as XML_Char; pub const D: XML_Char = 'd' as XML_Char; pub const NULL: XML_Char = '\0' as XML_Char; pub static S: [XML_Char; 5] = [C, D, D, C, NULL]; } #[test] fn test_append_char() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [A, B])); // New BumpVec pool.finish_string(); assert!(pool.append_char(C)); pool.current_slice(|s| assert_eq!(s, [C])); } #[test] fn test_append_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); let mut string = [A, B, C, NULL]; unsafe { assert!(pool.append_c_string(string.as_mut_ptr())); } pool.current_slice(|s| assert_eq!(s, [A, B, C])); } #[test] fn test_copy_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); let new_string = unsafe { pool.copy_c_string(S.as_ptr()) }; assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [B])); let new_string2 = unsafe { pool.copy_c_string_n(S.as_ptr(), 4) }; assert_eq!(new_string2.unwrap(), [B, C, D, D, C]); } #[test] fn test_store_c_string() { use consts::*; use crate::lib::xmlparse::XmlGetInternalEncoding; let mut pool = StringPool::try_new().unwrap(); let enc = XmlGetInternalEncoding(); let read_buf = unsafe { ExpatBufRef::new(S.as_ptr(), S.as_ptr().add(3)) }; assert!(pool.store_c_string(enc, read_buf)); let string = pool.finish_string(); assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); // No overlap between buffers: assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A, A])); // Force reallocation: pool.inner().rent(|v| v.borrow_mut().0.resize(2, 0)); assert!(pool.store_c_string(enc, read_buf)); let s = pool.finish_string(); assert_eq!(s, [A, A, C, D, D, NULL]); }
{ self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); while *s != 0 { if !vec.append_char(*s) { return false; } s = s.offset(1) } true }) }
identifier_body
string_pool.rs
use crate::expat_external_h::XML_Char; use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert}; use crate::lib::xmltok::{ENCODING, XML_Convert_Result}; use bumpalo::Bump; use bumpalo::collections::vec::Vec as BumpVec; use fallible_collections::FallibleBox; use libc::c_int; use std::cell::{Cell, RefCell}; use std::convert::TryInto; use std::mem::swap; pub const INIT_BLOCK_SIZE: usize = 1024; rental! { mod rental_pool { use super::*; #[rental(debug)] pub(crate) struct InnerStringPool { // The rental crate requires that all fields but the last one // implement `StableDeref`, which means we need to wrap it // in a `Box` bump: Box<Bump>, current_bump_vec: RefCell<RentedBumpVec<'bump>>, } } } use rental_pool::InnerStringPool; /// A StringPool has the purpose of allocating distinct strings and then /// handing them off to be referenced either temporarily or for the entire length /// of the pool. pub(crate) struct StringPool(Option<InnerStringPool>); impl StringPool { pub(crate) fn try_new() -> Result<Self, ()> { let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?; let boxed_bump = Box::try_new(bump).map_err(|_| ())?; Ok(StringPool(Some(InnerStringPool::new( boxed_bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )))) } /// # Safety /// /// The inner type is only ever None in middle of the clear() /// method. Therefore it is safe to use anywhere else. fn inner(&self) -> &InnerStringPool { self.0.as_ref().unwrap_or_else(|| unsafe { std::hint::unreachable_unchecked() }) } /// Determines whether or not the current BumpVec is empty. pub(crate) fn is_empty(&self) -> bool { self.inner().rent(|vec| vec.borrow().0.is_empty()) } /// Determines whether or not the current BumpVec is full. pub(crate) fn is_full(&self) -> bool { self.inner().rent(|vec| vec.borrow().is_full()) } /// Gets the current vec, converts it into an immutable slice, /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string(&self) -> &[XML_Char] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); pool.current_bump_vec.replace(vec).0.into_bump_slice() }) } /// Gets the current vec, converts it into a slice of cells (with interior mutability), /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string_cells(&self) -> &[Cell<XML_Char>] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); let sl = pool.current_bump_vec.replace(vec).0.into_bump_slice_mut(); Cell::from_mut(sl).as_slice_of_cells() }) } /// Resets the current bump vec to the beginning pub(crate) fn clear_current(&self) { self.inner().rent(|v| v.borrow_mut().0.clear()) } /// Obtains the length of the current BumpVec. pub(crate) fn len(&self) -> usize { self.inner().rent(|vec| vec.borrow().0.len()) } /// Call callback with an immutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&[XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow().0.as_slice())) } /// Call callback with a mutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_mut_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&mut [XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow_mut().0.as_mut_slice())) } /// Unsafe temporary version of `current_slice()`. This needs to be removed /// when callers are made safe. pub(crate) unsafe fn current_start(&self) -> *const XML_Char { self.inner().rent(|v| v.borrow().0.as_ptr()) } /// Appends a char to the current BumpVec. pub(crate) fn append_char(&self, c: XML_Char) -> bool { self.inner().rent(|vec| vec.borrow_mut().append_char(c)) } /// Overwrites the last char in the current BumpVec. /// Note that this will panic if empty. This is not an insert /// operation as it does not shift bytes afterwards. pub(crate) fn replace_last_char(&self, c: XML_Char) { self.inner().rent(|buf| { *buf.borrow_mut() .0 .last_mut() .expect("Called replace_last_char() when string was empty") = c; }) } /// Decrements the length, panicing if len is 0 pub(crate) fn backtrack(&self) { self.inner().rent(|vec| vec.borrow_mut().0.pop().expect("Called backtrack() on empty BumpVec")); } /// Gets the last character, panicing if len is 0 pub(crate) fn get_last_char(&self) -> XML_Char { self.inner().rent(|buf| *buf.borrow().0.last().expect("Called get_last_char() when string was empty")) } /// Appends an entire C String to the current BumpVec. pub(crate) unsafe fn append_c_string(&self, mut s: *const XML_Char) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); while *s!= 0 { if!vec.append_char(*s) { return false; } s = s.offset(1) } true }) } /// Resets the current Bump and deallocates its contents. /// The `inner` method must never be called here as it assumes /// self.0 is never `None` pub(crate) fn clear(&mut self) { let mut inner_pool = self.0.take(); let mut bump = inner_pool.unwrap().into_head(); bump.reset(); inner_pool = Some(InnerStringPool::new( bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )); swap(&mut self.0, &mut inner_pool); } pub(crate) fn store_c_string( &self, enc: &ENCODING, buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); if!vec.append(enc, buf) { return false; } if!vec.append_char('\0' as XML_Char) { return false; } true }) } pub(crate) fn append( &self, enc: &ENCODING, read_buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| vec.borrow_mut().append(enc, read_buf)) } pub(crate) unsafe fn copy_c_string( &self, mut s: *const XML_Char, ) -> Option<&[XML_Char]> { // self.append_c_string(s);? let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); loop { if!vec.append_char(*s) { return false; } if *s == 0 { break; } s = s.offset(1); } true }); if!successful { return None; } Some(self.finish_string()) } pub(crate) unsafe fn copy_c_string_n( &self, mut s: *const XML_Char, mut n: c_int, ) -> Option<&[XML_Char]> { let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); let mut n = n.try_into().unwrap(); if vec.0.try_reserve_exact(n).is_err() { return false; }; while n > 0 { if!vec.append_char(*s) { return false; } n -= 1; s = s.offset(1) } true }); if!successful { return None; } Some(self.finish_string()) } } #[derive(Debug)] pub(crate) struct RentedBumpVec<'bump>(BumpVec<'bump, XML_Char>); impl<'bump> RentedBumpVec<'bump> { fn is_full(&self) -> bool { self.0.len() == self.0.capacity() } fn append<'a>( &mut self, enc: &ENCODING, mut read_buf: ExpatBufRef<'a>, ) -> bool { loop { // REXPAT: always reserve at least 4 bytes, // so at least one character gets converted every iteration if self.0.try_reserve(read_buf.len().max(4)).is_err() { return false; } let start_len = self.0.len(); let cap = self.0.capacity(); self.0.resize(cap, 0); let mut write_buf = ExpatBufRefMut::from(&mut self.0[start_len..]); let write_buf_len = write_buf.len(); let convert_res = XmlConvert!(enc, &mut read_buf, &mut write_buf); // The write buf shrinks by how much was written to it let written_size = write_buf_len - write_buf.len(); self.0.truncate(start_len + written_size); if convert_res == XML_Convert_Result::COMPLETED || convert_res == XML_Convert_Result::INPUT_INCOMPLETE { return true; } } } fn append_char(&mut self, c: XML_Char) -> bool { if self.0.try_reserve(1).is_err() { false } else { self.0.push(c); true } } } #[cfg(test)] mod consts { use super::XML_Char; pub const A: XML_Char = 'a' as XML_Char; pub const B: XML_Char = 'b' as XML_Char; pub const C: XML_Char = 'c' as XML_Char; pub const D: XML_Char = 'd' as XML_Char; pub const NULL: XML_Char = '\0' as XML_Char; pub static S: [XML_Char; 5] = [C, D, D, C, NULL]; } #[test] fn test_append_char() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [A, B])); // New BumpVec pool.finish_string(); assert!(pool.append_char(C)); pool.current_slice(|s| assert_eq!(s, [C])); } #[test] fn test_append_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); let mut string = [A, B, C, NULL]; unsafe { assert!(pool.append_c_string(string.as_mut_ptr())); } pool.current_slice(|s| assert_eq!(s, [A, B, C])); } #[test] fn test_copy_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A]));
pool.copy_c_string(S.as_ptr()) }; assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [B])); let new_string2 = unsafe { pool.copy_c_string_n(S.as_ptr(), 4) }; assert_eq!(new_string2.unwrap(), [B, C, D, D, C]); } #[test] fn test_store_c_string() { use consts::*; use crate::lib::xmlparse::XmlGetInternalEncoding; let mut pool = StringPool::try_new().unwrap(); let enc = XmlGetInternalEncoding(); let read_buf = unsafe { ExpatBufRef::new(S.as_ptr(), S.as_ptr().add(3)) }; assert!(pool.store_c_string(enc, read_buf)); let string = pool.finish_string(); assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); // No overlap between buffers: assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A, A])); // Force reallocation: pool.inner().rent(|v| v.borrow_mut().0.resize(2, 0)); assert!(pool.store_c_string(enc, read_buf)); let s = pool.finish_string(); assert_eq!(s, [A, A, C, D, D, NULL]); }
let new_string = unsafe {
random_line_split
string_pool.rs
use crate::expat_external_h::XML_Char; use crate::lib::xmlparse::{ExpatBufRef, ExpatBufRefMut, XmlConvert}; use crate::lib::xmltok::{ENCODING, XML_Convert_Result}; use bumpalo::Bump; use bumpalo::collections::vec::Vec as BumpVec; use fallible_collections::FallibleBox; use libc::c_int; use std::cell::{Cell, RefCell}; use std::convert::TryInto; use std::mem::swap; pub const INIT_BLOCK_SIZE: usize = 1024; rental! { mod rental_pool { use super::*; #[rental(debug)] pub(crate) struct InnerStringPool { // The rental crate requires that all fields but the last one // implement `StableDeref`, which means we need to wrap it // in a `Box` bump: Box<Bump>, current_bump_vec: RefCell<RentedBumpVec<'bump>>, } } } use rental_pool::InnerStringPool; /// A StringPool has the purpose of allocating distinct strings and then /// handing them off to be referenced either temporarily or for the entire length /// of the pool. pub(crate) struct StringPool(Option<InnerStringPool>); impl StringPool { pub(crate) fn try_new() -> Result<Self, ()> { let bump = Bump::try_with_capacity(INIT_BLOCK_SIZE).map_err(|_| ())?; let boxed_bump = Box::try_new(bump).map_err(|_| ())?; Ok(StringPool(Some(InnerStringPool::new( boxed_bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )))) } /// # Safety /// /// The inner type is only ever None in middle of the clear() /// method. Therefore it is safe to use anywhere else. fn inner(&self) -> &InnerStringPool { self.0.as_ref().unwrap_or_else(|| unsafe { std::hint::unreachable_unchecked() }) } /// Determines whether or not the current BumpVec is empty. pub(crate) fn is_empty(&self) -> bool { self.inner().rent(|vec| vec.borrow().0.is_empty()) } /// Determines whether or not the current BumpVec is full. pub(crate) fn is_full(&self) -> bool { self.inner().rent(|vec| vec.borrow().is_full()) } /// Gets the current vec, converts it into an immutable slice, /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string(&self) -> &[XML_Char] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); pool.current_bump_vec.replace(vec).0.into_bump_slice() }) } /// Gets the current vec, converts it into a slice of cells (with interior mutability), /// and resets bookkeeping so that it will create a new vec next time. pub(crate) fn finish_string_cells(&self) -> &[Cell<XML_Char>] { self.inner().ref_rent_all(|pool| { let mut vec = RentedBumpVec(BumpVec::new_in(&pool.bump)); let sl = pool.current_bump_vec.replace(vec).0.into_bump_slice_mut(); Cell::from_mut(sl).as_slice_of_cells() }) } /// Resets the current bump vec to the beginning pub(crate) fn clear_current(&self) { self.inner().rent(|v| v.borrow_mut().0.clear()) } /// Obtains the length of the current BumpVec. pub(crate) fn len(&self) -> usize { self.inner().rent(|vec| vec.borrow().0.len()) } /// Call callback with an immutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&[XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow().0.as_slice())) } /// Call callback with a mutable buffer of the current BumpVec. This must /// be a callback to ensure that we don't (safely) borrow the slice for /// longer than it stays vaild. pub(crate) fn current_mut_slice<F, R>(&self, mut callback: F) -> R where F: FnMut(&mut [XML_Char]) -> R { self.inner().rent(|v| callback(v.borrow_mut().0.as_mut_slice())) } /// Unsafe temporary version of `current_slice()`. This needs to be removed /// when callers are made safe. pub(crate) unsafe fn current_start(&self) -> *const XML_Char { self.inner().rent(|v| v.borrow().0.as_ptr()) } /// Appends a char to the current BumpVec. pub(crate) fn append_char(&self, c: XML_Char) -> bool { self.inner().rent(|vec| vec.borrow_mut().append_char(c)) } /// Overwrites the last char in the current BumpVec. /// Note that this will panic if empty. This is not an insert /// operation as it does not shift bytes afterwards. pub(crate) fn replace_last_char(&self, c: XML_Char) { self.inner().rent(|buf| { *buf.borrow_mut() .0 .last_mut() .expect("Called replace_last_char() when string was empty") = c; }) } /// Decrements the length, panicing if len is 0 pub(crate) fn backtrack(&self) { self.inner().rent(|vec| vec.borrow_mut().0.pop().expect("Called backtrack() on empty BumpVec")); } /// Gets the last character, panicing if len is 0 pub(crate) fn get_last_char(&self) -> XML_Char { self.inner().rent(|buf| *buf.borrow().0.last().expect("Called get_last_char() when string was empty")) } /// Appends an entire C String to the current BumpVec. pub(crate) unsafe fn append_c_string(&self, mut s: *const XML_Char) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); while *s!= 0 { if!vec.append_char(*s)
s = s.offset(1) } true }) } /// Resets the current Bump and deallocates its contents. /// The `inner` method must never be called here as it assumes /// self.0 is never `None` pub(crate) fn clear(&mut self) { let mut inner_pool = self.0.take(); let mut bump = inner_pool.unwrap().into_head(); bump.reset(); inner_pool = Some(InnerStringPool::new( bump, |bump| RefCell::new(RentedBumpVec(BumpVec::new_in(&bump))), )); swap(&mut self.0, &mut inner_pool); } pub(crate) fn store_c_string( &self, enc: &ENCODING, buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); if!vec.append(enc, buf) { return false; } if!vec.append_char('\0' as XML_Char) { return false; } true }) } pub(crate) fn append( &self, enc: &ENCODING, read_buf: ExpatBufRef, ) -> bool { self.inner().rent(|vec| vec.borrow_mut().append(enc, read_buf)) } pub(crate) unsafe fn copy_c_string( &self, mut s: *const XML_Char, ) -> Option<&[XML_Char]> { // self.append_c_string(s);? let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); loop { if!vec.append_char(*s) { return false; } if *s == 0 { break; } s = s.offset(1); } true }); if!successful { return None; } Some(self.finish_string()) } pub(crate) unsafe fn copy_c_string_n( &self, mut s: *const XML_Char, mut n: c_int, ) -> Option<&[XML_Char]> { let successful = self.inner().rent(|vec| { let mut vec = vec.borrow_mut(); let mut n = n.try_into().unwrap(); if vec.0.try_reserve_exact(n).is_err() { return false; }; while n > 0 { if!vec.append_char(*s) { return false; } n -= 1; s = s.offset(1) } true }); if!successful { return None; } Some(self.finish_string()) } } #[derive(Debug)] pub(crate) struct RentedBumpVec<'bump>(BumpVec<'bump, XML_Char>); impl<'bump> RentedBumpVec<'bump> { fn is_full(&self) -> bool { self.0.len() == self.0.capacity() } fn append<'a>( &mut self, enc: &ENCODING, mut read_buf: ExpatBufRef<'a>, ) -> bool { loop { // REXPAT: always reserve at least 4 bytes, // so at least one character gets converted every iteration if self.0.try_reserve(read_buf.len().max(4)).is_err() { return false; } let start_len = self.0.len(); let cap = self.0.capacity(); self.0.resize(cap, 0); let mut write_buf = ExpatBufRefMut::from(&mut self.0[start_len..]); let write_buf_len = write_buf.len(); let convert_res = XmlConvert!(enc, &mut read_buf, &mut write_buf); // The write buf shrinks by how much was written to it let written_size = write_buf_len - write_buf.len(); self.0.truncate(start_len + written_size); if convert_res == XML_Convert_Result::COMPLETED || convert_res == XML_Convert_Result::INPUT_INCOMPLETE { return true; } } } fn append_char(&mut self, c: XML_Char) -> bool { if self.0.try_reserve(1).is_err() { false } else { self.0.push(c); true } } } #[cfg(test)] mod consts { use super::XML_Char; pub const A: XML_Char = 'a' as XML_Char; pub const B: XML_Char = 'b' as XML_Char; pub const C: XML_Char = 'c' as XML_Char; pub const D: XML_Char = 'd' as XML_Char; pub const NULL: XML_Char = '\0' as XML_Char; pub static S: [XML_Char; 5] = [C, D, D, C, NULL]; } #[test] fn test_append_char() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [A, B])); // New BumpVec pool.finish_string(); assert!(pool.append_char(C)); pool.current_slice(|s| assert_eq!(s, [C])); } #[test] fn test_append_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); let mut string = [A, B, C, NULL]; unsafe { assert!(pool.append_c_string(string.as_mut_ptr())); } pool.current_slice(|s| assert_eq!(s, [A, B, C])); } #[test] fn test_copy_string() { use consts::*; let mut pool = StringPool::try_new().unwrap(); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); let new_string = unsafe { pool.copy_c_string(S.as_ptr()) }; assert_eq!(new_string.unwrap(), [A, C, D, D, C, NULL]); assert!(pool.append_char(B)); pool.current_slice(|s| assert_eq!(s, [B])); let new_string2 = unsafe { pool.copy_c_string_n(S.as_ptr(), 4) }; assert_eq!(new_string2.unwrap(), [B, C, D, D, C]); } #[test] fn test_store_c_string() { use consts::*; use crate::lib::xmlparse::XmlGetInternalEncoding; let mut pool = StringPool::try_new().unwrap(); let enc = XmlGetInternalEncoding(); let read_buf = unsafe { ExpatBufRef::new(S.as_ptr(), S.as_ptr().add(3)) }; assert!(pool.store_c_string(enc, read_buf)); let string = pool.finish_string(); assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A])); // No overlap between buffers: assert_eq!(&*string, &[C, D, D, NULL]); assert!(pool.append_char(A)); pool.current_slice(|s| assert_eq!(s, [A, A])); // Force reallocation: pool.inner().rent(|v| v.borrow_mut().0.resize(2, 0)); assert!(pool.store_c_string(enc, read_buf)); let s = pool.finish_string(); assert_eq!(s, [A, A, C, D, D, NULL]); }
{ return false; }
conditional_block
lib.rs
//! A library for analysis of Boolean networks. As of now, the library supports: //! - Regulatory graphs with monotonicity and observability constraints. //! - Boolean networks, possibly with partially unknown and parametrised update functions. //! - Full SBML-qual support for import/export as well as custom string format `.aeon`. //! - Fully symbolic asynchronous state-space generator using BDDs (great overall performance). //! - Semi-symbolic state-space generator, using BDDs used only for the network parameters //! (allows state-level parallelism for smaller networks). //! //! For a quick introduction to Boolean networks and their symbolic manipulation, you can //! check out our [tutorial module](./tutorial/index.html). //! #[macro_use] extern crate lazy_static; extern crate core; use regex::Regex; use std::collections::HashMap; use std::iter::Map; use std::ops::Range; pub mod async_graph; pub mod bdd_params; pub mod biodivine_std; pub mod fixed_points; pub mod sbml; #[cfg(feature = "solver-z3")] pub mod solver_context; pub mod symbolic_async_graph; pub mod tutorial; /// **(internal)** Implements `.aeon` parser for `BooleanNetwork` and `RegulatoryGraph` objects. mod _aeon_parser; /// **(internal)** Methods for manipulating `ModelAnnotation` objects. mod _impl_annotations; /// **(internal)** Utility methods for `BinaryOp`. mod _impl_binary_op; /// **(internal)** Utility methods for `BooleanNetwork`. mod _impl_boolean_network; /// **(internal)** `BooleanNetwork` to `.aeon` string. mod _impl_boolean_network_display; /// **(internal)** Implements experimental `.bnet` parser for `BooleanNetwork`. mod _impl_boolean_network_from_bnet; /// **(internal)** Implements an experimental `.bnet` writer for `BooleanNetwork`. mod _impl_boolean_network_to_bnet; /// **(internal)** All methods implemented by the `ExtendedBoolean` object. mod _impl_extended_boolean; /// **(internal)** Utility methods for `FnUpdate`. mod _impl_fn_update; /// **(internal)** Utility methods for `Parameter`. mod _impl_parameter; /// **(internal)** Utility methods for `ParameterId`. mod _impl_parameter_id; /// **(internal)** Utility methods for `Regulation`. mod _impl_regulation; /// **(internal)** All methods for analysing and manipulating `RegulatoryGraph`. mod _impl_regulatory_graph; /// **(internal)** All methods implemented by the `Space` object. mod _impl_space; /// **(internal)** Utility methods for `Variable`. mod _impl_variable; /// **(internal)** Utility methods for `VariableId`. mod _impl_variable_id; // Re-export data structures used for advanced graph algorithms on `RegulatoryGraph`. pub use _impl_regulatory_graph::signed_directed_graph::SdGraph; pub use _impl_regulatory_graph::signed_directed_graph::Sign; /// **(internal)** A regex string of an identifier which we currently allow to appear /// as a variable or parameter name. const ID_REGEX_STR: &str = r"[a-zA-Z0-9_]+"; lazy_static! { /// A regular expression that matches the identifiers allowed as names of /// Boolean parameters or variables. static ref ID_REGEX: Regex = Regex::new(ID_REGEX_STR).unwrap(); } /// A type-safe index of a `Variable` inside a `RegulatoryGraph` (or a `BooleanNetwork`). /// /// If needed, it can be converted into `usize` for serialisation and safely read /// again by providing the original `RegulatoryGraph` as context /// to the `VariableId::try_from_usize`. /// /// **Warning:** Do not mix type-safe indices between different networks/graphs! #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct VariableId(usize); /// A type-safe index of a `Parameter` inside a `BooleanNetwork`. /// /// If needed, it can be converted into `usize` for serialisation and safely read /// again by providing the original `BooleanNetwork` as context /// to the `ParameterId::try_from_usize`. /// /// **Warning:** Do not mix type-safe indices between different networks! #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ParameterId(usize); /// Possible monotonous effects of a `Regulation` in a `RegulatoryGraph`. /// /// Activation means positive and inhibition means negative monotonicity. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Monotonicity { Activation, Inhibition, } /// A Boolean variable of a `RegulatoryGraph` (or a `BooleanNetwork`) with a given `name`. /// /// `Variable` can be only created by and borrowed from a `RegulatoryGraph`. /// It has no public constructor. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Variable { name: String, } /// An explicit parameter of a `BooleanNetwork`; an uninterpreted Boolean function with a given /// `name` and `arity`. /// /// `Parameter` can be only created by and borrowed form the `BooleanNetwork` itself. /// It has no public constructor. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct
{ name: String, arity: u32, } /// Describes an interaction between two `Variables` in a `RegulatoryGraph` /// (or a `BooleanNetwork`). /// /// Every regulation can be *monotonous*, and can be set as *observable*: /// /// - Monotonicity is either *positive* or *negative* and signifies that the influence of the /// `regulator` on the `target` has to *increase* or *decrease* the `target` value respectively. /// - If observability is set to `true`, the `regulator` *must* have influence on the outcome /// of the `target` update function in *some* context. If set to false, this is not enforced /// (i.e. the `regulator` *can* have an influence on the `target`, but it is not required). /// /// Regulations can be represented as strings in the /// form `"regulator_name'relationship' target_name"`. The'relationship' starts with `-`, which /// is followed by `>` for activation (positive monotonicity), `|` for inhibition (negative /// monotonicity) or `?` for unspecified monotonicity. Finally, an additional `?` at the end /// of'relationship' signifies a non-observable regulation. Together, this gives the /// following options: `->, ->?, -|, -|?, -?, -??`. /// /// Regulations cannot be created directly, they are only borrowed from a `RegulatoryGraph` /// or a `BooleanNetwork`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Regulation { regulator: VariableId, target: VariableId, observable: bool, monotonicity: Option<Monotonicity>, } /// A directed graph representing relationships between a collection of Boolean variables /// using `Regulations`. /// /// It can be explored using `regulators`, `targets`, `transitive_regulators`, or /// `transitive_targets` (for example to determine if two variables depend on each other). /// We can also compute the SCCs of this graph. /// /// A regulatory graph can be described using a custom string format. In this format, /// each line represents a regulation or a comment (starting with `#`). /// /// Regulations can be represented as strings in the form of /// `"regulator_name'relationship' target_name"`. The'relationship' is one of the arrow strings /// `->, ->?, -|, -|?, -?, -??`. Here, `>` means activation, `|` is inhibition and `?` is /// unspecified monotonicity. The last question mark signifies observability — if it is present, /// the regulation is not necessarily observable. See `Regulation` and tutorial module for a more /// detailed explanation. /// /// Example of a `RegulatoryGraph`: /// /// ```rg /// # Regulators of a /// a ->? a /// b -|? a /// /// # Regulators of b /// a -> b /// b -| b /// ``` #[derive(Clone, Debug)] pub struct RegulatoryGraph { variables: Vec<Variable>, regulations: Vec<Regulation>, variable_to_index: HashMap<String, VariableId>, } /// Possible binary Boolean operators that can appear in `FnUpdate`. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryOp { And, Or, Xor, Iff, Imp, } /// A Boolean update function formula which references /// `Variables` and `Parameters` of a `BooleanNetwork`. /// /// An update function specifies the evolution rules for one specific `Variable` of a /// `BooleanNetwork`. The arguments used in the function must be the same as specified /// by the `RegulatoryGraph` of the network. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum FnUpdate { /// A true/false constant. Const(bool), /// References a network variable. Var(VariableId), /// References a network parameter (uninterpreted function). /// /// The variable list are the arguments of the function invocation. Param(ParameterId, Vec<VariableId>), /// Negation. Not(Box<FnUpdate>), /// Binary boolean operation. Binary(BinaryOp, Box<FnUpdate>, Box<FnUpdate>), } /// A Boolean network, possibly parametrised with uninterpreted Boolean functions. /// /// The structure of the network is based on an underlying `RegulatoryGraph`. However, /// compared to a `RegulatoryGraph`, `BooleanNetwork` can have a specific update function /// given for each variable. /// /// If the function is not specified (so called *implicit parametrisation*), all admissible /// Boolean functions are considered in its place. A function can be also only partially /// specified by using declared *explicit parameters*. These are uninterpreted but named Boolean /// functions, such that, again, all admissible instantiations of these functions are considered. /// See crate tutorial to learn more. /// /// ### Boolean network equivalence /// /// Please keep in mind that we consider two networks to be equivalent when they share a regulatory /// graph, and when they have (syntactically) the same update functions and parameters. We do not /// perform any semantic checks for whether the update functions are functionally equivalent. /// /// Also keep in mind that the *ordering* of variables and parameters must be shared by equivalent /// networks. This is because we want to preserve the property that `VariableId` and `ParameterId` /// objects are interchangeable as log as networks are equivalent. #[derive(Clone, Debug, Eq, PartialEq)] pub struct BooleanNetwork { graph: RegulatoryGraph, parameters: Vec<Parameter>, update_functions: Vec<Option<FnUpdate>>, parameter_to_index: HashMap<String, ParameterId>, } /// An iterator over all `VariableIds` of a `RegulatoryGraph` (or a `BooleanNetwork`). pub type VariableIdIterator = Map<Range<usize>, fn(usize) -> VariableId>; /// An iterator over all `ParameterIds` of a `BooleanNetwork`. pub type ParameterIdIterator = Map<Range<usize>, fn(usize) -> ParameterId>; /// An iterator over all `Regulations` of a `RegulatoryGraph`. pub type RegulationIterator<'a> = std::slice::Iter<'a, Regulation>; /// An enum representing the possible state of each variable when describing a hypercube. #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub enum ExtendedBoolean { Zero, One, Any, } /// `Space` represents a hypercube (multi-dimensional rectangle) in the Boolean state space. /// /// Keep in mind that there is no way of representing an empty hypercube at the moment. So any API /// that can take/return an empty set has to use `Option<Space>` or something similar. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Space(Vec<ExtendedBoolean>); /// Annotations are "meta" objects that can be declared as part of AEON models to add additional /// properties that are not directly recognized by the main AEON toolbox. /// /// Annotations are comments which start with `#!`. After the `#!` "preamble", each annotation /// can contains a "path prefix" with path segments separated using `:` (path segments can be /// surrounded by white space that is automatically trimmed). Based on these path /// segments, the parser will create an annotation tree. If there are multiple annotations with /// the same path, their values are concatenated using newlines. /// /// For example, annotations can be used to describe model layout: /// /// ```text /// #! layout : var_1 : 10,20 /// #! layout : var_2 : 14,-3 /// ``` /// /// Another usage for annotations are extra properties enforced on the model behaviour, for /// example through CTL: /// ```test /// #! property : AG (problem => AF apoptosis) /// ``` /// /// Obviously, you can also use annotations to specify model metadata: /// ```text /// #! name: My Awesome Model /// #! description: This model describes... /// #! description:var_1: This variable describes... /// ``` /// /// You can use "empty" path (e.g. `#! is_multivalued`), and you can use an empty annotation /// value with a non-empty path (e.g. `#!is_multivalued:var_1:`). Though this is not particularly /// encouraged: it is better to just have `var_1` as the annotation value if you can do that. /// An exception to this may be a case where `is_multivalued:var_1:` has an "optional" value and /// you want to express that while the "key" is provided, but the "value" is missing. Similarly, for /// the sake of completeness, it is technically allowed to use empty path names (e.g. `a::b:value` /// translates to `["a", "", "b"] = "value"`), but it is discouraged. /// /// Note that the path segments should only contain alphanumeric characters and underscores, /// but can be escaped using backticks (`` ` ``; other backticks in path segments are not allowed). /// Similarly, annotation values cannot contain colons (path segment separators) or backticks, /// unless escaped with `` #`ACTUAL_STRING`# ``. You can also use escaping if you wish to /// retain whitespace around annotation values. As mentioned, multi-line values can be split /// into multiple annotation comments. #[derive(PartialEq, Eq, Clone)] pub struct ModelAnnotation { value: Option<String>, inner: HashMap<String, ModelAnnotation>, }
Parameter
identifier_name
lib.rs
//! A library for analysis of Boolean networks. As of now, the library supports: //! - Regulatory graphs with monotonicity and observability constraints. //! - Boolean networks, possibly with partially unknown and parametrised update functions. //! - Full SBML-qual support for import/export as well as custom string format `.aeon`. //! - Fully symbolic asynchronous state-space generator using BDDs (great overall performance). //! - Semi-symbolic state-space generator, using BDDs used only for the network parameters //! (allows state-level parallelism for smaller networks). //! //! For a quick introduction to Boolean networks and their symbolic manipulation, you can //! check out our [tutorial module](./tutorial/index.html). //! #[macro_use] extern crate lazy_static; extern crate core; use regex::Regex; use std::collections::HashMap; use std::iter::Map; use std::ops::Range; pub mod async_graph; pub mod bdd_params; pub mod biodivine_std; pub mod fixed_points; pub mod sbml; #[cfg(feature = "solver-z3")] pub mod solver_context; pub mod symbolic_async_graph; pub mod tutorial; /// **(internal)** Implements `.aeon` parser for `BooleanNetwork` and `RegulatoryGraph` objects. mod _aeon_parser; /// **(internal)** Methods for manipulating `ModelAnnotation` objects. mod _impl_annotations; /// **(internal)** Utility methods for `BinaryOp`. mod _impl_binary_op; /// **(internal)** Utility methods for `BooleanNetwork`. mod _impl_boolean_network; /// **(internal)** `BooleanNetwork` to `.aeon` string. mod _impl_boolean_network_display; /// **(internal)** Implements experimental `.bnet` parser for `BooleanNetwork`. mod _impl_boolean_network_from_bnet; /// **(internal)** Implements an experimental `.bnet` writer for `BooleanNetwork`. mod _impl_boolean_network_to_bnet; /// **(internal)** All methods implemented by the `ExtendedBoolean` object. mod _impl_extended_boolean; /// **(internal)** Utility methods for `FnUpdate`. mod _impl_fn_update; /// **(internal)** Utility methods for `Parameter`. mod _impl_parameter; /// **(internal)** Utility methods for `ParameterId`. mod _impl_parameter_id; /// **(internal)** Utility methods for `Regulation`. mod _impl_regulation; /// **(internal)** All methods for analysing and manipulating `RegulatoryGraph`. mod _impl_regulatory_graph; /// **(internal)** All methods implemented by the `Space` object. mod _impl_space; /// **(internal)** Utility methods for `Variable`. mod _impl_variable; /// **(internal)** Utility methods for `VariableId`. mod _impl_variable_id; // Re-export data structures used for advanced graph algorithms on `RegulatoryGraph`. pub use _impl_regulatory_graph::signed_directed_graph::SdGraph; pub use _impl_regulatory_graph::signed_directed_graph::Sign; /// **(internal)** A regex string of an identifier which we currently allow to appear /// as a variable or parameter name. const ID_REGEX_STR: &str = r"[a-zA-Z0-9_]+"; lazy_static! { /// A regular expression that matches the identifiers allowed as names of /// Boolean parameters or variables. static ref ID_REGEX: Regex = Regex::new(ID_REGEX_STR).unwrap(); } /// A type-safe index of a `Variable` inside a `RegulatoryGraph` (or a `BooleanNetwork`). /// /// If needed, it can be converted into `usize` for serialisation and safely read /// again by providing the original `RegulatoryGraph` as context /// to the `VariableId::try_from_usize`. /// /// **Warning:** Do not mix type-safe indices between different networks/graphs! #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct VariableId(usize); /// A type-safe index of a `Parameter` inside a `BooleanNetwork`. /// /// If needed, it can be converted into `usize` for serialisation and safely read /// again by providing the original `BooleanNetwork` as context /// to the `ParameterId::try_from_usize`. /// /// **Warning:** Do not mix type-safe indices between different networks! #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ParameterId(usize); /// Possible monotonous effects of a `Regulation` in a `RegulatoryGraph`. /// /// Activation means positive and inhibition means negative monotonicity. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Monotonicity { Activation, Inhibition, } /// A Boolean variable of a `RegulatoryGraph` (or a `BooleanNetwork`) with a given `name`. /// /// `Variable` can be only created by and borrowed from a `RegulatoryGraph`. /// It has no public constructor. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Variable { name: String, } /// An explicit parameter of a `BooleanNetwork`; an uninterpreted Boolean function with a given /// `name` and `arity`. /// /// `Parameter` can be only created by and borrowed form the `BooleanNetwork` itself. /// It has no public constructor. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Parameter { name: String, arity: u32, } /// Describes an interaction between two `Variables` in a `RegulatoryGraph` /// (or a `BooleanNetwork`). /// /// Every regulation can be *monotonous*, and can be set as *observable*: /// /// - Monotonicity is either *positive* or *negative* and signifies that the influence of the /// `regulator` on the `target` has to *increase* or *decrease* the `target` value respectively. /// - If observability is set to `true`, the `regulator` *must* have influence on the outcome /// of the `target` update function in *some* context. If set to false, this is not enforced /// (i.e. the `regulator` *can* have an influence on the `target`, but it is not required). /// /// Regulations can be represented as strings in the /// form `"regulator_name'relationship' target_name"`. The'relationship' starts with `-`, which /// is followed by `>` for activation (positive monotonicity), `|` for inhibition (negative /// monotonicity) or `?` for unspecified monotonicity. Finally, an additional `?` at the end /// of'relationship' signifies a non-observable regulation. Together, this gives the /// following options: `->, ->?, -|, -|?, -?, -??`. /// /// Regulations cannot be created directly, they are only borrowed from a `RegulatoryGraph` /// or a `BooleanNetwork`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Regulation { regulator: VariableId, target: VariableId, observable: bool, monotonicity: Option<Monotonicity>, } /// A directed graph representing relationships between a collection of Boolean variables /// using `Regulations`. /// /// It can be explored using `regulators`, `targets`, `transitive_regulators`, or /// `transitive_targets` (for example to determine if two variables depend on each other). /// We can also compute the SCCs of this graph. /// /// A regulatory graph can be described using a custom string format. In this format, /// each line represents a regulation or a comment (starting with `#`). /// /// Regulations can be represented as strings in the form of /// `"regulator_name'relationship' target_name"`. The'relationship' is one of the arrow strings /// `->, ->?, -|, -|?, -?, -??`. Here, `>` means activation, `|` is inhibition and `?` is /// unspecified monotonicity. The last question mark signifies observability — if it is present, /// the regulation is not necessarily observable. See `Regulation` and tutorial module for a more /// detailed explanation. /// /// Example of a `RegulatoryGraph`: /// /// ```rg /// # Regulators of a /// a ->? a /// b -|? a /// /// # Regulators of b /// a -> b /// b -| b /// ``` #[derive(Clone, Debug)] pub struct RegulatoryGraph { variables: Vec<Variable>, regulations: Vec<Regulation>, variable_to_index: HashMap<String, VariableId>, } /// Possible binary Boolean operators that can appear in `FnUpdate`. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryOp { And, Or, Xor, Iff, Imp, } /// A Boolean update function formula which references /// `Variables` and `Parameters` of a `BooleanNetwork`. /// /// An update function specifies the evolution rules for one specific `Variable` of a /// `BooleanNetwork`. The arguments used in the function must be the same as specified /// by the `RegulatoryGraph` of the network. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum FnUpdate { /// A true/false constant. Const(bool), /// References a network variable. Var(VariableId), /// References a network parameter (uninterpreted function). /// /// The variable list are the arguments of the function invocation. Param(ParameterId, Vec<VariableId>), /// Negation. Not(Box<FnUpdate>), /// Binary boolean operation. Binary(BinaryOp, Box<FnUpdate>, Box<FnUpdate>), } /// A Boolean network, possibly parametrised with uninterpreted Boolean functions. /// /// The structure of the network is based on an underlying `RegulatoryGraph`. However, /// compared to a `RegulatoryGraph`, `BooleanNetwork` can have a specific update function /// given for each variable. /// /// If the function is not specified (so called *implicit parametrisation*), all admissible /// Boolean functions are considered in its place. A function can be also only partially /// specified by using declared *explicit parameters*. These are uninterpreted but named Boolean /// functions, such that, again, all admissible instantiations of these functions are considered. /// See crate tutorial to learn more. /// /// ### Boolean network equivalence /// /// Please keep in mind that we consider two networks to be equivalent when they share a regulatory /// graph, and when they have (syntactically) the same update functions and parameters. We do not /// perform any semantic checks for whether the update functions are functionally equivalent. /// /// Also keep in mind that the *ordering* of variables and parameters must be shared by equivalent /// networks. This is because we want to preserve the property that `VariableId` and `ParameterId` /// objects are interchangeable as log as networks are equivalent. #[derive(Clone, Debug, Eq, PartialEq)] pub struct BooleanNetwork { graph: RegulatoryGraph, parameters: Vec<Parameter>, update_functions: Vec<Option<FnUpdate>>, parameter_to_index: HashMap<String, ParameterId>, } /// An iterator over all `VariableIds` of a `RegulatoryGraph` (or a `BooleanNetwork`). pub type VariableIdIterator = Map<Range<usize>, fn(usize) -> VariableId>; /// An iterator over all `ParameterIds` of a `BooleanNetwork`. pub type ParameterIdIterator = Map<Range<usize>, fn(usize) -> ParameterId>; /// An iterator over all `Regulations` of a `RegulatoryGraph`. pub type RegulationIterator<'a> = std::slice::Iter<'a, Regulation>; /// An enum representing the possible state of each variable when describing a hypercube. #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub enum ExtendedBoolean { Zero, One, Any, } /// `Space` represents a hypercube (multi-dimensional rectangle) in the Boolean state space. /// /// Keep in mind that there is no way of representing an empty hypercube at the moment. So any API /// that can take/return an empty set has to use `Option<Space>` or something similar. #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct Space(Vec<ExtendedBoolean>); /// Annotations are "meta" objects that can be declared as part of AEON models to add additional /// properties that are not directly recognized by the main AEON toolbox. /// /// Annotations are comments which start with `#!`. After the `#!` "preamble", each annotation /// can contains a "path prefix" with path segments separated using `:` (path segments can be /// surrounded by white space that is automatically trimmed). Based on these path /// segments, the parser will create an annotation tree. If there are multiple annotations with /// the same path, their values are concatenated using newlines. /// /// For example, annotations can be used to describe model layout: /// /// ```text /// #! layout : var_1 : 10,20 /// #! layout : var_2 : 14,-3 /// ``` /// /// Another usage for annotations are extra properties enforced on the model behaviour, for /// example through CTL: /// ```test /// #! property : AG (problem => AF apoptosis) /// ``` /// /// Obviously, you can also use annotations to specify model metadata: /// ```text /// #! name: My Awesome Model /// #! description: This model describes... /// #! description:var_1: This variable describes... /// ``` /// /// You can use "empty" path (e.g. `#! is_multivalued`), and you can use an empty annotation /// value with a non-empty path (e.g. `#!is_multivalued:var_1:`). Though this is not particularly /// encouraged: it is better to just have `var_1` as the annotation value if you can do that. /// An exception to this may be a case where `is_multivalued:var_1:` has an "optional" value and /// you want to express that while the "key" is provided, but the "value" is missing. Similarly, for /// the sake of completeness, it is technically allowed to use empty path names (e.g. `a::b:value` /// translates to `["a", "", "b"] = "value"`), but it is discouraged. /// /// Note that the path segments should only contain alphanumeric characters and underscores, /// but can be escaped using backticks (`` ` ``; other backticks in path segments are not allowed). /// Similarly, annotation values cannot contain colons (path segment separators) or backticks, /// unless escaped with `` #`ACTUAL_STRING`# ``. You can also use escaping if you wish to /// retain whitespace around annotation values. As mentioned, multi-line values can be split /// into multiple annotation comments. #[derive(PartialEq, Eq, Clone)]
pub struct ModelAnnotation { value: Option<String>, inner: HashMap<String, ModelAnnotation>, }
random_line_split
post_trees.rs
use std::collections::HashMap; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::generic::builder_rc::OperatorBuilder; use timely::dataflow::{Scope, Stream}; use colored::*; use crate::event::{Event, ID}; use crate::operators::active_posts::StatUpdate; use crate::operators::active_posts::StatUpdateType; use crate::operators::friend_recommendations::RecommendationUpdate; /// Given a stream of events, group them in connected components /// based on the root post id that they refer to. /// In other words, build the tree of events for each post. /// /// The operator emits 2 streams as output: /// 1) StatUpdates: will be fed into the `active_posts` operator /// that implements query 1 /// 2) RecommendationUpdates: will be fed into the `friend_recommendation` /// operator that implements query 2 /// /// In case of multiple workers, an upstream `exchange` operator /// will partition the events by root post id. Thus this operator /// will handle only a subset of the posts. /// /// "Reply to comments" events are broadcasted to all workers /// as they don't carry the root post id in the payload. /// /// When the `post_trees` operator receives an Reply event that /// cannot match to any currently received comment, it stores /// it in an out-of-order (ooo) queue. When the maximum bounded delay /// has expired, old events in the ooo queue are discarded /// (including events do not belong to the posts handled by this worker) /// pub trait PostTrees<G: Scope> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>); } impl<G: Scope<Timestamp = u64>> PostTrees<G> for Stream<G, Event> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>) { let mut state: PostTreesState = PostTreesState::new(worker_id); let mut builder = OperatorBuilder::new("PostTrees".to_owned(), self.scope()); let mut input = builder.new_input(self, Pipeline); // declare two output streams, one for each downstream operator let (mut stat_output, stat_stream) = builder.new_output(); let (mut rec_output, rec_stream) = builder.new_output(); builder.build(move |_| { let mut buf = Vec::new(); move |_frontiers| { input.for_each(|time, data| { data.swap(&mut buf); for event in buf.drain(..) { // update the post trees let (opt_target_id, opt_root_post_id) = state.update_post_tree(&event); // check if the root post_id has been already received match opt_root_post_id { Some(root_post_id) => { if let ID::Post(pid) = root_post_id { state.append_output_updates(&event, pid); } else { panic!("expect ID::Post, got ID::Comment"); } // check whether we can pop some stuff out of the ooo map if let Some(_) = event.id() { state.process_ooo_events(&event); } } None => { state.push_ooo_event(event, opt_target_id.unwrap()); } }; // state.dump(); } let mut stat_handle = stat_output.activate(); let mut rec_handle = rec_output.activate(); let mut stat_session = stat_handle.session(&time); let mut rec_session = rec_handle.session(&time); // emit stat updates as output for stat_update in state.pending_stat_updates.drain(..) { stat_session.give(stat_update); } // emit recommendation updates as output for rec_update in state.pending_rec_updates.drain(..) { rec_session.give(rec_update); } // check we if we can clean some old events from the ooo queue state.clean_ooo_events(*time.time()); }); } }); // return the two output streams (stat_stream, rec_stream) } } #[derive(Debug)] struct Node { person_id: u64, // "creator" of the event root_post_id: ID, } /// State associated with the `post_trees` operator struct PostTreesState { worker_id: usize, // event ID --> post ID it refers to (root of the tree) root_of: HashMap<ID, Node>, // out-of-order events: id of missing event --> event that depends on it ooo_events: HashMap<ID, Vec<Event>>, // updates to be sent on the stat output stream pending_stat_updates: Vec<StatUpdate>, // updates to be sent on the recommendation output stream pending_rec_updates: Vec<RecommendationUpdate>, } impl PostTreesState { fn new(worker_id: usize) -> PostTreesState { PostTreesState { worker_id: worker_id, root_of: HashMap::<ID, Node>::new(), ooo_events: HashMap::<ID, Vec<Event>>::new(), pending_stat_updates: Vec::new(), pending_rec_updates: Vec::new(), } } /// given an event, try to match it to some post tree fn update_post_tree(&mut self, event: &Event) -> (Option<ID>, Option<ID>) { match event { Event::Post(post) => { let node = Node { person_id: post.person_id, root_post_id: post.post_id }; self.root_of.insert(post.post_id, node); (None, Some(post.post_id)) } Event::Like(like) => { // likes are not stored in the tree let post_id = match self.root_of.get(&like.post_id) { Some(_) => Some(like.post_id), // can only like a post None => None, }; (Some(like.post_id), post_id) } Event::Comment(comment) => { let reply_to_id = comment.reply_to_post_id.or(comment.reply_to_comment_id).unwrap(); if let Some(root_node) = self.root_of.get(&reply_to_id) { let root_post_id = root_node.root_post_id; let node = Node { person_id: comment.person_id, root_post_id: root_post_id }; self.root_of.insert(comment.comment_id, node); (Some(reply_to_id), Some(root_post_id)) } else { (Some(reply_to_id), None) } } } } /// process events that have `root_event` as their target post, /// recursively process the newly inserted events fn process_ooo_events(&mut self, root_event: &Event) { let id = root_event.id().unwrap(); if let Some(events) = self.ooo_events.remove(&id) { println!("-- {} for id = {:?}", "process_ooo_events".bold().yellow(), id); let mut new_events = Vec::new(); for event in events { let (opt_target_id, opt_root_post_id) = self.update_post_tree(&event); assert!(opt_target_id.unwrap() == id, "wtf"); let root_post_id = opt_root_post_id.expect("[process_ooo_events] root_post_id is None"); // only use this event if its timestamp is greater or equal to the parent's. if event.timestamp() >= root_event.timestamp() { self.append_output_updates(&event, root_post_id.u64()); if let Some(_) = event.id() { new_events.push(event); } } } // adding events might unlock other ooo events for event in new_events.drain(..) { self.process_ooo_events(&event); } } } /// insert an event into the out-of-order queue fn push_ooo_event(&mut self, event: Event, target_id: ID) { self.ooo_events.entry(target_id).or_insert(Vec::new()).push(event); } /// remove all old events from the out-of-order queue /// (including Reply events there were not meant to be received by this worker) fn clean_ooo_events(&mut self, timestamp: u64) { self.ooo_events = self .ooo_events .clone() .into_iter() .filter(|(_, events)| events.iter().all(|event| event.timestamp() > timestamp)) .collect::<HashMap<_, _>>(); } /// generate all output updates for the current event fn append_output_updates(&mut self, event: &Event, root_post_id: u64) { self.append_stat_update(&event, root_post_id); self.append_rec_update(&event, root_post_id); } /// given an event (and the current state of the post trees), /// generate a new stat update and append it to the pending list fn append_stat_update(&mut self, event: &Event, root_post_id: u64) { let update_type = match event { Event::Post(_) => StatUpdateType::Post, Event::Like(_) => StatUpdateType::Like, Event::Comment(comment) => { if comment.reply_to_post_id!= None { StatUpdateType::Comment } else { StatUpdateType::Reply } } }; let update = StatUpdate { update_type: update_type, post_id: root_post_id, person_id: event.person_id(), timestamp: event.timestamp(), }; self.pending_stat_updates.push(update); } /// given an event (and the current state of the post trees), /// generate a new recommendation update and append it to the pending list fn append_rec_update(&mut self, event: &Event, root_post_id: u64) { if let Event::Post(post) = event { // a new post with some tags has been created into a forum let update = RecommendationUpdate::Post { timestamp: event.timestamp(), person_id: event.person_id(), forum_id: post.forum_id, tags: post.tags.clone(), }; self.pending_rec_updates.push(update) } else if let Event::Comment(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Comment { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } else if let Event::Like(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Like { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } } #[allow(dead_code)] fn dump(&self) { println!( "{}", format!( "{} {}", format!("[W{}]", self.worker_id).bold().blue(), "Current state".bold().blue() ) ); println!(" root_of -- {:?}", self.root_of); self.dump_ooo_events(2); } fn
(&self, num_spaces: usize) { let spaces = " ".repeat(num_spaces); println!("{}---- ooo_events", spaces); for (post_id, events) in self.ooo_events.iter() { println!( "{}{:?} -- \n{} {}", spaces, post_id, spaces, events .iter() .map(|e| e.to_string()) .collect::<Vec<_>>() .join(&format!("\n{} ", spaces)) ); } println!("{}----", spaces); } }
dump_ooo_events
identifier_name
post_trees.rs
use std::collections::HashMap; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::generic::builder_rc::OperatorBuilder; use timely::dataflow::{Scope, Stream}; use colored::*; use crate::event::{Event, ID}; use crate::operators::active_posts::StatUpdate; use crate::operators::active_posts::StatUpdateType; use crate::operators::friend_recommendations::RecommendationUpdate; /// Given a stream of events, group them in connected components /// based on the root post id that they refer to. /// In other words, build the tree of events for each post. /// /// The operator emits 2 streams as output: /// 1) StatUpdates: will be fed into the `active_posts` operator /// that implements query 1 /// 2) RecommendationUpdates: will be fed into the `friend_recommendation` /// operator that implements query 2 /// /// In case of multiple workers, an upstream `exchange` operator /// will partition the events by root post id. Thus this operator /// will handle only a subset of the posts. /// /// "Reply to comments" events are broadcasted to all workers /// as they don't carry the root post id in the payload. /// /// When the `post_trees` operator receives an Reply event that /// cannot match to any currently received comment, it stores /// it in an out-of-order (ooo) queue. When the maximum bounded delay /// has expired, old events in the ooo queue are discarded /// (including events do not belong to the posts handled by this worker) /// pub trait PostTrees<G: Scope> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>); } impl<G: Scope<Timestamp = u64>> PostTrees<G> for Stream<G, Event> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>) { let mut state: PostTreesState = PostTreesState::new(worker_id); let mut builder = OperatorBuilder::new("PostTrees".to_owned(), self.scope()); let mut input = builder.new_input(self, Pipeline); // declare two output streams, one for each downstream operator let (mut stat_output, stat_stream) = builder.new_output(); let (mut rec_output, rec_stream) = builder.new_output(); builder.build(move |_| { let mut buf = Vec::new(); move |_frontiers| { input.for_each(|time, data| { data.swap(&mut buf); for event in buf.drain(..) { // update the post trees let (opt_target_id, opt_root_post_id) = state.update_post_tree(&event); // check if the root post_id has been already received match opt_root_post_id { Some(root_post_id) => { if let ID::Post(pid) = root_post_id { state.append_output_updates(&event, pid); } else { panic!("expect ID::Post, got ID::Comment"); } // check whether we can pop some stuff out of the ooo map if let Some(_) = event.id() { state.process_ooo_events(&event); } } None => { state.push_ooo_event(event, opt_target_id.unwrap()); } }; // state.dump(); } let mut stat_handle = stat_output.activate(); let mut rec_handle = rec_output.activate(); let mut stat_session = stat_handle.session(&time); let mut rec_session = rec_handle.session(&time); // emit stat updates as output for stat_update in state.pending_stat_updates.drain(..) { stat_session.give(stat_update); } // emit recommendation updates as output for rec_update in state.pending_rec_updates.drain(..) { rec_session.give(rec_update); } // check we if we can clean some old events from the ooo queue state.clean_ooo_events(*time.time()); }); } }); // return the two output streams (stat_stream, rec_stream) } } #[derive(Debug)] struct Node { person_id: u64, // "creator" of the event root_post_id: ID, } /// State associated with the `post_trees` operator struct PostTreesState { worker_id: usize, // event ID --> post ID it refers to (root of the tree) root_of: HashMap<ID, Node>, // out-of-order events: id of missing event --> event that depends on it ooo_events: HashMap<ID, Vec<Event>>, // updates to be sent on the stat output stream pending_stat_updates: Vec<StatUpdate>, // updates to be sent on the recommendation output stream pending_rec_updates: Vec<RecommendationUpdate>, } impl PostTreesState { fn new(worker_id: usize) -> PostTreesState { PostTreesState { worker_id: worker_id, root_of: HashMap::<ID, Node>::new(), ooo_events: HashMap::<ID, Vec<Event>>::new(), pending_stat_updates: Vec::new(), pending_rec_updates: Vec::new(), } } /// given an event, try to match it to some post tree fn update_post_tree(&mut self, event: &Event) -> (Option<ID>, Option<ID>)
let node = Node { person_id: comment.person_id, root_post_id: root_post_id }; self.root_of.insert(comment.comment_id, node); (Some(reply_to_id), Some(root_post_id)) } else { (Some(reply_to_id), None) } } } } /// process events that have `root_event` as their target post, /// recursively process the newly inserted events fn process_ooo_events(&mut self, root_event: &Event) { let id = root_event.id().unwrap(); if let Some(events) = self.ooo_events.remove(&id) { println!("-- {} for id = {:?}", "process_ooo_events".bold().yellow(), id); let mut new_events = Vec::new(); for event in events { let (opt_target_id, opt_root_post_id) = self.update_post_tree(&event); assert!(opt_target_id.unwrap() == id, "wtf"); let root_post_id = opt_root_post_id.expect("[process_ooo_events] root_post_id is None"); // only use this event if its timestamp is greater or equal to the parent's. if event.timestamp() >= root_event.timestamp() { self.append_output_updates(&event, root_post_id.u64()); if let Some(_) = event.id() { new_events.push(event); } } } // adding events might unlock other ooo events for event in new_events.drain(..) { self.process_ooo_events(&event); } } } /// insert an event into the out-of-order queue fn push_ooo_event(&mut self, event: Event, target_id: ID) { self.ooo_events.entry(target_id).or_insert(Vec::new()).push(event); } /// remove all old events from the out-of-order queue /// (including Reply events there were not meant to be received by this worker) fn clean_ooo_events(&mut self, timestamp: u64) { self.ooo_events = self .ooo_events .clone() .into_iter() .filter(|(_, events)| events.iter().all(|event| event.timestamp() > timestamp)) .collect::<HashMap<_, _>>(); } /// generate all output updates for the current event fn append_output_updates(&mut self, event: &Event, root_post_id: u64) { self.append_stat_update(&event, root_post_id); self.append_rec_update(&event, root_post_id); } /// given an event (and the current state of the post trees), /// generate a new stat update and append it to the pending list fn append_stat_update(&mut self, event: &Event, root_post_id: u64) { let update_type = match event { Event::Post(_) => StatUpdateType::Post, Event::Like(_) => StatUpdateType::Like, Event::Comment(comment) => { if comment.reply_to_post_id!= None { StatUpdateType::Comment } else { StatUpdateType::Reply } } }; let update = StatUpdate { update_type: update_type, post_id: root_post_id, person_id: event.person_id(), timestamp: event.timestamp(), }; self.pending_stat_updates.push(update); } /// given an event (and the current state of the post trees), /// generate a new recommendation update and append it to the pending list fn append_rec_update(&mut self, event: &Event, root_post_id: u64) { if let Event::Post(post) = event { // a new post with some tags has been created into a forum let update = RecommendationUpdate::Post { timestamp: event.timestamp(), person_id: event.person_id(), forum_id: post.forum_id, tags: post.tags.clone(), }; self.pending_rec_updates.push(update) } else if let Event::Comment(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Comment { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } else if let Event::Like(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Like { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } } #[allow(dead_code)] fn dump(&self) { println!( "{}", format!( "{} {}", format!("[W{}]", self.worker_id).bold().blue(), "Current state".bold().blue() ) ); println!(" root_of -- {:?}", self.root_of); self.dump_ooo_events(2); } fn dump_ooo_events(&self, num_spaces: usize) { let spaces = " ".repeat(num_spaces); println!("{}---- ooo_events", spaces); for (post_id, events) in self.ooo_events.iter() { println!( "{}{:?} -- \n{} {}", spaces, post_id, spaces, events .iter() .map(|e| e.to_string()) .collect::<Vec<_>>() .join(&format!("\n{} ", spaces)) ); } println!("{}----", spaces); } }
{ match event { Event::Post(post) => { let node = Node { person_id: post.person_id, root_post_id: post.post_id }; self.root_of.insert(post.post_id, node); (None, Some(post.post_id)) } Event::Like(like) => { // likes are not stored in the tree let post_id = match self.root_of.get(&like.post_id) { Some(_) => Some(like.post_id), // can only like a post None => None, }; (Some(like.post_id), post_id) } Event::Comment(comment) => { let reply_to_id = comment.reply_to_post_id.or(comment.reply_to_comment_id).unwrap(); if let Some(root_node) = self.root_of.get(&reply_to_id) { let root_post_id = root_node.root_post_id;
identifier_body
post_trees.rs
use std::collections::HashMap; use timely::dataflow::channels::pact::Pipeline; use timely::dataflow::operators::generic::builder_rc::OperatorBuilder; use timely::dataflow::{Scope, Stream}; use colored::*; use crate::event::{Event, ID}; use crate::operators::active_posts::StatUpdate; use crate::operators::active_posts::StatUpdateType; use crate::operators::friend_recommendations::RecommendationUpdate; /// Given a stream of events, group them in connected components /// based on the root post id that they refer to. /// In other words, build the tree of events for each post. /// /// The operator emits 2 streams as output: /// 1) StatUpdates: will be fed into the `active_posts` operator /// that implements query 1 /// 2) RecommendationUpdates: will be fed into the `friend_recommendation` /// operator that implements query 2 ///
/// will handle only a subset of the posts. /// /// "Reply to comments" events are broadcasted to all workers /// as they don't carry the root post id in the payload. /// /// When the `post_trees` operator receives an Reply event that /// cannot match to any currently received comment, it stores /// it in an out-of-order (ooo) queue. When the maximum bounded delay /// has expired, old events in the ooo queue are discarded /// (including events do not belong to the posts handled by this worker) /// pub trait PostTrees<G: Scope> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>); } impl<G: Scope<Timestamp = u64>> PostTrees<G> for Stream<G, Event> { fn post_trees( &self, worker_id: usize, ) -> (Stream<G, StatUpdate>, Stream<G, RecommendationUpdate>) { let mut state: PostTreesState = PostTreesState::new(worker_id); let mut builder = OperatorBuilder::new("PostTrees".to_owned(), self.scope()); let mut input = builder.new_input(self, Pipeline); // declare two output streams, one for each downstream operator let (mut stat_output, stat_stream) = builder.new_output(); let (mut rec_output, rec_stream) = builder.new_output(); builder.build(move |_| { let mut buf = Vec::new(); move |_frontiers| { input.for_each(|time, data| { data.swap(&mut buf); for event in buf.drain(..) { // update the post trees let (opt_target_id, opt_root_post_id) = state.update_post_tree(&event); // check if the root post_id has been already received match opt_root_post_id { Some(root_post_id) => { if let ID::Post(pid) = root_post_id { state.append_output_updates(&event, pid); } else { panic!("expect ID::Post, got ID::Comment"); } // check whether we can pop some stuff out of the ooo map if let Some(_) = event.id() { state.process_ooo_events(&event); } } None => { state.push_ooo_event(event, opt_target_id.unwrap()); } }; // state.dump(); } let mut stat_handle = stat_output.activate(); let mut rec_handle = rec_output.activate(); let mut stat_session = stat_handle.session(&time); let mut rec_session = rec_handle.session(&time); // emit stat updates as output for stat_update in state.pending_stat_updates.drain(..) { stat_session.give(stat_update); } // emit recommendation updates as output for rec_update in state.pending_rec_updates.drain(..) { rec_session.give(rec_update); } // check we if we can clean some old events from the ooo queue state.clean_ooo_events(*time.time()); }); } }); // return the two output streams (stat_stream, rec_stream) } } #[derive(Debug)] struct Node { person_id: u64, // "creator" of the event root_post_id: ID, } /// State associated with the `post_trees` operator struct PostTreesState { worker_id: usize, // event ID --> post ID it refers to (root of the tree) root_of: HashMap<ID, Node>, // out-of-order events: id of missing event --> event that depends on it ooo_events: HashMap<ID, Vec<Event>>, // updates to be sent on the stat output stream pending_stat_updates: Vec<StatUpdate>, // updates to be sent on the recommendation output stream pending_rec_updates: Vec<RecommendationUpdate>, } impl PostTreesState { fn new(worker_id: usize) -> PostTreesState { PostTreesState { worker_id: worker_id, root_of: HashMap::<ID, Node>::new(), ooo_events: HashMap::<ID, Vec<Event>>::new(), pending_stat_updates: Vec::new(), pending_rec_updates: Vec::new(), } } /// given an event, try to match it to some post tree fn update_post_tree(&mut self, event: &Event) -> (Option<ID>, Option<ID>) { match event { Event::Post(post) => { let node = Node { person_id: post.person_id, root_post_id: post.post_id }; self.root_of.insert(post.post_id, node); (None, Some(post.post_id)) } Event::Like(like) => { // likes are not stored in the tree let post_id = match self.root_of.get(&like.post_id) { Some(_) => Some(like.post_id), // can only like a post None => None, }; (Some(like.post_id), post_id) } Event::Comment(comment) => { let reply_to_id = comment.reply_to_post_id.or(comment.reply_to_comment_id).unwrap(); if let Some(root_node) = self.root_of.get(&reply_to_id) { let root_post_id = root_node.root_post_id; let node = Node { person_id: comment.person_id, root_post_id: root_post_id }; self.root_of.insert(comment.comment_id, node); (Some(reply_to_id), Some(root_post_id)) } else { (Some(reply_to_id), None) } } } } /// process events that have `root_event` as their target post, /// recursively process the newly inserted events fn process_ooo_events(&mut self, root_event: &Event) { let id = root_event.id().unwrap(); if let Some(events) = self.ooo_events.remove(&id) { println!("-- {} for id = {:?}", "process_ooo_events".bold().yellow(), id); let mut new_events = Vec::new(); for event in events { let (opt_target_id, opt_root_post_id) = self.update_post_tree(&event); assert!(opt_target_id.unwrap() == id, "wtf"); let root_post_id = opt_root_post_id.expect("[process_ooo_events] root_post_id is None"); // only use this event if its timestamp is greater or equal to the parent's. if event.timestamp() >= root_event.timestamp() { self.append_output_updates(&event, root_post_id.u64()); if let Some(_) = event.id() { new_events.push(event); } } } // adding events might unlock other ooo events for event in new_events.drain(..) { self.process_ooo_events(&event); } } } /// insert an event into the out-of-order queue fn push_ooo_event(&mut self, event: Event, target_id: ID) { self.ooo_events.entry(target_id).or_insert(Vec::new()).push(event); } /// remove all old events from the out-of-order queue /// (including Reply events there were not meant to be received by this worker) fn clean_ooo_events(&mut self, timestamp: u64) { self.ooo_events = self .ooo_events .clone() .into_iter() .filter(|(_, events)| events.iter().all(|event| event.timestamp() > timestamp)) .collect::<HashMap<_, _>>(); } /// generate all output updates for the current event fn append_output_updates(&mut self, event: &Event, root_post_id: u64) { self.append_stat_update(&event, root_post_id); self.append_rec_update(&event, root_post_id); } /// given an event (and the current state of the post trees), /// generate a new stat update and append it to the pending list fn append_stat_update(&mut self, event: &Event, root_post_id: u64) { let update_type = match event { Event::Post(_) => StatUpdateType::Post, Event::Like(_) => StatUpdateType::Like, Event::Comment(comment) => { if comment.reply_to_post_id!= None { StatUpdateType::Comment } else { StatUpdateType::Reply } } }; let update = StatUpdate { update_type: update_type, post_id: root_post_id, person_id: event.person_id(), timestamp: event.timestamp(), }; self.pending_stat_updates.push(update); } /// given an event (and the current state of the post trees), /// generate a new recommendation update and append it to the pending list fn append_rec_update(&mut self, event: &Event, root_post_id: u64) { if let Event::Post(post) = event { // a new post with some tags has been created into a forum let update = RecommendationUpdate::Post { timestamp: event.timestamp(), person_id: event.person_id(), forum_id: post.forum_id, tags: post.tags.clone(), }; self.pending_rec_updates.push(update) } else if let Event::Comment(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Comment { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } else if let Event::Like(_) = event { let to_person_id = self.root_of.get(&ID::Post(root_post_id)).unwrap().person_id; let update = RecommendationUpdate::Like { timestamp: event.timestamp(), from_person_id: event.person_id(), to_person_id: to_person_id, }; self.pending_rec_updates.push(update) } } #[allow(dead_code)] fn dump(&self) { println!( "{}", format!( "{} {}", format!("[W{}]", self.worker_id).bold().blue(), "Current state".bold().blue() ) ); println!(" root_of -- {:?}", self.root_of); self.dump_ooo_events(2); } fn dump_ooo_events(&self, num_spaces: usize) { let spaces = " ".repeat(num_spaces); println!("{}---- ooo_events", spaces); for (post_id, events) in self.ooo_events.iter() { println!( "{}{:?} -- \n{} {}", spaces, post_id, spaces, events .iter() .map(|e| e.to_string()) .collect::<Vec<_>>() .join(&format!("\n{} ", spaces)) ); } println!("{}----", spaces); } }
/// In case of multiple workers, an upstream `exchange` operator /// will partition the events by root post id. Thus this operator
random_line_split
worker.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::pin::Pin; use std::rc::Rc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::task::Context; use std::task::Poll; use deno_broadcast_channel::InMemoryBroadcastChannel; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::ascii_str; use deno_core::error::AnyError; use deno_core::error::JsError; use deno_core::futures::Future; use deno_core::v8; use deno_core::CompiledWasmModuleStore; use deno_core::Extension; use deno_core::FsModuleLoader; use deno_core::GetErrorClassFn; use deno_core::JsRuntime; use deno_core::LocalInspectorSession; use deno_core::ModuleCode; use deno_core::ModuleId; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::Snapshot; use deno_core::SourceMapGetter; use deno_fs::FileSystem; use deno_http::DefaultHttpPropertyExtractor; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_node::SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX; use deno_tls::RootCertStoreProvider; use deno_web::BlobStore; use log::debug; use crate::inspector_server::InspectorServer; use crate::ops; use crate::permissions::PermissionsContainer; use crate::shared::runtime; use crate::BootstrapOptions; pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send; #[derive(Clone, Default)] pub struct ExitCode(Arc<AtomicI32>); impl ExitCode { pub fn get(&self) -> i32 { self.0.load(Relaxed) } pub fn set(&mut self, code: i32) { self.0.store(code, Relaxed); } } /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in the `Deno` namespace. /// /// All `WebWorker`s created during program execution /// are descendants of this worker. pub struct MainWorker { pub js_runtime: JsRuntime, should_break_on_first_statement: bool, should_wait_for_inspector_session: bool, exit_code: ExitCode, bootstrap_fn_global: Option<v8::Global<v8::Function>>, } pub struct WorkerOptions { pub bootstrap: BootstrapOptions, /// JsRuntime extensions, not to be confused with ES modules. /// /// Extensions register "ops" and JavaScript sources provided in `js` or `esm` /// configuration. If you are using a snapshot, then extensions shouldn't /// provide JavaScript sources that were already snapshotted. pub extensions: Vec<Extension>, /// V8 snapshot that should be loaded on startup. pub startup_snapshot: Option<Snapshot>, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub seed: Option<u64>, pub fs: Arc<dyn FileSystem>, /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules. /// /// If not provided runtime will error if code being /// executed tries to load modules. pub module_loader: Rc<dyn ModuleLoader>, pub npm_resolver: Option<Arc<dyn deno_node::NpmResolver>>, // Callbacks invoked when creating new instance of WebWorker pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, /// Source map reference for errors. pub source_map_getter: Option<Box<dyn SourceMapGetter>>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, // If true, the worker will wait for inspector session and break on first // statement of user code. Takes higher precedence than // `should_wait_for_inspector_session`. pub should_break_on_first_statement: bool, // If true, the worker will wait for inspector session before executing // user code. pub should_wait_for_inspector_session: bool, /// Allows to map error type to a string "class" used to represent /// error in JavaScript. pub get_error_class_fn: Option<GetErrorClassFn>, pub cache_storage_dir: Option<std::path::PathBuf>, pub origin_storage_dir: Option<std::path::PathBuf>, pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, /// The store to use for transferring SharedArrayBuffers between isolates. /// If multiple isolates should have the possibility of sharing /// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If /// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be /// serialized. pub shared_array_buffer_store: Option<SharedArrayBufferStore>, /// The store to use for transferring `WebAssembly.Module` objects between /// isolates. /// If multiple isolates should have the possibility of sharing /// `WebAssembly.Module` objects, they should use the same /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, pub stdio: Stdio, } impl Default for WorkerOptions { fn default() -> Self { Self { create_web_worker_cb: Arc::new(|_| { unimplemented!("web workers are not supported") }), fs: Arc::new(deno_fs::RealFs), module_loader: Rc::new(FsModuleLoader), seed: None, unsafely_ignore_certificate_errors: Default::default(), should_break_on_first_statement: Default::default(), should_wait_for_inspector_session: Default::default(), compiled_wasm_module_store: Default::default(), shared_array_buffer_store: Default::default(), maybe_inspector_server: Default::default(), format_js_error_fn: Default::default(), get_error_class_fn: Default::default(), origin_storage_dir: Default::default(), cache_storage_dir: Default::default(), broadcast_channel: Default::default(), source_map_getter: Default::default(), root_cert_store_provider: Default::default(), npm_resolver: Default::default(), blob_store: Default::default(), extensions: Default::default(), startup_snapshot: Default::default(), create_params: Default::default(), bootstrap: Default::default(), stdio: Default::default(), } } } impl MainWorker { pub fn bootstrap_from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, options: WorkerOptions, ) -> Self { let bootstrap_options = options.bootstrap.clone(); let mut worker = Self::from_options(main_module, permissions, options); worker.bootstrap(&bootstrap_options); worker } pub fn from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, mut options: WorkerOptions, ) -> Self { deno_core::extension!(deno_permissions_worker, options = { permissions: PermissionsContainer, unstable: bool, enable_testing_features: bool, }, state = |state, options| { state.put::<PermissionsContainer>(options.permissions); state.put(ops::UnstableChecker { unstable: options.unstable }); state.put(ops::TestingFeaturesEnabled(options.enable_testing_features)); }, ); // Permissions: many ops depend on this let unstable = options.bootstrap.unstable; let enable_testing_features = options.bootstrap.enable_testing_features; let exit_code = ExitCode(Arc::new(AtomicI32::new(0))); let create_cache = options.cache_storage_dir.map(|storage_dir| { let create_cache_fn = move || SqliteBackedCache::new(storage_dir.clone()); CreateCache(Arc::new(create_cache_fn)) }); // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/build.rs`, `runtime/web_worker.rs` and `cli/build.rs`! let mut extensions = vec![ // Web APIs deno_webidl::deno_webidl::init_ops_and_esm(), deno_console::deno_console::init_ops_and_esm(), deno_url::deno_url::init_ops_and_esm(), deno_web::deno_web::init_ops_and_esm::<PermissionsContainer>( options.blob_store.clone(), options.bootstrap.location.clone(), ), deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>( deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: options.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), ..Default::default() }, ), deno_cache::deno_cache::init_ops_and_esm::<SqliteBackedCache>( create_cache, ), deno_websocket::deno_websocket::init_ops_and_esm::<PermissionsContainer>( options.bootstrap.user_agent.clone(), options.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_webstorage::deno_webstorage::init_ops_and_esm( options.origin_storage_dir.clone(), ), deno_crypto::deno_crypto::init_ops_and_esm(options.seed), deno_broadcast_channel::deno_broadcast_channel::init_ops_and_esm( options.broadcast_channel.clone(), unstable, ), deno_ffi::deno_ffi::init_ops_and_esm::<PermissionsContainer>(unstable), deno_net::deno_net::init_ops_and_esm::<PermissionsContainer>( options.root_cert_store_provider.clone(), unstable, options.unsafely_ignore_certificate_errors.clone(), ), deno_tls::deno_tls::init_ops_and_esm(), deno_kv::deno_kv::init_ops_and_esm( MultiBackendDbHandler::remote_or_sqlite::<PermissionsContainer>( options.origin_storage_dir.clone(), ), unstable, ), deno_napi::deno_napi::init_ops_and_esm::<PermissionsContainer>(), deno_http::deno_http::init_ops_and_esm::<DefaultHttpPropertyExtractor>(), deno_io::deno_io::init_ops_and_esm(Some(options.stdio)), deno_fs::deno_fs::init_ops_and_esm::<PermissionsContainer>( unstable, options.fs.clone(), ), deno_node::deno_node::init_ops_and_esm::<PermissionsContainer>( options.npm_resolver, options.fs, ), // Ops from this crate ops::runtime::deno_runtime::init_ops_and_esm(main_module.clone()), ops::worker_host::deno_worker_host::init_ops_and_esm( options.create_web_worker_cb.clone(), options.format_js_error_fn.clone(), ), ops::fs_events::deno_fs_events::init_ops_and_esm(), ops::os::deno_os::init_ops_and_esm(exit_code.clone()), ops::permissions::deno_permissions::init_ops_and_esm(), ops::process::deno_process::init_ops_and_esm(), ops::signal::deno_signal::init_ops_and_esm(), ops::tty::deno_tty::init_ops_and_esm(), ops::http::deno_http_runtime::init_ops_and_esm(), deno_permissions_worker::init_ops_and_esm( permissions, unstable, enable_testing_features, ), runtime::init_ops_and_esm(), ]; for extension in &mut extensions { #[cfg(not(feature = "__runtime_js_sources"))] { extension.js_files = std::borrow::Cow::Borrowed(&[]); extension.esm_files = std::borrow::Cow::Borrowed(&[]); extension.esm_entry_point = None; } #[cfg(feature = "__runtime_js_sources")] { use crate::shared::maybe_transpile_source; for source in extension.esm_files.to_mut() { maybe_transpile_source(source).unwrap(); } for source in extension.js_files.to_mut() { maybe_transpile_source(source).unwrap(); } } } extensions.extend(std::mem::take(&mut options.extensions)); #[cfg(all(feature = "include_js_files_for_snapshotting", feature = "dont_create_runtime_snapshot", not(feature = "__runtime_js_sources")))] options.startup_snapshot.as_ref().expect("Sources are not embedded, snapshotting was disabled and a user snapshot was not provided."); // Clear extension modules from the module map, except preserve `node:*` // modules. let preserve_snapshotted_modules = Some(SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(options.module_loader.clone()), startup_snapshot: options .startup_snapshot .or_else(crate::js::deno_isolate_init), create_params: options.create_params, source_map_getter: options.source_map_getter, get_error_class_fn: options.get_error_class_fn, shared_array_buffer_store: options.shared_array_buffer_store.clone(), compiled_wasm_module_store: options.compiled_wasm_module_store.clone(), extensions, preserve_snapshotted_modules, inspector: options.maybe_inspector_server.is_some(), is_main: true, ..Default::default() }); if let Some(server) = options.maybe_inspector_server.clone() { server.register_inspector( main_module.to_string(), &mut js_runtime, options.should_break_on_first_statement || options.should_wait_for_inspector_session, ); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. let op_state = js_runtime.op_state(); let inspector = js_runtime.inspector(); op_state.borrow_mut().put(inspector); } let bootstrap_fn_global = { let context = js_runtime.main_context(); let scope = &mut js_runtime.handle_scope(); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"mainRuntime").unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); v8::Global::new(scope, bootstrap_fn) }; Self { js_runtime, should_break_on_first_statement: options.should_break_on_first_statement, should_wait_for_inspector_session: options .should_wait_for_inspector_session, exit_code, bootstrap_fn_global: Some(bootstrap_fn_global), } } pub fn bootstrap(&mut self, options: &BootstrapOptions) { let scope = &mut self.js_runtime.handle_scope(); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); bootstrap_fn.call(scope, undefined.into(), &[args]).unwrap(); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) pub fn execute_script( &mut self, script_name: &'static str, source_code: ModuleCode, ) -> Result<v8::Global<v8::Value>, AnyError> { self.js_runtime.execute_script(script_name, source_code) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_main_module(module_specifier, None) .await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_side_module(module_specifier, None) .await } /// Executes specified JavaScript module. pub async fn evaluate_module( &mut self, id: ModuleId, ) -> Result<(), AnyError> { self.wait_for_inspector_session(); let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { // Not using biased mode leads to non-determinism for relatively simple // programs. biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result.expect("Module evaluation result not provided.") } event_loop_result = self.run_event_loop(false) => { event_loop_result?; let maybe_result = receiver.await; maybe_result.expect("Module evaluation result not provided.") } } } /// Loads, instantiates and executes specified JavaScript module. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_side_module(module_specifier).await?; self.evaluate_module(id).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn
( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_main_module(module_specifier).await?; self.evaluate_module(id).await } fn wait_for_inspector_session(&mut self) { if self.should_break_on_first_statement { self .js_runtime .inspector() .borrow_mut() .wait_for_session_and_break_on_next_statement(); } else if self.should_wait_for_inspector_session { self.js_runtime.inspector().borrow_mut().wait_for_session(); } } /// Create new inspector session. This function panics if Worker /// was not configured to create inspector. pub async fn create_inspector_session(&mut self) -> LocalInspectorSession { self.js_runtime.maybe_init_inspector(); self.js_runtime.inspector().borrow().create_local_session() } pub fn poll_event_loop( &mut self, cx: &mut Context, wait_for_inspector: bool, ) -> Poll<Result<(), AnyError>> { self.js_runtime.poll_event_loop(cx, wait_for_inspector) } pub async fn run_event_loop( &mut self, wait_for_inspector: bool, ) -> Result<(), AnyError> { self.js_runtime.run_event_loop(wait_for_inspector).await } /// A utility function that runs provided future concurrently with the event loop. /// /// Useful when using a local inspector session. pub async fn with_event_loop<'a, T>( &mut self, mut fut: Pin<Box<dyn Future<Output = T> + 'a>>, ) -> T { loop { tokio::select! { biased; result = &mut fut => { return result; } _ = self.run_event_loop(false) => {} }; } } /// Return exit code set by the executed code (either in main worker /// or one of child web workers). pub fn exit_code(&self) -> i32 { self.exit_code.get() } /// Dispatches "load" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "load" event handlers. pub fn dispatch_load_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('load'))"), )?; Ok(()) } /// Dispatches "unload" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "unload" event handlers. pub fn dispatch_unload_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('unload'))"), )?; Ok(()) } /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean /// indicating if the event was prevented and thus event loop should continue /// running. pub fn dispatch_beforeunload_event( &mut self, script_name: &'static str, ) -> Result<bool, AnyError> { let value = self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!( "dispatchEvent(new Event('beforeunload', { cancelable: true }));" ), )?; let local_value = value.open(&mut self.js_runtime.handle_scope()); Ok(local_value.is_false()) } }
execute_main_module
identifier_name
worker.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::pin::Pin; use std::rc::Rc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::task::Context; use std::task::Poll; use deno_broadcast_channel::InMemoryBroadcastChannel; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::ascii_str; use deno_core::error::AnyError; use deno_core::error::JsError; use deno_core::futures::Future; use deno_core::v8; use deno_core::CompiledWasmModuleStore; use deno_core::Extension; use deno_core::FsModuleLoader; use deno_core::GetErrorClassFn; use deno_core::JsRuntime; use deno_core::LocalInspectorSession; use deno_core::ModuleCode; use deno_core::ModuleId; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::Snapshot; use deno_core::SourceMapGetter; use deno_fs::FileSystem; use deno_http::DefaultHttpPropertyExtractor; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_node::SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX; use deno_tls::RootCertStoreProvider; use deno_web::BlobStore; use log::debug; use crate::inspector_server::InspectorServer; use crate::ops; use crate::permissions::PermissionsContainer; use crate::shared::runtime; use crate::BootstrapOptions; pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send; #[derive(Clone, Default)] pub struct ExitCode(Arc<AtomicI32>); impl ExitCode { pub fn get(&self) -> i32 { self.0.load(Relaxed) } pub fn set(&mut self, code: i32) { self.0.store(code, Relaxed); } } /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in the `Deno` namespace. /// /// All `WebWorker`s created during program execution /// are descendants of this worker. pub struct MainWorker { pub js_runtime: JsRuntime, should_break_on_first_statement: bool, should_wait_for_inspector_session: bool, exit_code: ExitCode, bootstrap_fn_global: Option<v8::Global<v8::Function>>, } pub struct WorkerOptions { pub bootstrap: BootstrapOptions, /// JsRuntime extensions, not to be confused with ES modules. /// /// Extensions register "ops" and JavaScript sources provided in `js` or `esm` /// configuration. If you are using a snapshot, then extensions shouldn't /// provide JavaScript sources that were already snapshotted. pub extensions: Vec<Extension>, /// V8 snapshot that should be loaded on startup. pub startup_snapshot: Option<Snapshot>, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub seed: Option<u64>, pub fs: Arc<dyn FileSystem>, /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules. /// /// If not provided runtime will error if code being /// executed tries to load modules. pub module_loader: Rc<dyn ModuleLoader>, pub npm_resolver: Option<Arc<dyn deno_node::NpmResolver>>, // Callbacks invoked when creating new instance of WebWorker pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, /// Source map reference for errors. pub source_map_getter: Option<Box<dyn SourceMapGetter>>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, // If true, the worker will wait for inspector session and break on first // statement of user code. Takes higher precedence than // `should_wait_for_inspector_session`. pub should_break_on_first_statement: bool, // If true, the worker will wait for inspector session before executing // user code. pub should_wait_for_inspector_session: bool, /// Allows to map error type to a string "class" used to represent /// error in JavaScript. pub get_error_class_fn: Option<GetErrorClassFn>, pub cache_storage_dir: Option<std::path::PathBuf>, pub origin_storage_dir: Option<std::path::PathBuf>, pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, /// The store to use for transferring SharedArrayBuffers between isolates. /// If multiple isolates should have the possibility of sharing /// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If /// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be /// serialized. pub shared_array_buffer_store: Option<SharedArrayBufferStore>, /// The store to use for transferring `WebAssembly.Module` objects between /// isolates. /// If multiple isolates should have the possibility of sharing /// `WebAssembly.Module` objects, they should use the same /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, pub stdio: Stdio, } impl Default for WorkerOptions { fn default() -> Self
root_cert_store_provider: Default::default(), npm_resolver: Default::default(), blob_store: Default::default(), extensions: Default::default(), startup_snapshot: Default::default(), create_params: Default::default(), bootstrap: Default::default(), stdio: Default::default(), } } } impl MainWorker { pub fn bootstrap_from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, options: WorkerOptions, ) -> Self { let bootstrap_options = options.bootstrap.clone(); let mut worker = Self::from_options(main_module, permissions, options); worker.bootstrap(&bootstrap_options); worker } pub fn from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, mut options: WorkerOptions, ) -> Self { deno_core::extension!(deno_permissions_worker, options = { permissions: PermissionsContainer, unstable: bool, enable_testing_features: bool, }, state = |state, options| { state.put::<PermissionsContainer>(options.permissions); state.put(ops::UnstableChecker { unstable: options.unstable }); state.put(ops::TestingFeaturesEnabled(options.enable_testing_features)); }, ); // Permissions: many ops depend on this let unstable = options.bootstrap.unstable; let enable_testing_features = options.bootstrap.enable_testing_features; let exit_code = ExitCode(Arc::new(AtomicI32::new(0))); let create_cache = options.cache_storage_dir.map(|storage_dir| { let create_cache_fn = move || SqliteBackedCache::new(storage_dir.clone()); CreateCache(Arc::new(create_cache_fn)) }); // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/build.rs`, `runtime/web_worker.rs` and `cli/build.rs`! let mut extensions = vec![ // Web APIs deno_webidl::deno_webidl::init_ops_and_esm(), deno_console::deno_console::init_ops_and_esm(), deno_url::deno_url::init_ops_and_esm(), deno_web::deno_web::init_ops_and_esm::<PermissionsContainer>( options.blob_store.clone(), options.bootstrap.location.clone(), ), deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>( deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: options.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), ..Default::default() }, ), deno_cache::deno_cache::init_ops_and_esm::<SqliteBackedCache>( create_cache, ), deno_websocket::deno_websocket::init_ops_and_esm::<PermissionsContainer>( options.bootstrap.user_agent.clone(), options.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_webstorage::deno_webstorage::init_ops_and_esm( options.origin_storage_dir.clone(), ), deno_crypto::deno_crypto::init_ops_and_esm(options.seed), deno_broadcast_channel::deno_broadcast_channel::init_ops_and_esm( options.broadcast_channel.clone(), unstable, ), deno_ffi::deno_ffi::init_ops_and_esm::<PermissionsContainer>(unstable), deno_net::deno_net::init_ops_and_esm::<PermissionsContainer>( options.root_cert_store_provider.clone(), unstable, options.unsafely_ignore_certificate_errors.clone(), ), deno_tls::deno_tls::init_ops_and_esm(), deno_kv::deno_kv::init_ops_and_esm( MultiBackendDbHandler::remote_or_sqlite::<PermissionsContainer>( options.origin_storage_dir.clone(), ), unstable, ), deno_napi::deno_napi::init_ops_and_esm::<PermissionsContainer>(), deno_http::deno_http::init_ops_and_esm::<DefaultHttpPropertyExtractor>(), deno_io::deno_io::init_ops_and_esm(Some(options.stdio)), deno_fs::deno_fs::init_ops_and_esm::<PermissionsContainer>( unstable, options.fs.clone(), ), deno_node::deno_node::init_ops_and_esm::<PermissionsContainer>( options.npm_resolver, options.fs, ), // Ops from this crate ops::runtime::deno_runtime::init_ops_and_esm(main_module.clone()), ops::worker_host::deno_worker_host::init_ops_and_esm( options.create_web_worker_cb.clone(), options.format_js_error_fn.clone(), ), ops::fs_events::deno_fs_events::init_ops_and_esm(), ops::os::deno_os::init_ops_and_esm(exit_code.clone()), ops::permissions::deno_permissions::init_ops_and_esm(), ops::process::deno_process::init_ops_and_esm(), ops::signal::deno_signal::init_ops_and_esm(), ops::tty::deno_tty::init_ops_and_esm(), ops::http::deno_http_runtime::init_ops_and_esm(), deno_permissions_worker::init_ops_and_esm( permissions, unstable, enable_testing_features, ), runtime::init_ops_and_esm(), ]; for extension in &mut extensions { #[cfg(not(feature = "__runtime_js_sources"))] { extension.js_files = std::borrow::Cow::Borrowed(&[]); extension.esm_files = std::borrow::Cow::Borrowed(&[]); extension.esm_entry_point = None; } #[cfg(feature = "__runtime_js_sources")] { use crate::shared::maybe_transpile_source; for source in extension.esm_files.to_mut() { maybe_transpile_source(source).unwrap(); } for source in extension.js_files.to_mut() { maybe_transpile_source(source).unwrap(); } } } extensions.extend(std::mem::take(&mut options.extensions)); #[cfg(all(feature = "include_js_files_for_snapshotting", feature = "dont_create_runtime_snapshot", not(feature = "__runtime_js_sources")))] options.startup_snapshot.as_ref().expect("Sources are not embedded, snapshotting was disabled and a user snapshot was not provided."); // Clear extension modules from the module map, except preserve `node:*` // modules. let preserve_snapshotted_modules = Some(SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(options.module_loader.clone()), startup_snapshot: options .startup_snapshot .or_else(crate::js::deno_isolate_init), create_params: options.create_params, source_map_getter: options.source_map_getter, get_error_class_fn: options.get_error_class_fn, shared_array_buffer_store: options.shared_array_buffer_store.clone(), compiled_wasm_module_store: options.compiled_wasm_module_store.clone(), extensions, preserve_snapshotted_modules, inspector: options.maybe_inspector_server.is_some(), is_main: true, ..Default::default() }); if let Some(server) = options.maybe_inspector_server.clone() { server.register_inspector( main_module.to_string(), &mut js_runtime, options.should_break_on_first_statement || options.should_wait_for_inspector_session, ); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. let op_state = js_runtime.op_state(); let inspector = js_runtime.inspector(); op_state.borrow_mut().put(inspector); } let bootstrap_fn_global = { let context = js_runtime.main_context(); let scope = &mut js_runtime.handle_scope(); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"mainRuntime").unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); v8::Global::new(scope, bootstrap_fn) }; Self { js_runtime, should_break_on_first_statement: options.should_break_on_first_statement, should_wait_for_inspector_session: options .should_wait_for_inspector_session, exit_code, bootstrap_fn_global: Some(bootstrap_fn_global), } } pub fn bootstrap(&mut self, options: &BootstrapOptions) { let scope = &mut self.js_runtime.handle_scope(); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); bootstrap_fn.call(scope, undefined.into(), &[args]).unwrap(); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) pub fn execute_script( &mut self, script_name: &'static str, source_code: ModuleCode, ) -> Result<v8::Global<v8::Value>, AnyError> { self.js_runtime.execute_script(script_name, source_code) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_main_module(module_specifier, None) .await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_side_module(module_specifier, None) .await } /// Executes specified JavaScript module. pub async fn evaluate_module( &mut self, id: ModuleId, ) -> Result<(), AnyError> { self.wait_for_inspector_session(); let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { // Not using biased mode leads to non-determinism for relatively simple // programs. biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result.expect("Module evaluation result not provided.") } event_loop_result = self.run_event_loop(false) => { event_loop_result?; let maybe_result = receiver.await; maybe_result.expect("Module evaluation result not provided.") } } } /// Loads, instantiates and executes specified JavaScript module. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_side_module(module_specifier).await?; self.evaluate_module(id).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn execute_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_main_module(module_specifier).await?; self.evaluate_module(id).await } fn wait_for_inspector_session(&mut self) { if self.should_break_on_first_statement { self .js_runtime .inspector() .borrow_mut() .wait_for_session_and_break_on_next_statement(); } else if self.should_wait_for_inspector_session { self.js_runtime.inspector().borrow_mut().wait_for_session(); } } /// Create new inspector session. This function panics if Worker /// was not configured to create inspector. pub async fn create_inspector_session(&mut self) -> LocalInspectorSession { self.js_runtime.maybe_init_inspector(); self.js_runtime.inspector().borrow().create_local_session() } pub fn poll_event_loop( &mut self, cx: &mut Context, wait_for_inspector: bool, ) -> Poll<Result<(), AnyError>> { self.js_runtime.poll_event_loop(cx, wait_for_inspector) } pub async fn run_event_loop( &mut self, wait_for_inspector: bool, ) -> Result<(), AnyError> { self.js_runtime.run_event_loop(wait_for_inspector).await } /// A utility function that runs provided future concurrently with the event loop. /// /// Useful when using a local inspector session. pub async fn with_event_loop<'a, T>( &mut self, mut fut: Pin<Box<dyn Future<Output = T> + 'a>>, ) -> T { loop { tokio::select! { biased; result = &mut fut => { return result; } _ = self.run_event_loop(false) => {} }; } } /// Return exit code set by the executed code (either in main worker /// or one of child web workers). pub fn exit_code(&self) -> i32 { self.exit_code.get() } /// Dispatches "load" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "load" event handlers. pub fn dispatch_load_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('load'))"), )?; Ok(()) } /// Dispatches "unload" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "unload" event handlers. pub fn dispatch_unload_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('unload'))"), )?; Ok(()) } /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean /// indicating if the event was prevented and thus event loop should continue /// running. pub fn dispatch_beforeunload_event( &mut self, script_name: &'static str, ) -> Result<bool, AnyError> { let value = self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!( "dispatchEvent(new Event('beforeunload', { cancelable: true }));" ), )?; let local_value = value.open(&mut self.js_runtime.handle_scope()); Ok(local_value.is_false()) } }
{ Self { create_web_worker_cb: Arc::new(|_| { unimplemented!("web workers are not supported") }), fs: Arc::new(deno_fs::RealFs), module_loader: Rc::new(FsModuleLoader), seed: None, unsafely_ignore_certificate_errors: Default::default(), should_break_on_first_statement: Default::default(), should_wait_for_inspector_session: Default::default(), compiled_wasm_module_store: Default::default(), shared_array_buffer_store: Default::default(), maybe_inspector_server: Default::default(), format_js_error_fn: Default::default(), get_error_class_fn: Default::default(), origin_storage_dir: Default::default(), cache_storage_dir: Default::default(), broadcast_channel: Default::default(), source_map_getter: Default::default(),
identifier_body
worker.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::pin::Pin; use std::rc::Rc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::task::Context; use std::task::Poll; use deno_broadcast_channel::InMemoryBroadcastChannel; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::ascii_str; use deno_core::error::AnyError; use deno_core::error::JsError; use deno_core::futures::Future; use deno_core::v8; use deno_core::CompiledWasmModuleStore; use deno_core::Extension; use deno_core::FsModuleLoader; use deno_core::GetErrorClassFn; use deno_core::JsRuntime; use deno_core::LocalInspectorSession; use deno_core::ModuleCode; use deno_core::ModuleId; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::Snapshot; use deno_core::SourceMapGetter; use deno_fs::FileSystem; use deno_http::DefaultHttpPropertyExtractor; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_node::SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX; use deno_tls::RootCertStoreProvider; use deno_web::BlobStore; use log::debug; use crate::inspector_server::InspectorServer; use crate::ops; use crate::permissions::PermissionsContainer; use crate::shared::runtime; use crate::BootstrapOptions; pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send; #[derive(Clone, Default)] pub struct ExitCode(Arc<AtomicI32>); impl ExitCode { pub fn get(&self) -> i32 { self.0.load(Relaxed) } pub fn set(&mut self, code: i32) { self.0.store(code, Relaxed); } } /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in the `Deno` namespace. /// /// All `WebWorker`s created during program execution /// are descendants of this worker. pub struct MainWorker { pub js_runtime: JsRuntime, should_break_on_first_statement: bool, should_wait_for_inspector_session: bool, exit_code: ExitCode, bootstrap_fn_global: Option<v8::Global<v8::Function>>, } pub struct WorkerOptions { pub bootstrap: BootstrapOptions, /// JsRuntime extensions, not to be confused with ES modules. /// /// Extensions register "ops" and JavaScript sources provided in `js` or `esm` /// configuration. If you are using a snapshot, then extensions shouldn't /// provide JavaScript sources that were already snapshotted. pub extensions: Vec<Extension>, /// V8 snapshot that should be loaded on startup. pub startup_snapshot: Option<Snapshot>, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub seed: Option<u64>, pub fs: Arc<dyn FileSystem>, /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules. /// /// If not provided runtime will error if code being /// executed tries to load modules. pub module_loader: Rc<dyn ModuleLoader>, pub npm_resolver: Option<Arc<dyn deno_node::NpmResolver>>, // Callbacks invoked when creating new instance of WebWorker pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, /// Source map reference for errors. pub source_map_getter: Option<Box<dyn SourceMapGetter>>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, // If true, the worker will wait for inspector session and break on first // statement of user code. Takes higher precedence than // `should_wait_for_inspector_session`. pub should_break_on_first_statement: bool, // If true, the worker will wait for inspector session before executing // user code. pub should_wait_for_inspector_session: bool, /// Allows to map error type to a string "class" used to represent /// error in JavaScript. pub get_error_class_fn: Option<GetErrorClassFn>, pub cache_storage_dir: Option<std::path::PathBuf>, pub origin_storage_dir: Option<std::path::PathBuf>, pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, /// The store to use for transferring SharedArrayBuffers between isolates. /// If multiple isolates should have the possibility of sharing /// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If /// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be /// serialized. pub shared_array_buffer_store: Option<SharedArrayBufferStore>, /// The store to use for transferring `WebAssembly.Module` objects between /// isolates. /// If multiple isolates should have the possibility of sharing /// `WebAssembly.Module` objects, they should use the same /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, pub stdio: Stdio, } impl Default for WorkerOptions { fn default() -> Self { Self { create_web_worker_cb: Arc::new(|_| { unimplemented!("web workers are not supported") }), fs: Arc::new(deno_fs::RealFs), module_loader: Rc::new(FsModuleLoader), seed: None, unsafely_ignore_certificate_errors: Default::default(), should_break_on_first_statement: Default::default(), should_wait_for_inspector_session: Default::default(), compiled_wasm_module_store: Default::default(), shared_array_buffer_store: Default::default(), maybe_inspector_server: Default::default(), format_js_error_fn: Default::default(), get_error_class_fn: Default::default(), origin_storage_dir: Default::default(), cache_storage_dir: Default::default(), broadcast_channel: Default::default(), source_map_getter: Default::default(), root_cert_store_provider: Default::default(), npm_resolver: Default::default(), blob_store: Default::default(), extensions: Default::default(), startup_snapshot: Default::default(), create_params: Default::default(), bootstrap: Default::default(), stdio: Default::default(), } } } impl MainWorker { pub fn bootstrap_from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, options: WorkerOptions, ) -> Self { let bootstrap_options = options.bootstrap.clone(); let mut worker = Self::from_options(main_module, permissions, options); worker.bootstrap(&bootstrap_options); worker } pub fn from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, mut options: WorkerOptions, ) -> Self { deno_core::extension!(deno_permissions_worker, options = { permissions: PermissionsContainer, unstable: bool, enable_testing_features: bool, }, state = |state, options| { state.put::<PermissionsContainer>(options.permissions); state.put(ops::UnstableChecker { unstable: options.unstable }); state.put(ops::TestingFeaturesEnabled(options.enable_testing_features)); }, ); // Permissions: many ops depend on this let unstable = options.bootstrap.unstable; let enable_testing_features = options.bootstrap.enable_testing_features; let exit_code = ExitCode(Arc::new(AtomicI32::new(0))); let create_cache = options.cache_storage_dir.map(|storage_dir| { let create_cache_fn = move || SqliteBackedCache::new(storage_dir.clone()); CreateCache(Arc::new(create_cache_fn)) }); // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/build.rs`, `runtime/web_worker.rs` and `cli/build.rs`! let mut extensions = vec![ // Web APIs deno_webidl::deno_webidl::init_ops_and_esm(), deno_console::deno_console::init_ops_and_esm(), deno_url::deno_url::init_ops_and_esm(), deno_web::deno_web::init_ops_and_esm::<PermissionsContainer>( options.blob_store.clone(), options.bootstrap.location.clone(), ), deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>( deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: options.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), ..Default::default() }, ), deno_cache::deno_cache::init_ops_and_esm::<SqliteBackedCache>( create_cache, ), deno_websocket::deno_websocket::init_ops_and_esm::<PermissionsContainer>( options.bootstrap.user_agent.clone(), options.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_webstorage::deno_webstorage::init_ops_and_esm( options.origin_storage_dir.clone(), ), deno_crypto::deno_crypto::init_ops_and_esm(options.seed), deno_broadcast_channel::deno_broadcast_channel::init_ops_and_esm( options.broadcast_channel.clone(), unstable, ), deno_ffi::deno_ffi::init_ops_and_esm::<PermissionsContainer>(unstable), deno_net::deno_net::init_ops_and_esm::<PermissionsContainer>( options.root_cert_store_provider.clone(), unstable, options.unsafely_ignore_certificate_errors.clone(), ), deno_tls::deno_tls::init_ops_and_esm(), deno_kv::deno_kv::init_ops_and_esm( MultiBackendDbHandler::remote_or_sqlite::<PermissionsContainer>( options.origin_storage_dir.clone(), ), unstable, ), deno_napi::deno_napi::init_ops_and_esm::<PermissionsContainer>(), deno_http::deno_http::init_ops_and_esm::<DefaultHttpPropertyExtractor>(), deno_io::deno_io::init_ops_and_esm(Some(options.stdio)), deno_fs::deno_fs::init_ops_and_esm::<PermissionsContainer>( unstable, options.fs.clone(), ), deno_node::deno_node::init_ops_and_esm::<PermissionsContainer>( options.npm_resolver, options.fs, ), // Ops from this crate ops::runtime::deno_runtime::init_ops_and_esm(main_module.clone()), ops::worker_host::deno_worker_host::init_ops_and_esm( options.create_web_worker_cb.clone(), options.format_js_error_fn.clone(), ), ops::fs_events::deno_fs_events::init_ops_and_esm(), ops::os::deno_os::init_ops_and_esm(exit_code.clone()), ops::permissions::deno_permissions::init_ops_and_esm(), ops::process::deno_process::init_ops_and_esm(), ops::signal::deno_signal::init_ops_and_esm(), ops::tty::deno_tty::init_ops_and_esm(), ops::http::deno_http_runtime::init_ops_and_esm(), deno_permissions_worker::init_ops_and_esm( permissions, unstable, enable_testing_features, ), runtime::init_ops_and_esm(), ]; for extension in &mut extensions { #[cfg(not(feature = "__runtime_js_sources"))] { extension.js_files = std::borrow::Cow::Borrowed(&[]); extension.esm_files = std::borrow::Cow::Borrowed(&[]); extension.esm_entry_point = None; } #[cfg(feature = "__runtime_js_sources")] { use crate::shared::maybe_transpile_source; for source in extension.esm_files.to_mut() { maybe_transpile_source(source).unwrap(); } for source in extension.js_files.to_mut() { maybe_transpile_source(source).unwrap(); } } } extensions.extend(std::mem::take(&mut options.extensions)); #[cfg(all(feature = "include_js_files_for_snapshotting", feature = "dont_create_runtime_snapshot", not(feature = "__runtime_js_sources")))] options.startup_snapshot.as_ref().expect("Sources are not embedded, snapshotting was disabled and a user snapshot was not provided."); // Clear extension modules from the module map, except preserve `node:*` // modules. let preserve_snapshotted_modules = Some(SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(options.module_loader.clone()), startup_snapshot: options .startup_snapshot .or_else(crate::js::deno_isolate_init), create_params: options.create_params, source_map_getter: options.source_map_getter, get_error_class_fn: options.get_error_class_fn, shared_array_buffer_store: options.shared_array_buffer_store.clone(), compiled_wasm_module_store: options.compiled_wasm_module_store.clone(), extensions, preserve_snapshotted_modules, inspector: options.maybe_inspector_server.is_some(), is_main: true, ..Default::default() }); if let Some(server) = options.maybe_inspector_server.clone()
let bootstrap_fn_global = { let context = js_runtime.main_context(); let scope = &mut js_runtime.handle_scope(); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"mainRuntime").unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); v8::Global::new(scope, bootstrap_fn) }; Self { js_runtime, should_break_on_first_statement: options.should_break_on_first_statement, should_wait_for_inspector_session: options .should_wait_for_inspector_session, exit_code, bootstrap_fn_global: Some(bootstrap_fn_global), } } pub fn bootstrap(&mut self, options: &BootstrapOptions) { let scope = &mut self.js_runtime.handle_scope(); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); bootstrap_fn.call(scope, undefined.into(), &[args]).unwrap(); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) pub fn execute_script( &mut self, script_name: &'static str, source_code: ModuleCode, ) -> Result<v8::Global<v8::Value>, AnyError> { self.js_runtime.execute_script(script_name, source_code) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_main_module(module_specifier, None) .await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_side_module(module_specifier, None) .await } /// Executes specified JavaScript module. pub async fn evaluate_module( &mut self, id: ModuleId, ) -> Result<(), AnyError> { self.wait_for_inspector_session(); let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { // Not using biased mode leads to non-determinism for relatively simple // programs. biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result.expect("Module evaluation result not provided.") } event_loop_result = self.run_event_loop(false) => { event_loop_result?; let maybe_result = receiver.await; maybe_result.expect("Module evaluation result not provided.") } } } /// Loads, instantiates and executes specified JavaScript module. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_side_module(module_specifier).await?; self.evaluate_module(id).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn execute_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_main_module(module_specifier).await?; self.evaluate_module(id).await } fn wait_for_inspector_session(&mut self) { if self.should_break_on_first_statement { self .js_runtime .inspector() .borrow_mut() .wait_for_session_and_break_on_next_statement(); } else if self.should_wait_for_inspector_session { self.js_runtime.inspector().borrow_mut().wait_for_session(); } } /// Create new inspector session. This function panics if Worker /// was not configured to create inspector. pub async fn create_inspector_session(&mut self) -> LocalInspectorSession { self.js_runtime.maybe_init_inspector(); self.js_runtime.inspector().borrow().create_local_session() } pub fn poll_event_loop( &mut self, cx: &mut Context, wait_for_inspector: bool, ) -> Poll<Result<(), AnyError>> { self.js_runtime.poll_event_loop(cx, wait_for_inspector) } pub async fn run_event_loop( &mut self, wait_for_inspector: bool, ) -> Result<(), AnyError> { self.js_runtime.run_event_loop(wait_for_inspector).await } /// A utility function that runs provided future concurrently with the event loop. /// /// Useful when using a local inspector session. pub async fn with_event_loop<'a, T>( &mut self, mut fut: Pin<Box<dyn Future<Output = T> + 'a>>, ) -> T { loop { tokio::select! { biased; result = &mut fut => { return result; } _ = self.run_event_loop(false) => {} }; } } /// Return exit code set by the executed code (either in main worker /// or one of child web workers). pub fn exit_code(&self) -> i32 { self.exit_code.get() } /// Dispatches "load" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "load" event handlers. pub fn dispatch_load_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('load'))"), )?; Ok(()) } /// Dispatches "unload" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "unload" event handlers. pub fn dispatch_unload_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('unload'))"), )?; Ok(()) } /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean /// indicating if the event was prevented and thus event loop should continue /// running. pub fn dispatch_beforeunload_event( &mut self, script_name: &'static str, ) -> Result<bool, AnyError> { let value = self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!( "dispatchEvent(new Event('beforeunload', { cancelable: true }));" ), )?; let local_value = value.open(&mut self.js_runtime.handle_scope()); Ok(local_value.is_false()) } }
{ server.register_inspector( main_module.to_string(), &mut js_runtime, options.should_break_on_first_statement || options.should_wait_for_inspector_session, ); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. let op_state = js_runtime.op_state(); let inspector = js_runtime.inspector(); op_state.borrow_mut().put(inspector); }
conditional_block
worker.rs
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. use std::pin::Pin; use std::rc::Rc; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering::Relaxed; use std::sync::Arc; use std::task::Context; use std::task::Poll; use deno_broadcast_channel::InMemoryBroadcastChannel; use deno_cache::CreateCache; use deno_cache::SqliteBackedCache; use deno_core::ascii_str; use deno_core::error::AnyError; use deno_core::error::JsError; use deno_core::futures::Future; use deno_core::v8; use deno_core::CompiledWasmModuleStore; use deno_core::Extension; use deno_core::FsModuleLoader; use deno_core::GetErrorClassFn; use deno_core::JsRuntime; use deno_core::LocalInspectorSession; use deno_core::ModuleCode; use deno_core::ModuleId; use deno_core::ModuleLoader; use deno_core::ModuleSpecifier; use deno_core::RuntimeOptions; use deno_core::SharedArrayBufferStore; use deno_core::Snapshot; use deno_core::SourceMapGetter; use deno_fs::FileSystem; use deno_http::DefaultHttpPropertyExtractor; use deno_io::Stdio; use deno_kv::dynamic::MultiBackendDbHandler; use deno_node::SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX; use deno_tls::RootCertStoreProvider; use deno_web::BlobStore; use log::debug; use crate::inspector_server::InspectorServer; use crate::ops; use crate::permissions::PermissionsContainer; use crate::shared::runtime; use crate::BootstrapOptions; pub type FormatJsErrorFn = dyn Fn(&JsError) -> String + Sync + Send; #[derive(Clone, Default)] pub struct ExitCode(Arc<AtomicI32>); impl ExitCode { pub fn get(&self) -> i32 { self.0.load(Relaxed) } pub fn set(&mut self, code: i32) { self.0.store(code, Relaxed); } } /// This worker is created and used by almost all /// subcommands in Deno executable. /// /// It provides ops available in the `Deno` namespace. /// /// All `WebWorker`s created during program execution /// are descendants of this worker. pub struct MainWorker { pub js_runtime: JsRuntime, should_break_on_first_statement: bool, should_wait_for_inspector_session: bool, exit_code: ExitCode, bootstrap_fn_global: Option<v8::Global<v8::Function>>, } pub struct WorkerOptions { pub bootstrap: BootstrapOptions, /// JsRuntime extensions, not to be confused with ES modules. /// /// Extensions register "ops" and JavaScript sources provided in `js` or `esm` /// configuration. If you are using a snapshot, then extensions shouldn't /// provide JavaScript sources that were already snapshotted. pub extensions: Vec<Extension>, /// V8 snapshot that should be loaded on startup. pub startup_snapshot: Option<Snapshot>, /// Optional isolate creation parameters, such as heap limits. pub create_params: Option<v8::CreateParams>, pub unsafely_ignore_certificate_errors: Option<Vec<String>>, pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>, pub seed: Option<u64>, pub fs: Arc<dyn FileSystem>, /// Implementation of `ModuleLoader` which will be /// called when V8 requests to load ES modules. /// /// If not provided runtime will error if code being /// executed tries to load modules. pub module_loader: Rc<dyn ModuleLoader>, pub npm_resolver: Option<Arc<dyn deno_node::NpmResolver>>, // Callbacks invoked when creating new instance of WebWorker pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>, pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>, /// Source map reference for errors. pub source_map_getter: Option<Box<dyn SourceMapGetter>>, pub maybe_inspector_server: Option<Arc<InspectorServer>>, // If true, the worker will wait for inspector session and break on first // statement of user code. Takes higher precedence than // `should_wait_for_inspector_session`. pub should_break_on_first_statement: bool, // If true, the worker will wait for inspector session before executing // user code. pub should_wait_for_inspector_session: bool, /// Allows to map error type to a string "class" used to represent /// error in JavaScript. pub get_error_class_fn: Option<GetErrorClassFn>, pub cache_storage_dir: Option<std::path::PathBuf>, pub origin_storage_dir: Option<std::path::PathBuf>, pub blob_store: Arc<BlobStore>, pub broadcast_channel: InMemoryBroadcastChannel, /// The store to use for transferring SharedArrayBuffers between isolates. /// If multiple isolates should have the possibility of sharing /// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If /// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be /// serialized. pub shared_array_buffer_store: Option<SharedArrayBufferStore>, /// The store to use for transferring `WebAssembly.Module` objects between /// isolates. /// If multiple isolates should have the possibility of sharing /// `WebAssembly.Module` objects, they should use the same /// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified, /// `WebAssembly.Module` objects cannot be serialized. pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>, pub stdio: Stdio, } impl Default for WorkerOptions { fn default() -> Self { Self { create_web_worker_cb: Arc::new(|_| { unimplemented!("web workers are not supported") }), fs: Arc::new(deno_fs::RealFs), module_loader: Rc::new(FsModuleLoader), seed: None, unsafely_ignore_certificate_errors: Default::default(), should_break_on_first_statement: Default::default(), should_wait_for_inspector_session: Default::default(), compiled_wasm_module_store: Default::default(), shared_array_buffer_store: Default::default(), maybe_inspector_server: Default::default(), format_js_error_fn: Default::default(), get_error_class_fn: Default::default(), origin_storage_dir: Default::default(), cache_storage_dir: Default::default(), broadcast_channel: Default::default(), source_map_getter: Default::default(), root_cert_store_provider: Default::default(), npm_resolver: Default::default(), blob_store: Default::default(), extensions: Default::default(), startup_snapshot: Default::default(), create_params: Default::default(), bootstrap: Default::default(), stdio: Default::default(), } } } impl MainWorker { pub fn bootstrap_from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, options: WorkerOptions, ) -> Self { let bootstrap_options = options.bootstrap.clone(); let mut worker = Self::from_options(main_module, permissions, options); worker.bootstrap(&bootstrap_options); worker } pub fn from_options( main_module: ModuleSpecifier, permissions: PermissionsContainer, mut options: WorkerOptions, ) -> Self { deno_core::extension!(deno_permissions_worker, options = {
state = |state, options| { state.put::<PermissionsContainer>(options.permissions); state.put(ops::UnstableChecker { unstable: options.unstable }); state.put(ops::TestingFeaturesEnabled(options.enable_testing_features)); }, ); // Permissions: many ops depend on this let unstable = options.bootstrap.unstable; let enable_testing_features = options.bootstrap.enable_testing_features; let exit_code = ExitCode(Arc::new(AtomicI32::new(0))); let create_cache = options.cache_storage_dir.map(|storage_dir| { let create_cache_fn = move || SqliteBackedCache::new(storage_dir.clone()); CreateCache(Arc::new(create_cache_fn)) }); // NOTE(bartlomieju): ordering is important here, keep it in sync with // `runtime/build.rs`, `runtime/web_worker.rs` and `cli/build.rs`! let mut extensions = vec![ // Web APIs deno_webidl::deno_webidl::init_ops_and_esm(), deno_console::deno_console::init_ops_and_esm(), deno_url::deno_url::init_ops_and_esm(), deno_web::deno_web::init_ops_and_esm::<PermissionsContainer>( options.blob_store.clone(), options.bootstrap.location.clone(), ), deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>( deno_fetch::Options { user_agent: options.bootstrap.user_agent.clone(), root_cert_store_provider: options.root_cert_store_provider.clone(), unsafely_ignore_certificate_errors: options .unsafely_ignore_certificate_errors .clone(), file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler), ..Default::default() }, ), deno_cache::deno_cache::init_ops_and_esm::<SqliteBackedCache>( create_cache, ), deno_websocket::deno_websocket::init_ops_and_esm::<PermissionsContainer>( options.bootstrap.user_agent.clone(), options.root_cert_store_provider.clone(), options.unsafely_ignore_certificate_errors.clone(), ), deno_webstorage::deno_webstorage::init_ops_and_esm( options.origin_storage_dir.clone(), ), deno_crypto::deno_crypto::init_ops_and_esm(options.seed), deno_broadcast_channel::deno_broadcast_channel::init_ops_and_esm( options.broadcast_channel.clone(), unstable, ), deno_ffi::deno_ffi::init_ops_and_esm::<PermissionsContainer>(unstable), deno_net::deno_net::init_ops_and_esm::<PermissionsContainer>( options.root_cert_store_provider.clone(), unstable, options.unsafely_ignore_certificate_errors.clone(), ), deno_tls::deno_tls::init_ops_and_esm(), deno_kv::deno_kv::init_ops_and_esm( MultiBackendDbHandler::remote_or_sqlite::<PermissionsContainer>( options.origin_storage_dir.clone(), ), unstable, ), deno_napi::deno_napi::init_ops_and_esm::<PermissionsContainer>(), deno_http::deno_http::init_ops_and_esm::<DefaultHttpPropertyExtractor>(), deno_io::deno_io::init_ops_and_esm(Some(options.stdio)), deno_fs::deno_fs::init_ops_and_esm::<PermissionsContainer>( unstable, options.fs.clone(), ), deno_node::deno_node::init_ops_and_esm::<PermissionsContainer>( options.npm_resolver, options.fs, ), // Ops from this crate ops::runtime::deno_runtime::init_ops_and_esm(main_module.clone()), ops::worker_host::deno_worker_host::init_ops_and_esm( options.create_web_worker_cb.clone(), options.format_js_error_fn.clone(), ), ops::fs_events::deno_fs_events::init_ops_and_esm(), ops::os::deno_os::init_ops_and_esm(exit_code.clone()), ops::permissions::deno_permissions::init_ops_and_esm(), ops::process::deno_process::init_ops_and_esm(), ops::signal::deno_signal::init_ops_and_esm(), ops::tty::deno_tty::init_ops_and_esm(), ops::http::deno_http_runtime::init_ops_and_esm(), deno_permissions_worker::init_ops_and_esm( permissions, unstable, enable_testing_features, ), runtime::init_ops_and_esm(), ]; for extension in &mut extensions { #[cfg(not(feature = "__runtime_js_sources"))] { extension.js_files = std::borrow::Cow::Borrowed(&[]); extension.esm_files = std::borrow::Cow::Borrowed(&[]); extension.esm_entry_point = None; } #[cfg(feature = "__runtime_js_sources")] { use crate::shared::maybe_transpile_source; for source in extension.esm_files.to_mut() { maybe_transpile_source(source).unwrap(); } for source in extension.js_files.to_mut() { maybe_transpile_source(source).unwrap(); } } } extensions.extend(std::mem::take(&mut options.extensions)); #[cfg(all(feature = "include_js_files_for_snapshotting", feature = "dont_create_runtime_snapshot", not(feature = "__runtime_js_sources")))] options.startup_snapshot.as_ref().expect("Sources are not embedded, snapshotting was disabled and a user snapshot was not provided."); // Clear extension modules from the module map, except preserve `node:*` // modules. let preserve_snapshotted_modules = Some(SUPPORTED_BUILTIN_NODE_MODULES_WITH_PREFIX); let mut js_runtime = JsRuntime::new(RuntimeOptions { module_loader: Some(options.module_loader.clone()), startup_snapshot: options .startup_snapshot .or_else(crate::js::deno_isolate_init), create_params: options.create_params, source_map_getter: options.source_map_getter, get_error_class_fn: options.get_error_class_fn, shared_array_buffer_store: options.shared_array_buffer_store.clone(), compiled_wasm_module_store: options.compiled_wasm_module_store.clone(), extensions, preserve_snapshotted_modules, inspector: options.maybe_inspector_server.is_some(), is_main: true, ..Default::default() }); if let Some(server) = options.maybe_inspector_server.clone() { server.register_inspector( main_module.to_string(), &mut js_runtime, options.should_break_on_first_statement || options.should_wait_for_inspector_session, ); // Put inspector handle into the op state so we can put a breakpoint when // executing a CJS entrypoint. let op_state = js_runtime.op_state(); let inspector = js_runtime.inspector(); op_state.borrow_mut().put(inspector); } let bootstrap_fn_global = { let context = js_runtime.main_context(); let scope = &mut js_runtime.handle_scope(); let context_local = v8::Local::new(scope, context); let global_obj = context_local.global(scope); let bootstrap_str = v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap(); let bootstrap_ns: v8::Local<v8::Object> = global_obj .get(scope, bootstrap_str.into()) .unwrap() .try_into() .unwrap(); let main_runtime_str = v8::String::new_external_onebyte_static(scope, b"mainRuntime").unwrap(); let bootstrap_fn = bootstrap_ns.get(scope, main_runtime_str.into()).unwrap(); let bootstrap_fn = v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap(); v8::Global::new(scope, bootstrap_fn) }; Self { js_runtime, should_break_on_first_statement: options.should_break_on_first_statement, should_wait_for_inspector_session: options .should_wait_for_inspector_session, exit_code, bootstrap_fn_global: Some(bootstrap_fn_global), } } pub fn bootstrap(&mut self, options: &BootstrapOptions) { let scope = &mut self.js_runtime.handle_scope(); let args = options.as_v8(scope); let bootstrap_fn = self.bootstrap_fn_global.take().unwrap(); let bootstrap_fn = v8::Local::new(scope, bootstrap_fn); let undefined = v8::undefined(scope); bootstrap_fn.call(scope, undefined.into(), &[args]).unwrap(); } /// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script) pub fn execute_script( &mut self, script_name: &'static str, source_code: ModuleCode, ) -> Result<v8::Global<v8::Value>, AnyError> { self.js_runtime.execute_script(script_name, source_code) } /// Loads and instantiates specified JavaScript module as "main" module. pub async fn preload_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_main_module(module_specifier, None) .await } /// Loads and instantiates specified JavaScript module as "side" module. pub async fn preload_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<ModuleId, AnyError> { self .js_runtime .load_side_module(module_specifier, None) .await } /// Executes specified JavaScript module. pub async fn evaluate_module( &mut self, id: ModuleId, ) -> Result<(), AnyError> { self.wait_for_inspector_session(); let mut receiver = self.js_runtime.mod_evaluate(id); tokio::select! { // Not using biased mode leads to non-determinism for relatively simple // programs. biased; maybe_result = &mut receiver => { debug!("received module evaluate {:#?}", maybe_result); maybe_result.expect("Module evaluation result not provided.") } event_loop_result = self.run_event_loop(false) => { event_loop_result?; let maybe_result = receiver.await; maybe_result.expect("Module evaluation result not provided.") } } } /// Loads, instantiates and executes specified JavaScript module. pub async fn execute_side_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_side_module(module_specifier).await?; self.evaluate_module(id).await } /// Loads, instantiates and executes specified JavaScript module. /// /// This module will have "import.meta.main" equal to true. pub async fn execute_main_module( &mut self, module_specifier: &ModuleSpecifier, ) -> Result<(), AnyError> { let id = self.preload_main_module(module_specifier).await?; self.evaluate_module(id).await } fn wait_for_inspector_session(&mut self) { if self.should_break_on_first_statement { self .js_runtime .inspector() .borrow_mut() .wait_for_session_and_break_on_next_statement(); } else if self.should_wait_for_inspector_session { self.js_runtime.inspector().borrow_mut().wait_for_session(); } } /// Create new inspector session. This function panics if Worker /// was not configured to create inspector. pub async fn create_inspector_session(&mut self) -> LocalInspectorSession { self.js_runtime.maybe_init_inspector(); self.js_runtime.inspector().borrow().create_local_session() } pub fn poll_event_loop( &mut self, cx: &mut Context, wait_for_inspector: bool, ) -> Poll<Result<(), AnyError>> { self.js_runtime.poll_event_loop(cx, wait_for_inspector) } pub async fn run_event_loop( &mut self, wait_for_inspector: bool, ) -> Result<(), AnyError> { self.js_runtime.run_event_loop(wait_for_inspector).await } /// A utility function that runs provided future concurrently with the event loop. /// /// Useful when using a local inspector session. pub async fn with_event_loop<'a, T>( &mut self, mut fut: Pin<Box<dyn Future<Output = T> + 'a>>, ) -> T { loop { tokio::select! { biased; result = &mut fut => { return result; } _ = self.run_event_loop(false) => {} }; } } /// Return exit code set by the executed code (either in main worker /// or one of child web workers). pub fn exit_code(&self) -> i32 { self.exit_code.get() } /// Dispatches "load" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "load" event handlers. pub fn dispatch_load_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('load'))"), )?; Ok(()) } /// Dispatches "unload" event to the JavaScript runtime. /// /// Does not poll event loop, and thus not await any of the "unload" event handlers. pub fn dispatch_unload_event( &mut self, script_name: &'static str, ) -> Result<(), AnyError> { self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!("dispatchEvent(new Event('unload'))"), )?; Ok(()) } /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean /// indicating if the event was prevented and thus event loop should continue /// running. pub fn dispatch_beforeunload_event( &mut self, script_name: &'static str, ) -> Result<bool, AnyError> { let value = self.js_runtime.execute_script( script_name, // NOTE(@bartlomieju): not using `globalThis` here, because user might delete // it. Instead we're using global `dispatchEvent` function which will // used a saved reference to global scope. ascii_str!( "dispatchEvent(new Event('beforeunload', { cancelable: true }));" ), )?; let local_value = value.open(&mut self.js_runtime.handle_scope()); Ok(local_value.is_false()) } }
permissions: PermissionsContainer, unstable: bool, enable_testing_features: bool, },
random_line_split
install.rs
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::FrumConfig; use crate::input_version::InputVersion; use crate::outln; use crate::version::Version; use crate::version_file::get_user_version_for_directory; use anyhow::Result; use colored::Colorize; use log::debug; use reqwest::Url; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use std::process::Command; use thiserror::Error; #[derive(Error, Debug)] pub enum FrumError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version: {version}")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CantListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVersion { version: Version }, #[error("Can't build Ruby: {stderr}")] CantBuildRuby { stderr: String }, } pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl crate::command::Command for Install { type Error = FrumError; fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(FrumError::CantInferVersion)?; let version = match current_version.clone() { InputVersion::Full(Version::Semver(v)) => Version::Semver(v), InputVersion::Full(Version::System) => { return Err(FrumError::NotInstallableVersion { version: Version::System, }) } current_version => { let available_versions = crate::remote_ruby_index::list(&config.ruby_build_mirror) .map_err(|source| FrumError::CantListRemoteVersions { source })? .drain(..) .map(|x| x.version) .collect::<Vec<_>>(); current_version .to_version(&available_versions) .ok_or(FrumError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(FrumError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(config.ruby_build_mirror.clone(), &version); outln!(config#Info, "{} Downloading {}", "==>".green(), format!("{}", url).green()); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(FrumError::VersionNotFound { version: current_version, }); } outln!(config#Info, "{} Extracting {}", "==>".green(), archive(&version).green()); let temp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&temp_installations_dir).map_err(FrumError::IoError)?; let temp_dir = tempfile::TempDir::new_in(&temp_installations_dir) .expect("Can't generate a temp directory"); extract_archive_into(&temp_dir, response)?; outln!(config#Info, "{} Building {}", "==>".green(), format!("Ruby {}", current_version).green()); let installed_directory = std::fs::read_dir(&temp_dir) .map_err(FrumError::IoError)? .next() .ok_or(FrumError::TarIsEmpty)? .map_err(FrumError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if!config.default_version_dir().exists() { debug!("Use {} as the default version", current_version); create_alias(&config, "default", &version).map_err(FrumError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), FrumError> { #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::zip::Zip::new(response); extractor .extract_into(path) .map_err(|source| FrumError::ExtractError { source })?; Ok(()) } fn package_url(mirror_url: Url, version: &Version) -> Url { debug!("pakage url"); Url::parse(&format!( "{}/{}/{}", mirror_url.as_str().trim_end_matches('/'), match version { Version::Semver(version) => format!("{}.{}", version.major, version.minor), _ => unreachable!(), }, archive(version), )) .unwrap() } #[cfg(unix)] fn archive(version: &Version) -> String { format!("ruby-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &Version) -> String { format!("ruby-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, FrumError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &Command::new("brew") .arg("--prefix") .arg("openssl") .output() .map_err(FrumError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/usr/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), FrumError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); // Provide a default value for --with-openssl-dir if!configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!configure.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; debug!("make install"); let make_install = Command::new("make") .arg("install") .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make_install.status.success()
; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::command::Command; use crate::config::FrumConfig; use crate::version::Version; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.7.0").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.7.0"); Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.6.4"); assert_eq!( std::fs::read_link(&config.default_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("2.7.0"))) ); } #[test] fn test_install_default_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install"); assert!(config.versions_dir().join("2.6.4").exists()); assert!(config .versions_dir() .join("2.6.4") .join("bin") .join("ruby") .exists()); assert!(config.default_version_dir().exists()); } }
{ return Err(FrumError::CantBuildRuby { stderr: format!( "make install: {}", String::from_utf8_lossy(&make_install.stderr).to_string() ), }); }
conditional_block
install.rs
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::FrumConfig; use crate::input_version::InputVersion; use crate::outln; use crate::version::Version; use crate::version_file::get_user_version_for_directory; use anyhow::Result; use colored::Colorize; use log::debug; use reqwest::Url; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use std::process::Command; use thiserror::Error; #[derive(Error, Debug)] pub enum FrumError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version: {version}")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CantListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVersion { version: Version }, #[error("Can't build Ruby: {stderr}")] CantBuildRuby { stderr: String }, } pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl crate::command::Command for Install { type Error = FrumError; fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(FrumError::CantInferVersion)?; let version = match current_version.clone() { InputVersion::Full(Version::Semver(v)) => Version::Semver(v), InputVersion::Full(Version::System) => { return Err(FrumError::NotInstallableVersion { version: Version::System, }) } current_version => { let available_versions = crate::remote_ruby_index::list(&config.ruby_build_mirror) .map_err(|source| FrumError::CantListRemoteVersions { source })? .drain(..) .map(|x| x.version) .collect::<Vec<_>>(); current_version .to_version(&available_versions) .ok_or(FrumError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(FrumError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(config.ruby_build_mirror.clone(), &version); outln!(config#Info, "{} Downloading {}", "==>".green(), format!("{}", url).green()); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(FrumError::VersionNotFound { version: current_version, }); } outln!(config#Info, "{} Extracting {}", "==>".green(), archive(&version).green()); let temp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&temp_installations_dir).map_err(FrumError::IoError)?; let temp_dir = tempfile::TempDir::new_in(&temp_installations_dir) .expect("Can't generate a temp directory"); extract_archive_into(&temp_dir, response)?; outln!(config#Info, "{} Building {}", "==>".green(), format!("Ruby {}", current_version).green()); let installed_directory = std::fs::read_dir(&temp_dir) .map_err(FrumError::IoError)? .next() .ok_or(FrumError::TarIsEmpty)? .map_err(FrumError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if!config.default_version_dir().exists() { debug!("Use {} as the default version", current_version); create_alias(&config, "default", &version).map_err(FrumError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), FrumError> { #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::zip::Zip::new(response); extractor .extract_into(path) .map_err(|source| FrumError::ExtractError { source })?; Ok(()) } fn package_url(mirror_url: Url, version: &Version) -> Url { debug!("pakage url"); Url::parse(&format!( "{}/{}/{}", mirror_url.as_str().trim_end_matches('/'), match version { Version::Semver(version) => format!("{}.{}", version.major, version.minor), _ => unreachable!(), }, archive(version), )) .unwrap() } #[cfg(unix)] fn archive(version: &Version) -> String { format!("ruby-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &Version) -> String { format!("ruby-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, FrumError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &Command::new("brew") .arg("--prefix") .arg("openssl") .output() .map_err(FrumError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/usr/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), FrumError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); // Provide a default value for --with-openssl-dir if!configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!configure.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; debug!("make install"); let make_install = Command::new("make") .arg("install") .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make_install.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make install: {}", String::from_utf8_lossy(&make_install.stderr).to_string() ), }); }; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::command::Command; use crate::config::FrumConfig; use crate::version::Version; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.7.0").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.7.0"); Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.6.4"); assert_eq!( std::fs::read_link(&config.default_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("2.7.0"))) ); } #[test] fn
() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install"); assert!(config.versions_dir().join("2.6.4").exists()); assert!(config .versions_dir() .join("2.6.4") .join("bin") .join("ruby") .exists()); assert!(config.default_version_dir().exists()); } }
test_install_default_version
identifier_name
install.rs
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::FrumConfig; use crate::input_version::InputVersion; use crate::outln; use crate::version::Version; use crate::version_file::get_user_version_for_directory; use anyhow::Result;
use log::debug; use reqwest::Url; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use std::process::Command; use thiserror::Error; #[derive(Error, Debug)] pub enum FrumError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version: {version}")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CantListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVersion { version: Version }, #[error("Can't build Ruby: {stderr}")] CantBuildRuby { stderr: String }, } pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl crate::command::Command for Install { type Error = FrumError; fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(FrumError::CantInferVersion)?; let version = match current_version.clone() { InputVersion::Full(Version::Semver(v)) => Version::Semver(v), InputVersion::Full(Version::System) => { return Err(FrumError::NotInstallableVersion { version: Version::System, }) } current_version => { let available_versions = crate::remote_ruby_index::list(&config.ruby_build_mirror) .map_err(|source| FrumError::CantListRemoteVersions { source })? .drain(..) .map(|x| x.version) .collect::<Vec<_>>(); current_version .to_version(&available_versions) .ok_or(FrumError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(FrumError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(config.ruby_build_mirror.clone(), &version); outln!(config#Info, "{} Downloading {}", "==>".green(), format!("{}", url).green()); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(FrumError::VersionNotFound { version: current_version, }); } outln!(config#Info, "{} Extracting {}", "==>".green(), archive(&version).green()); let temp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&temp_installations_dir).map_err(FrumError::IoError)?; let temp_dir = tempfile::TempDir::new_in(&temp_installations_dir) .expect("Can't generate a temp directory"); extract_archive_into(&temp_dir, response)?; outln!(config#Info, "{} Building {}", "==>".green(), format!("Ruby {}", current_version).green()); let installed_directory = std::fs::read_dir(&temp_dir) .map_err(FrumError::IoError)? .next() .ok_or(FrumError::TarIsEmpty)? .map_err(FrumError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if!config.default_version_dir().exists() { debug!("Use {} as the default version", current_version); create_alias(&config, "default", &version).map_err(FrumError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), FrumError> { #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::zip::Zip::new(response); extractor .extract_into(path) .map_err(|source| FrumError::ExtractError { source })?; Ok(()) } fn package_url(mirror_url: Url, version: &Version) -> Url { debug!("pakage url"); Url::parse(&format!( "{}/{}/{}", mirror_url.as_str().trim_end_matches('/'), match version { Version::Semver(version) => format!("{}.{}", version.major, version.minor), _ => unreachable!(), }, archive(version), )) .unwrap() } #[cfg(unix)] fn archive(version: &Version) -> String { format!("ruby-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &Version) -> String { format!("ruby-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, FrumError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &Command::new("brew") .arg("--prefix") .arg("openssl") .output() .map_err(FrumError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/usr/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), FrumError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); // Provide a default value for --with-openssl-dir if!configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!configure.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; debug!("make install"); let make_install = Command::new("make") .arg("install") .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make_install.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make install: {}", String::from_utf8_lossy(&make_install.stderr).to_string() ), }); }; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::command::Command; use crate::config::FrumConfig; use crate::version::Version; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.7.0").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.7.0"); Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.6.4"); assert_eq!( std::fs::read_link(&config.default_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("2.7.0"))) ); } #[test] fn test_install_default_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install"); assert!(config.versions_dir().join("2.6.4").exists()); assert!(config .versions_dir() .join("2.6.4") .join("bin") .join("ruby") .exists()); assert!(config.default_version_dir().exists()); } }
use colored::Colorize;
random_line_split
install.rs
use crate::alias::create_alias; use crate::archive::{self, extract::Error as ExtractError, extract::Extract}; use crate::config::FrumConfig; use crate::input_version::InputVersion; use crate::outln; use crate::version::Version; use crate::version_file::get_user_version_for_directory; use anyhow::Result; use colored::Colorize; use log::debug; use reqwest::Url; use std::io::prelude::*; use std::path::Path; use std::path::PathBuf; use std::process::Command; use thiserror::Error; #[derive(Error, Debug)] pub enum FrumError { #[error(transparent)] HttpError(#[from] reqwest::Error), #[error(transparent)] IoError(#[from] std::io::Error), #[error("Can't find the number of cores")] FromUtf8Error(#[from] std::string::FromUtf8Error), #[error("Can't extract the file: {source:?}")] ExtractError { source: ExtractError }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("Can't find version: {version}")] VersionNotFound { version: InputVersion }, #[error("Can't list the remote versions: {source:?}")] CantListRemoteVersions { source: reqwest::Error }, #[error("Version already installed at {path:?}")] VersionAlreadyInstalled { path: PathBuf }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("The requested version is not installable: {version}")] NotInstallableVersion { version: Version }, #[error("Can't build Ruby: {stderr}")] CantBuildRuby { stderr: String }, } pub struct Install { pub version: Option<InputVersion>, pub configure_opts: Vec<String>, } impl crate::command::Command for Install { type Error = FrumError; fn apply(&self, config: &FrumConfig) -> Result<(), Self::Error> { let current_version = self .version .clone() .or_else(|| get_user_version_for_directory(std::env::current_dir().unwrap())) .ok_or(FrumError::CantInferVersion)?; let version = match current_version.clone() { InputVersion::Full(Version::Semver(v)) => Version::Semver(v), InputVersion::Full(Version::System) => { return Err(FrumError::NotInstallableVersion { version: Version::System, }) } current_version => { let available_versions = crate::remote_ruby_index::list(&config.ruby_build_mirror) .map_err(|source| FrumError::CantListRemoteVersions { source })? .drain(..) .map(|x| x.version) .collect::<Vec<_>>(); current_version .to_version(&available_versions) .ok_or(FrumError::VersionNotFound { version: current_version, })? .clone() } }; let installations_dir = config.versions_dir(); let installation_dir = PathBuf::from(&installations_dir).join(version.to_string()); if installation_dir.exists() { return Err(FrumError::VersionAlreadyInstalled { path: installation_dir, }); } let url = package_url(config.ruby_build_mirror.clone(), &version); outln!(config#Info, "{} Downloading {}", "==>".green(), format!("{}", url).green()); let response = reqwest::blocking::get(url)?; if response.status() == 404 { return Err(FrumError::VersionNotFound { version: current_version, }); } outln!(config#Info, "{} Extracting {}", "==>".green(), archive(&version).green()); let temp_installations_dir = installations_dir.join(".downloads"); std::fs::create_dir_all(&temp_installations_dir).map_err(FrumError::IoError)?; let temp_dir = tempfile::TempDir::new_in(&temp_installations_dir) .expect("Can't generate a temp directory"); extract_archive_into(&temp_dir, response)?; outln!(config#Info, "{} Building {}", "==>".green(), format!("Ruby {}", current_version).green()); let installed_directory = std::fs::read_dir(&temp_dir) .map_err(FrumError::IoError)? .next() .ok_or(FrumError::TarIsEmpty)? .map_err(FrumError::IoError)?; let installed_directory = installed_directory.path(); build_package( &installed_directory, &installation_dir, &self.configure_opts, )?; if!config.default_version_dir().exists() { debug!("Use {} as the default version", current_version); create_alias(&config, "default", &version).map_err(FrumError::IoError)?; } Ok(()) } } fn extract_archive_into<P: AsRef<Path>>( path: P, response: reqwest::blocking::Response, ) -> Result<(), FrumError>
fn package_url(mirror_url: Url, version: &Version) -> Url { debug!("pakage url"); Url::parse(&format!( "{}/{}/{}", mirror_url.as_str().trim_end_matches('/'), match version { Version::Semver(version) => format!("{}.{}", version.major, version.minor), _ => unreachable!(), }, archive(version), )) .unwrap() } #[cfg(unix)] fn archive(version: &Version) -> String { format!("ruby-{}.tar.xz", version) } #[cfg(windows)] fn archive(version: &Version) -> String { format!("ruby-{}.zip", version) } #[allow(clippy::unnecessary_wraps)] fn openssl_dir() -> Result<String, FrumError> { #[cfg(target_os = "macos")] return Ok(String::from_utf8_lossy( &Command::new("brew") .arg("--prefix") .arg("openssl") .output() .map_err(FrumError::IoError)? .stdout, ) .trim() .to_string()); #[cfg(not(target_os = "macos"))] return Ok("/usr/local".to_string()); } fn build_package( current_dir: &Path, installed_dir: &Path, configure_opts: &[String], ) -> Result<(), FrumError> { debug!("./configure {}", configure_opts.join(" ")); let mut command = Command::new("sh"); command .arg("configure") .arg(format!("--prefix={}", installed_dir.to_str().unwrap())) .args(configure_opts); // Provide a default value for --with-openssl-dir if!configure_opts .iter() .any(|opt| opt.starts_with("--with-openssl-dir")) { command.arg(format!("--with-openssl-dir={}", openssl_dir()?)); } let configure = command .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!configure.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "configure failed: {}", String::from_utf8_lossy(&configure.stderr).to_string() ), }); }; debug!("make -j {}", num_cpus::get().to_string()); let make = Command::new("make") .arg("-j") .arg(num_cpus::get().to_string()) .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make failed: {}", String::from_utf8_lossy(&make.stderr).to_string() ), }); }; debug!("make install"); let make_install = Command::new("make") .arg("install") .current_dir(&current_dir) .output() .map_err(FrumError::IoError)?; if!make_install.status.success() { return Err(FrumError::CantBuildRuby { stderr: format!( "make install: {}", String::from_utf8_lossy(&make_install.stderr).to_string() ), }); }; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::command::Command; use crate::config::FrumConfig; use crate::version::Version; use tempfile::tempdir; #[test] fn test_install_second_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.7.0").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.7.0"); Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install 2.6.4"); assert_eq!( std::fs::read_link(&config.default_version_dir()) .unwrap() .components() .last(), Some(std::path::Component::Normal(std::ffi::OsStr::new("2.7.0"))) ); } #[test] fn test_install_default_version() { let config = FrumConfig { base_dir: Some(tempdir().unwrap().path().to_path_buf()), ..Default::default() }; Install { version: Some(InputVersion::Full(Version::Semver( semver::Version::parse("2.6.4").unwrap(), ))), configure_opts: vec![], } .apply(&config) .expect("Can't install"); assert!(config.versions_dir().join("2.6.4").exists()); assert!(config .versions_dir() .join("2.6.4") .join("bin") .join("ruby") .exists()); assert!(config.default_version_dir().exists()); } }
{ #[cfg(unix)] let extractor = archive::tar_xz::TarXz::new(response); #[cfg(windows)] let extractor = archive::zip::Zip::new(response); extractor .extract_into(path) .map_err(|source| FrumError::ExtractError { source })?; Ok(()) }
identifier_body
resolve_recovers_from_http_errors.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// This module tests the property that pkg_resolver does not enter a bad /// state (successfully handles retries) when the TUF server errors while /// servicing fuchsia.pkg.PackageResolver.Resolve FIDL requests. use { assert_matches::assert_matches, fuchsia_merkle::MerkleTree, fuchsia_pkg_testing::{ serve::{responder, Domain, HttpResponder}, Package, PackageBuilder, RepositoryBuilder, }, lib::{ extra_blob_contents, make_pkg_with_extra_blobs, ResolverVariant, TestEnvBuilder, EMPTY_REPO_PATH, FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING, }, std::{net::Ipv4Addr, sync::Arc}, }; async fn verify_resolve_fails_then_succeeds<H: HttpResponder>( pkg: Package, responder: H, failure_error: fidl_fuchsia_pkg::ResolveError, ) { let env = TestEnvBuilder::new().build().await; let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let pkg_url = format!("fuchsia-pkg://test/{}", pkg.name()); let should_fail = responder::AtomicToggle::new(true); let served_repository = repo .server() .response_overrider(responder::Toggleable::new(&should_fail, responder)) .response_overrider(responder::Filter::new( responder::is_range_request, responder::StaticResponseCode::server_error(), )) .start() .unwrap(); env.register_repo(&served_repository).await; // First resolve fails with the expected error. assert_matches!(env.resolve_package(&pkg_url).await, Err(error) if error == failure_error); // Disabling the custom responder allows the subsequent resolves to succeed. should_fail.unset(); let (package_dir, _resolved_context) = env.resolve_package(&pkg_url).await.expect("package to resolve"); pkg.verify_contents(&package_dir).await.expect("correct package contents"); env.stop().await; } #[fuchsia::test] async fn second_resolve_succeeds_when_far_404() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_404", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_404() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_404", 1).await; let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader( extra_blob_contents("second_resolve_succeeds_when_blob_404", 0).as_slice() ) .expect("merkle slice") .root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_errors_mid_download() { let pkg = PackageBuilder::new("second_resolve_succeeds_when_far_errors_mid_download") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_errors_mid_download()
#[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_far_complete() { let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_far_complete") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_blob_complete() { let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_blob_complete") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_corrupted", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_corrupted", 1).await; let blob = extra_blob_contents("second_resolve_succeeds_when_blob_corrupted", 0); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_tuf_metadata_update_fails() { // pkg-resolver uses tuf::client::Client::with_trusted_root_keys to create its TUF client. // That method will only retrieve the specified version of the root metadata (1 for these // tests), with the rest of the metadata being retrieved during the first update. This means // that hanging all attempts for 2.snapshot.json metadata will allow tuf client creation to // succeed but still fail tuf client update. // We want to specifically verify recovery from update failure because if creation fails, // pkg-resolver will not make a Repository object, so the next resolve attempt would try again // from scratch, but if update fails, pkg-resolver will keep its Repository object which // contains a rust-tuf client in a possibly invalid state, and we want to verify that // pkg-resolver calls update on the client again and that this update recovers the client. let pkg = PackageBuilder::new("second_resolve_succeeds_when_tuf_metadata_update_fails") .build() .await .unwrap(); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new("/2.snapshot.json", responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::Internal, ) .await } // The hyper clients used by the pkg-resolver to download blobs and TUF metadata sometimes end up // waiting on operations on their TCP connections that will never return (e.g. because of an // upstream network partition). To detect this, the pkg-resolver wraps the hyper client response // futures with timeout futures. To recover from this, the pkg-resolver drops the hyper client // response futures when the timeouts are hit. This recovery plan requires that dropping the hyper // response future causes hyper to close the underlying TCP connection and create a new one the // next time hyper is asked to perform a network operation. This assumption holds for http1, but // not for http2. // // This test verifies the "dropping a hyper response future prevents the underlying connection // from being reused" requirement. It does so by verifying that if a resolve fails due to a blob // download timeout and the resolve is retried, the retry will cause pkg-resolver to make an // additional TCP connection to the blob mirror. // // This test uses https because the test exists to catch changes to the Fuchsia hyper client // that would cause pkg-resolver to use http2 before the Fuchsia hyper client is able to recover // from bad TCP connections when using http2. The pkg-resolver does not explicitly enable http2 // on its hyper clients, so the way this change would sneak in is if the hyper client is changed // to use ALPN to prefer http2. The blob server used in this test has ALPN configured to prefer // http2. #[fuchsia::test] async fn blob_timeout_causes_new_tcp_connection() { let pkg = PackageBuilder::new("blob_timeout_causes_new_tcp_connection").build().await.unwrap(); let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let env = TestEnvBuilder::new() .resolver_variant(ResolverVariant::ZeroBlobNetworkBodyTimeout) .build() .await; let server = repo .server() .response_overrider(responder::ForPathPrefix::new( "/blobs/", responder::Once::new(responder::HangBody), )) .use_https_domain(Domain::TestFuchsiaCom) .bind_to_addr(Ipv4Addr::LOCALHOST) .start() .expect("Starting server succeeds"); env.register_repo(&server).await; assert_eq!(server.connection_attempts(), 0); // The resolve request may not succeed despite the retry: the zero timeout on the blob body // future can fire prior to the body being downloaded on the retry. However, we expect to // observe three connections: one for the TUF client, one for the initial resolve that timed // out, and one for the retried resolve. match env.resolve_package("fuchsia-pkg://test/blob_timeout_causes_new_tcp_connection").await { Ok(_) | Err(fidl_fuchsia_pkg::ResolveError::UnavailableBlob) => {} Err(e) => { panic!("unexpected error: {:?}", e); } }; assert_eq!(server.connection_attempts(), 3); env.stop().await; }
{ let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_when_blob_errors_mid_download") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await }
identifier_body
resolve_recovers_from_http_errors.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// This module tests the property that pkg_resolver does not enter a bad /// state (successfully handles retries) when the TUF server errors while /// servicing fuchsia.pkg.PackageResolver.Resolve FIDL requests. use { assert_matches::assert_matches, fuchsia_merkle::MerkleTree, fuchsia_pkg_testing::{ serve::{responder, Domain, HttpResponder}, Package, PackageBuilder, RepositoryBuilder, }, lib::{ extra_blob_contents, make_pkg_with_extra_blobs, ResolverVariant, TestEnvBuilder, EMPTY_REPO_PATH, FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING, }, std::{net::Ipv4Addr, sync::Arc}, }; async fn verify_resolve_fails_then_succeeds<H: HttpResponder>( pkg: Package, responder: H, failure_error: fidl_fuchsia_pkg::ResolveError, ) { let env = TestEnvBuilder::new().build().await; let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let pkg_url = format!("fuchsia-pkg://test/{}", pkg.name()); let should_fail = responder::AtomicToggle::new(true); let served_repository = repo .server() .response_overrider(responder::Toggleable::new(&should_fail, responder)) .response_overrider(responder::Filter::new( responder::is_range_request, responder::StaticResponseCode::server_error(), )) .start() .unwrap(); env.register_repo(&served_repository).await; // First resolve fails with the expected error. assert_matches!(env.resolve_package(&pkg_url).await, Err(error) if error == failure_error); // Disabling the custom responder allows the subsequent resolves to succeed. should_fail.unset(); let (package_dir, _resolved_context) = env.resolve_package(&pkg_url).await.expect("package to resolve"); pkg.verify_contents(&package_dir).await.expect("correct package contents"); env.stop().await; } #[fuchsia::test] async fn second_resolve_succeeds_when_far_404() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_404", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_404() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_404", 1).await; let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader( extra_blob_contents("second_resolve_succeeds_when_blob_404", 0).as_slice() ) .expect("merkle slice") .root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_errors_mid_download() { let pkg = PackageBuilder::new("second_resolve_succeeds_when_far_errors_mid_download") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_errors_mid_download() { let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_when_blob_errors_mid_download") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_far_complete() { let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_far_complete") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_blob_complete() { let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_blob_complete") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_corrupted", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_corrupted", 1).await; let blob = extra_blob_contents("second_resolve_succeeds_when_blob_corrupted", 0); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_tuf_metadata_update_fails() { // pkg-resolver uses tuf::client::Client::with_trusted_root_keys to create its TUF client. // That method will only retrieve the specified version of the root metadata (1 for these // tests), with the rest of the metadata being retrieved during the first update. This means // that hanging all attempts for 2.snapshot.json metadata will allow tuf client creation to // succeed but still fail tuf client update. // We want to specifically verify recovery from update failure because if creation fails, // pkg-resolver will not make a Repository object, so the next resolve attempt would try again // from scratch, but if update fails, pkg-resolver will keep its Repository object which // contains a rust-tuf client in a possibly invalid state, and we want to verify that // pkg-resolver calls update on the client again and that this update recovers the client.
.await .unwrap(); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new("/2.snapshot.json", responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::Internal, ) .await } // The hyper clients used by the pkg-resolver to download blobs and TUF metadata sometimes end up // waiting on operations on their TCP connections that will never return (e.g. because of an // upstream network partition). To detect this, the pkg-resolver wraps the hyper client response // futures with timeout futures. To recover from this, the pkg-resolver drops the hyper client // response futures when the timeouts are hit. This recovery plan requires that dropping the hyper // response future causes hyper to close the underlying TCP connection and create a new one the // next time hyper is asked to perform a network operation. This assumption holds for http1, but // not for http2. // // This test verifies the "dropping a hyper response future prevents the underlying connection // from being reused" requirement. It does so by verifying that if a resolve fails due to a blob // download timeout and the resolve is retried, the retry will cause pkg-resolver to make an // additional TCP connection to the blob mirror. // // This test uses https because the test exists to catch changes to the Fuchsia hyper client // that would cause pkg-resolver to use http2 before the Fuchsia hyper client is able to recover // from bad TCP connections when using http2. The pkg-resolver does not explicitly enable http2 // on its hyper clients, so the way this change would sneak in is if the hyper client is changed // to use ALPN to prefer http2. The blob server used in this test has ALPN configured to prefer // http2. #[fuchsia::test] async fn blob_timeout_causes_new_tcp_connection() { let pkg = PackageBuilder::new("blob_timeout_causes_new_tcp_connection").build().await.unwrap(); let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let env = TestEnvBuilder::new() .resolver_variant(ResolverVariant::ZeroBlobNetworkBodyTimeout) .build() .await; let server = repo .server() .response_overrider(responder::ForPathPrefix::new( "/blobs/", responder::Once::new(responder::HangBody), )) .use_https_domain(Domain::TestFuchsiaCom) .bind_to_addr(Ipv4Addr::LOCALHOST) .start() .expect("Starting server succeeds"); env.register_repo(&server).await; assert_eq!(server.connection_attempts(), 0); // The resolve request may not succeed despite the retry: the zero timeout on the blob body // future can fire prior to the body being downloaded on the retry. However, we expect to // observe three connections: one for the TUF client, one for the initial resolve that timed // out, and one for the retried resolve. match env.resolve_package("fuchsia-pkg://test/blob_timeout_causes_new_tcp_connection").await { Ok(_) | Err(fidl_fuchsia_pkg::ResolveError::UnavailableBlob) => {} Err(e) => { panic!("unexpected error: {:?}", e); } }; assert_eq!(server.connection_attempts(), 3); env.stop().await; }
let pkg = PackageBuilder::new("second_resolve_succeeds_when_tuf_metadata_update_fails") .build()
random_line_split
resolve_recovers_from_http_errors.rs
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// This module tests the property that pkg_resolver does not enter a bad /// state (successfully handles retries) when the TUF server errors while /// servicing fuchsia.pkg.PackageResolver.Resolve FIDL requests. use { assert_matches::assert_matches, fuchsia_merkle::MerkleTree, fuchsia_pkg_testing::{ serve::{responder, Domain, HttpResponder}, Package, PackageBuilder, RepositoryBuilder, }, lib::{ extra_blob_contents, make_pkg_with_extra_blobs, ResolverVariant, TestEnvBuilder, EMPTY_REPO_PATH, FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING, }, std::{net::Ipv4Addr, sync::Arc}, }; async fn verify_resolve_fails_then_succeeds<H: HttpResponder>( pkg: Package, responder: H, failure_error: fidl_fuchsia_pkg::ResolveError, ) { let env = TestEnvBuilder::new().build().await; let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let pkg_url = format!("fuchsia-pkg://test/{}", pkg.name()); let should_fail = responder::AtomicToggle::new(true); let served_repository = repo .server() .response_overrider(responder::Toggleable::new(&should_fail, responder)) .response_overrider(responder::Filter::new( responder::is_range_request, responder::StaticResponseCode::server_error(), )) .start() .unwrap(); env.register_repo(&served_repository).await; // First resolve fails with the expected error. assert_matches!(env.resolve_package(&pkg_url).await, Err(error) if error == failure_error); // Disabling the custom responder allows the subsequent resolves to succeed. should_fail.unset(); let (package_dir, _resolved_context) = env.resolve_package(&pkg_url).await.expect("package to resolve"); pkg.verify_contents(&package_dir).await.expect("correct package contents"); env.stop().await; } #[fuchsia::test] async fn second_resolve_succeeds_when_far_404() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_404", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn
() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_404", 1).await; let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader( extra_blob_contents("second_resolve_succeeds_when_blob_404", 0).as_slice() ) .expect("merkle slice") .root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::StaticResponseCode::not_found()), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_errors_mid_download() { let pkg = PackageBuilder::new("second_resolve_succeeds_when_far_errors_mid_download") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_errors_mid_download() { let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_when_blob_errors_mid_download") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenError), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_far_complete() { let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_far_complete") .add_resource_at( "meta/large_file", vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING].as_slice(), ) .build() .await .unwrap(); let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_disconnect_before_blob_complete() { let blob = vec![0; FILE_SIZE_LARGE_ENOUGH_TO_TRIGGER_HYPER_BATCHING]; let pkg = PackageBuilder::new("second_resolve_succeeds_disconnect_before_blob_complete") .add_resource_at("blobbity/blob", blob.as_slice()) .build() .await .unwrap(); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::UnavailableBlob, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_far_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_far_corrupted", 1).await; let path_to_override = format!("/blobs/{}", pkg.meta_far_merkle_root()); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_blob_corrupted() { let pkg = make_pkg_with_extra_blobs("second_resolve_succeeds_when_blob_corrupted", 1).await; let blob = extra_blob_contents("second_resolve_succeeds_when_blob_corrupted", 0); let path_to_override = format!( "/blobs/{}", MerkleTree::from_reader(blob.as_slice()).expect("merkle slice").root() ); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new(path_to_override, responder::OneByteFlipped), fidl_fuchsia_pkg::ResolveError::Io, ) .await } #[fuchsia::test] async fn second_resolve_succeeds_when_tuf_metadata_update_fails() { // pkg-resolver uses tuf::client::Client::with_trusted_root_keys to create its TUF client. // That method will only retrieve the specified version of the root metadata (1 for these // tests), with the rest of the metadata being retrieved during the first update. This means // that hanging all attempts for 2.snapshot.json metadata will allow tuf client creation to // succeed but still fail tuf client update. // We want to specifically verify recovery from update failure because if creation fails, // pkg-resolver will not make a Repository object, so the next resolve attempt would try again // from scratch, but if update fails, pkg-resolver will keep its Repository object which // contains a rust-tuf client in a possibly invalid state, and we want to verify that // pkg-resolver calls update on the client again and that this update recovers the client. let pkg = PackageBuilder::new("second_resolve_succeeds_when_tuf_metadata_update_fails") .build() .await .unwrap(); verify_resolve_fails_then_succeeds( pkg, responder::ForPath::new("/2.snapshot.json", responder::OneByteShortThenDisconnect), fidl_fuchsia_pkg::ResolveError::Internal, ) .await } // The hyper clients used by the pkg-resolver to download blobs and TUF metadata sometimes end up // waiting on operations on their TCP connections that will never return (e.g. because of an // upstream network partition). To detect this, the pkg-resolver wraps the hyper client response // futures with timeout futures. To recover from this, the pkg-resolver drops the hyper client // response futures when the timeouts are hit. This recovery plan requires that dropping the hyper // response future causes hyper to close the underlying TCP connection and create a new one the // next time hyper is asked to perform a network operation. This assumption holds for http1, but // not for http2. // // This test verifies the "dropping a hyper response future prevents the underlying connection // from being reused" requirement. It does so by verifying that if a resolve fails due to a blob // download timeout and the resolve is retried, the retry will cause pkg-resolver to make an // additional TCP connection to the blob mirror. // // This test uses https because the test exists to catch changes to the Fuchsia hyper client // that would cause pkg-resolver to use http2 before the Fuchsia hyper client is able to recover // from bad TCP connections when using http2. The pkg-resolver does not explicitly enable http2 // on its hyper clients, so the way this change would sneak in is if the hyper client is changed // to use ALPN to prefer http2. The blob server used in this test has ALPN configured to prefer // http2. #[fuchsia::test] async fn blob_timeout_causes_new_tcp_connection() { let pkg = PackageBuilder::new("blob_timeout_causes_new_tcp_connection").build().await.unwrap(); let repo = Arc::new( RepositoryBuilder::from_template_dir(EMPTY_REPO_PATH) .add_package(&pkg) .build() .await .unwrap(), ); let env = TestEnvBuilder::new() .resolver_variant(ResolverVariant::ZeroBlobNetworkBodyTimeout) .build() .await; let server = repo .server() .response_overrider(responder::ForPathPrefix::new( "/blobs/", responder::Once::new(responder::HangBody), )) .use_https_domain(Domain::TestFuchsiaCom) .bind_to_addr(Ipv4Addr::LOCALHOST) .start() .expect("Starting server succeeds"); env.register_repo(&server).await; assert_eq!(server.connection_attempts(), 0); // The resolve request may not succeed despite the retry: the zero timeout on the blob body // future can fire prior to the body being downloaded on the retry. However, we expect to // observe three connections: one for the TUF client, one for the initial resolve that timed // out, and one for the retried resolve. match env.resolve_package("fuchsia-pkg://test/blob_timeout_causes_new_tcp_connection").await { Ok(_) | Err(fidl_fuchsia_pkg::ResolveError::UnavailableBlob) => {} Err(e) => { panic!("unexpected error: {:?}", e); } }; assert_eq!(server.connection_attempts(), 3); env.stop().await; }
second_resolve_succeeds_when_blob_404
identifier_name
value_textbox.rs
// Copyright 2021 The Druid Authors. // // 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. //! A textbox that that parses and validates data. use tracing::instrument; use super::TextBox; use crate::text::{Formatter, Selection, TextComponent, ValidationError}; use crate::widget::prelude::*; use crate::{Data, Selector}; const BEGIN_EDITING: Selector = Selector::new("druid.builtin.textbox-begin-editing"); const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.textbox-complete-editing"); /// A `TextBox` that uses a [`Formatter`] to handle formatting and validation /// of its data. /// /// There are a number of ways to customize the behaviour of the text box /// in relation to the provided [`Formatter`]: /// /// - [`ValueTextBox::validate_while_editing`] takes a flag that determines whether /// or not the textbox can display text that is not valid, while editing is /// in progress. (Text will still be validated when the user attempts to complete /// editing.) /// /// - [`ValueTextBox::update_data_while_editing`] takes a flag that determines /// whether the output value is updated during editing, when possible. /// /// - [`ValueTextBox::delegate`] allows you to provide some implementation of /// the [`ValidationDelegate`] trait, which receives a callback during editing; /// this can be used to report errors further back up the tree. pub struct ValueTextBox<T> { child: TextBox<String>, formatter: Box<dyn Formatter<T>>, callback: Option<Box<dyn ValidationDelegate>>, is_editing: bool, validate_while_editing: bool, update_data_while_editing: bool, /// the last data that this textbox saw or created. /// This is used to determine when a change to the data is originating /// elsewhere in the application, which we need to special-case last_known_data: Option<T>, force_selection: Option<Selection>, old_buffer: String, buffer: String, } /// A type that can be registered to receive callbacks as the state of a /// [`ValueTextBox`] changes. pub trait ValidationDelegate { /// Called with a [`TextBoxEvent`] whenever the validation state of a /// [`ValueTextBox`] changes. fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, current_text: &str); } /// Events sent to a [`ValidationDelegate`]. pub enum TextBoxEvent { /// The textbox began editing. Began, /// An edit occured which was considered valid by the [`Formatter`]. Changed, /// An edit occured which was rejected by the [`Formatter`]. PartiallyInvalid(ValidationError), /// The user attempted to finish editing, but the input was not valid. Invalid(ValidationError), /// The user finished editing, with valid input. Complete, /// Editing was cancelled. Cancel, } impl TextBox<String> { /// Turn this `TextBox` into a [`ValueTextBox`], using the [`Formatter`] to /// manage the value. /// /// For simple value formatting, you can use the [`ParseFormatter`]. /// /// [`ValueTextBox`]: ValueTextBox /// [`Formatter`]: crate::text::format::Formatter /// [`ParseFormatter`]: crate::text::format::ParseFormatter pub fn with_formatter<T: Data>( self, formatter: impl Formatter<T> +'static, ) -> ValueTextBox<T> { ValueTextBox::new(self, formatter) } } impl<T: Data> ValueTextBox<T> { /// Create a new `ValueTextBox` from a normal [`TextBox`] and a [`Formatter`]. /// /// [`TextBox`]: crate::widget::TextBox /// [`Formatter`]: crate::text::format::Formatter pub fn new(mut child: TextBox<String>, formatter: impl Formatter<T> +'static) -> Self { child.text_mut().borrow_mut().send_notification_on_return = true; child.text_mut().borrow_mut().send_notification_on_cancel = true; child.handles_tab_notifications = false; ValueTextBox { child, formatter: Box::new(formatter), callback: None, is_editing: false,
last_known_data: None, validate_while_editing: true, update_data_while_editing: false, old_buffer: String::new(), buffer: String::new(), force_selection: None, } } /// Builder-style method to set an optional [`ValidationDelegate`] on this /// textbox. pub fn delegate(mut self, delegate: impl ValidationDelegate +'static) -> Self { self.callback = Some(Box::new(delegate)); self } /// Builder-style method to set whether or not this text box validates /// its contents during editing. /// /// If `true` (the default) edits that fail validation /// ([`Formatter::validate_partial_input`]) will be rejected. If `false`, /// those edits will be accepted, and the text box will be updated. pub fn validate_while_editing(mut self, validate: bool) -> Self { self.validate_while_editing = validate; self } /// Builder-style method to set whether or not this text box updates the /// incoming data during editing. /// /// If `false` (the default) the data is only updated when editing completes. pub fn update_data_while_editing(mut self, flag: bool) -> Self { self.update_data_while_editing = flag; self } fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) -> bool { match self.formatter.value(&self.buffer) { Ok(new_data) => { *data = new_data; self.buffer = self.formatter.format(data); self.is_editing = false; ctx.request_update(); self.send_event(ctx, TextBoxEvent::Complete); true } Err(err) => { if self.child.text().can_write() { if let Some(inval) = self .child .text_mut() .borrow_mut() .set_selection(Selection::new(0, self.buffer.len())) { ctx.invalidate_text_input(inval); } } self.send_event(ctx, TextBoxEvent::Invalid(err)); // our content isn't valid // ideally we would flash the background or something false } } } fn cancel(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = false; self.buffer = self.formatter.format(data); ctx.request_update(); ctx.resign_focus(); self.send_event(ctx, TextBoxEvent::Cancel); } fn begin(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = true; self.buffer = self.formatter.format_for_editing(data); self.last_known_data = Some(data.clone()); ctx.request_update(); self.send_event(ctx, TextBoxEvent::Began); } fn send_event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent) { if let Some(delegate) = self.callback.as_mut() { delegate.event(ctx, event, &self.buffer) } } } impl<T: Data + std::fmt::Debug> Widget<T> for ValueTextBox<T> { #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if matches!(event, Event::Command(cmd) if cmd.is(BEGIN_EDITING)) { return self.begin(ctx, data); } if self.is_editing { // if we reject an edit we want to reset the selection let pre_sel = if self.child.text().can_read() { Some(self.child.text().borrow().selection()) } else { None }; match event { // this is caused by an external focus change, like the mouse being clicked // elsewhere. Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => { if!self.complete(ctx, data) { self.cancel(ctx, data); } return; } Event::Notification(cmd) if cmd.is(TextComponent::TAB) => { ctx.set_handled(); ctx.request_paint(); if self.complete(ctx, data) { ctx.focus_next(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::BACKTAB) => { ctx.request_paint(); ctx.set_handled(); if self.complete(ctx, data) { ctx.focus_prev(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::RETURN) => { ctx.set_handled(); if self.complete(ctx, data) { ctx.resign_focus(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::CANCEL) => { ctx.set_handled(); self.cancel(ctx, data); return; } event => { self.child.event(ctx, event, &mut self.buffer, env); } } // if an edit occured, validate it with the formatter // notifications can arrive before update, so we always ignore them if!matches!(event, Event::Notification(_)) && self.buffer!= self.old_buffer { let mut validation = self .formatter .validate_partial_input(&self.buffer, &self.child.text().borrow().selection()); if self.validate_while_editing { let new_buf = match (validation.text_change.take(), validation.is_err()) { (Some(new_text), _) => { // be helpful: if the formatter is misbehaved, log it. if self .formatter .validate_partial_input(&new_text, &Selection::caret(0)) .is_err() { tracing::warn!( "formatter replacement text does not validate: '{}'", &new_text ); None } else { Some(new_text) } } (None, true) => Some(self.old_buffer.clone()), _ => None, }; let new_sel = match (validation.selection_change.take(), validation.is_err()) { (Some(new_sel), _) => Some(new_sel), (None, true) if pre_sel.is_some() => pre_sel, _ => None, }; if let Some(new_buf) = new_buf { self.buffer = new_buf; } self.force_selection = new_sel; if self.update_data_while_editing &&!validation.is_err() { if let Ok(new_data) = self.formatter.value(&self.buffer) { *data = new_data; self.last_known_data = Some(data.clone()); } } } match validation.error() { Some(err) => { self.send_event(ctx, TextBoxEvent::PartiallyInvalid(err.to_owned())) } None => self.send_event(ctx, TextBoxEvent::Changed), }; ctx.request_update(); } // if we *aren't* editing: } else { if let Event::MouseDown(_) = event { self.begin(ctx, data); } self.child.event(ctx, event, &mut self.buffer, env); } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { self.buffer = self.formatter.format(data); self.old_buffer = self.buffer.clone(); } LifeCycle::FocusChanged(true) if!self.is_editing => { ctx.submit_command(BEGIN_EDITING.to(ctx.widget_id())); } LifeCycle::FocusChanged(false) => { ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id())); } _ => (), } self.child.lifecycle(ctx, event, &self.buffer, env); } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, old, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) { if let Some(sel) = self.force_selection.take() { if self.child.text().can_write() { if let Some(change) = self.child.text_mut().borrow_mut().set_selection(sel) { ctx.invalidate_text_input(change); } } } let changed_by_us = self .last_known_data .as_ref() .map(|d| d.same(data)) .unwrap_or(false); if self.is_editing { if changed_by_us { self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else { // textbox is not well equipped to deal with the fact that, in // druid, data can change anywhere in the tree. If we are actively // editing, and new data arrives, we ignore the new data and keep // editing; the alternative would be to cancel editing, which // could also make sense. tracing::warn!( "ValueTextBox data changed externally, idk: '{}'", self.formatter.format(data) ); } } else { if!old.same(data) { // we aren't editing and data changed let new_text = self.formatter.format(data); // it's possible for different data inputs to produce the same formatted // output, in which case we would overwrite our actual previous data if!new_text.same(&self.buffer) { self.old_buffer = std::mem::replace(&mut self.buffer, new_text); } } if!self.old_buffer.same(&self.buffer) { // child widget handles calling request_layout, as needed self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else if ctx.env_changed() { self.child.update(ctx, &self.buffer, &self.buffer, env); } } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, bc, _data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, &self.buffer, env) } #[instrument(name = "ValueTextBox", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { self.child.paint(ctx, &self.buffer, env); } }
random_line_split
value_textbox.rs
// Copyright 2021 The Druid Authors. // // 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. //! A textbox that that parses and validates data. use tracing::instrument; use super::TextBox; use crate::text::{Formatter, Selection, TextComponent, ValidationError}; use crate::widget::prelude::*; use crate::{Data, Selector}; const BEGIN_EDITING: Selector = Selector::new("druid.builtin.textbox-begin-editing"); const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.textbox-complete-editing"); /// A `TextBox` that uses a [`Formatter`] to handle formatting and validation /// of its data. /// /// There are a number of ways to customize the behaviour of the text box /// in relation to the provided [`Formatter`]: /// /// - [`ValueTextBox::validate_while_editing`] takes a flag that determines whether /// or not the textbox can display text that is not valid, while editing is /// in progress. (Text will still be validated when the user attempts to complete /// editing.) /// /// - [`ValueTextBox::update_data_while_editing`] takes a flag that determines /// whether the output value is updated during editing, when possible. /// /// - [`ValueTextBox::delegate`] allows you to provide some implementation of /// the [`ValidationDelegate`] trait, which receives a callback during editing; /// this can be used to report errors further back up the tree. pub struct ValueTextBox<T> { child: TextBox<String>, formatter: Box<dyn Formatter<T>>, callback: Option<Box<dyn ValidationDelegate>>, is_editing: bool, validate_while_editing: bool, update_data_while_editing: bool, /// the last data that this textbox saw or created. /// This is used to determine when a change to the data is originating /// elsewhere in the application, which we need to special-case last_known_data: Option<T>, force_selection: Option<Selection>, old_buffer: String, buffer: String, } /// A type that can be registered to receive callbacks as the state of a /// [`ValueTextBox`] changes. pub trait ValidationDelegate { /// Called with a [`TextBoxEvent`] whenever the validation state of a /// [`ValueTextBox`] changes. fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, current_text: &str); } /// Events sent to a [`ValidationDelegate`]. pub enum TextBoxEvent { /// The textbox began editing. Began, /// An edit occured which was considered valid by the [`Formatter`]. Changed, /// An edit occured which was rejected by the [`Formatter`]. PartiallyInvalid(ValidationError), /// The user attempted to finish editing, but the input was not valid. Invalid(ValidationError), /// The user finished editing, with valid input. Complete, /// Editing was cancelled. Cancel, } impl TextBox<String> { /// Turn this `TextBox` into a [`ValueTextBox`], using the [`Formatter`] to /// manage the value. /// /// For simple value formatting, you can use the [`ParseFormatter`]. /// /// [`ValueTextBox`]: ValueTextBox /// [`Formatter`]: crate::text::format::Formatter /// [`ParseFormatter`]: crate::text::format::ParseFormatter pub fn with_formatter<T: Data>( self, formatter: impl Formatter<T> +'static, ) -> ValueTextBox<T> { ValueTextBox::new(self, formatter) } } impl<T: Data> ValueTextBox<T> { /// Create a new `ValueTextBox` from a normal [`TextBox`] and a [`Formatter`]. /// /// [`TextBox`]: crate::widget::TextBox /// [`Formatter`]: crate::text::format::Formatter pub fn new(mut child: TextBox<String>, formatter: impl Formatter<T> +'static) -> Self { child.text_mut().borrow_mut().send_notification_on_return = true; child.text_mut().borrow_mut().send_notification_on_cancel = true; child.handles_tab_notifications = false; ValueTextBox { child, formatter: Box::new(formatter), callback: None, is_editing: false, last_known_data: None, validate_while_editing: true, update_data_while_editing: false, old_buffer: String::new(), buffer: String::new(), force_selection: None, } } /// Builder-style method to set an optional [`ValidationDelegate`] on this /// textbox. pub fn delegate(mut self, delegate: impl ValidationDelegate +'static) -> Self { self.callback = Some(Box::new(delegate)); self } /// Builder-style method to set whether or not this text box validates /// its contents during editing. /// /// If `true` (the default) edits that fail validation /// ([`Formatter::validate_partial_input`]) will be rejected. If `false`, /// those edits will be accepted, and the text box will be updated. pub fn validate_while_editing(mut self, validate: bool) -> Self { self.validate_while_editing = validate; self } /// Builder-style method to set whether or not this text box updates the /// incoming data during editing. /// /// If `false` (the default) the data is only updated when editing completes. pub fn update_data_while_editing(mut self, flag: bool) -> Self { self.update_data_while_editing = flag; self } fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) -> bool { match self.formatter.value(&self.buffer) { Ok(new_data) => { *data = new_data; self.buffer = self.formatter.format(data); self.is_editing = false; ctx.request_update(); self.send_event(ctx, TextBoxEvent::Complete); true } Err(err) => { if self.child.text().can_write() { if let Some(inval) = self .child .text_mut() .borrow_mut() .set_selection(Selection::new(0, self.buffer.len())) { ctx.invalidate_text_input(inval); } } self.send_event(ctx, TextBoxEvent::Invalid(err)); // our content isn't valid // ideally we would flash the background or something false } } } fn
(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = false; self.buffer = self.formatter.format(data); ctx.request_update(); ctx.resign_focus(); self.send_event(ctx, TextBoxEvent::Cancel); } fn begin(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = true; self.buffer = self.formatter.format_for_editing(data); self.last_known_data = Some(data.clone()); ctx.request_update(); self.send_event(ctx, TextBoxEvent::Began); } fn send_event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent) { if let Some(delegate) = self.callback.as_mut() { delegate.event(ctx, event, &self.buffer) } } } impl<T: Data + std::fmt::Debug> Widget<T> for ValueTextBox<T> { #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if matches!(event, Event::Command(cmd) if cmd.is(BEGIN_EDITING)) { return self.begin(ctx, data); } if self.is_editing { // if we reject an edit we want to reset the selection let pre_sel = if self.child.text().can_read() { Some(self.child.text().borrow().selection()) } else { None }; match event { // this is caused by an external focus change, like the mouse being clicked // elsewhere. Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => { if!self.complete(ctx, data) { self.cancel(ctx, data); } return; } Event::Notification(cmd) if cmd.is(TextComponent::TAB) => { ctx.set_handled(); ctx.request_paint(); if self.complete(ctx, data) { ctx.focus_next(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::BACKTAB) => { ctx.request_paint(); ctx.set_handled(); if self.complete(ctx, data) { ctx.focus_prev(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::RETURN) => { ctx.set_handled(); if self.complete(ctx, data) { ctx.resign_focus(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::CANCEL) => { ctx.set_handled(); self.cancel(ctx, data); return; } event => { self.child.event(ctx, event, &mut self.buffer, env); } } // if an edit occured, validate it with the formatter // notifications can arrive before update, so we always ignore them if!matches!(event, Event::Notification(_)) && self.buffer!= self.old_buffer { let mut validation = self .formatter .validate_partial_input(&self.buffer, &self.child.text().borrow().selection()); if self.validate_while_editing { let new_buf = match (validation.text_change.take(), validation.is_err()) { (Some(new_text), _) => { // be helpful: if the formatter is misbehaved, log it. if self .formatter .validate_partial_input(&new_text, &Selection::caret(0)) .is_err() { tracing::warn!( "formatter replacement text does not validate: '{}'", &new_text ); None } else { Some(new_text) } } (None, true) => Some(self.old_buffer.clone()), _ => None, }; let new_sel = match (validation.selection_change.take(), validation.is_err()) { (Some(new_sel), _) => Some(new_sel), (None, true) if pre_sel.is_some() => pre_sel, _ => None, }; if let Some(new_buf) = new_buf { self.buffer = new_buf; } self.force_selection = new_sel; if self.update_data_while_editing &&!validation.is_err() { if let Ok(new_data) = self.formatter.value(&self.buffer) { *data = new_data; self.last_known_data = Some(data.clone()); } } } match validation.error() { Some(err) => { self.send_event(ctx, TextBoxEvent::PartiallyInvalid(err.to_owned())) } None => self.send_event(ctx, TextBoxEvent::Changed), }; ctx.request_update(); } // if we *aren't* editing: } else { if let Event::MouseDown(_) = event { self.begin(ctx, data); } self.child.event(ctx, event, &mut self.buffer, env); } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { self.buffer = self.formatter.format(data); self.old_buffer = self.buffer.clone(); } LifeCycle::FocusChanged(true) if!self.is_editing => { ctx.submit_command(BEGIN_EDITING.to(ctx.widget_id())); } LifeCycle::FocusChanged(false) => { ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id())); } _ => (), } self.child.lifecycle(ctx, event, &self.buffer, env); } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, old, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) { if let Some(sel) = self.force_selection.take() { if self.child.text().can_write() { if let Some(change) = self.child.text_mut().borrow_mut().set_selection(sel) { ctx.invalidate_text_input(change); } } } let changed_by_us = self .last_known_data .as_ref() .map(|d| d.same(data)) .unwrap_or(false); if self.is_editing { if changed_by_us { self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else { // textbox is not well equipped to deal with the fact that, in // druid, data can change anywhere in the tree. If we are actively // editing, and new data arrives, we ignore the new data and keep // editing; the alternative would be to cancel editing, which // could also make sense. tracing::warn!( "ValueTextBox data changed externally, idk: '{}'", self.formatter.format(data) ); } } else { if!old.same(data) { // we aren't editing and data changed let new_text = self.formatter.format(data); // it's possible for different data inputs to produce the same formatted // output, in which case we would overwrite our actual previous data if!new_text.same(&self.buffer) { self.old_buffer = std::mem::replace(&mut self.buffer, new_text); } } if!self.old_buffer.same(&self.buffer) { // child widget handles calling request_layout, as needed self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else if ctx.env_changed() { self.child.update(ctx, &self.buffer, &self.buffer, env); } } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, bc, _data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, &self.buffer, env) } #[instrument(name = "ValueTextBox", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { self.child.paint(ctx, &self.buffer, env); } }
cancel
identifier_name
value_textbox.rs
// Copyright 2021 The Druid Authors. // // 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. //! A textbox that that parses and validates data. use tracing::instrument; use super::TextBox; use crate::text::{Formatter, Selection, TextComponent, ValidationError}; use crate::widget::prelude::*; use crate::{Data, Selector}; const BEGIN_EDITING: Selector = Selector::new("druid.builtin.textbox-begin-editing"); const COMPLETE_EDITING: Selector = Selector::new("druid.builtin.textbox-complete-editing"); /// A `TextBox` that uses a [`Formatter`] to handle formatting and validation /// of its data. /// /// There are a number of ways to customize the behaviour of the text box /// in relation to the provided [`Formatter`]: /// /// - [`ValueTextBox::validate_while_editing`] takes a flag that determines whether /// or not the textbox can display text that is not valid, while editing is /// in progress. (Text will still be validated when the user attempts to complete /// editing.) /// /// - [`ValueTextBox::update_data_while_editing`] takes a flag that determines /// whether the output value is updated during editing, when possible. /// /// - [`ValueTextBox::delegate`] allows you to provide some implementation of /// the [`ValidationDelegate`] trait, which receives a callback during editing; /// this can be used to report errors further back up the tree. pub struct ValueTextBox<T> { child: TextBox<String>, formatter: Box<dyn Formatter<T>>, callback: Option<Box<dyn ValidationDelegate>>, is_editing: bool, validate_while_editing: bool, update_data_while_editing: bool, /// the last data that this textbox saw or created. /// This is used to determine when a change to the data is originating /// elsewhere in the application, which we need to special-case last_known_data: Option<T>, force_selection: Option<Selection>, old_buffer: String, buffer: String, } /// A type that can be registered to receive callbacks as the state of a /// [`ValueTextBox`] changes. pub trait ValidationDelegate { /// Called with a [`TextBoxEvent`] whenever the validation state of a /// [`ValueTextBox`] changes. fn event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent, current_text: &str); } /// Events sent to a [`ValidationDelegate`]. pub enum TextBoxEvent { /// The textbox began editing. Began, /// An edit occured which was considered valid by the [`Formatter`]. Changed, /// An edit occured which was rejected by the [`Formatter`]. PartiallyInvalid(ValidationError), /// The user attempted to finish editing, but the input was not valid. Invalid(ValidationError), /// The user finished editing, with valid input. Complete, /// Editing was cancelled. Cancel, } impl TextBox<String> { /// Turn this `TextBox` into a [`ValueTextBox`], using the [`Formatter`] to /// manage the value. /// /// For simple value formatting, you can use the [`ParseFormatter`]. /// /// [`ValueTextBox`]: ValueTextBox /// [`Formatter`]: crate::text::format::Formatter /// [`ParseFormatter`]: crate::text::format::ParseFormatter pub fn with_formatter<T: Data>( self, formatter: impl Formatter<T> +'static, ) -> ValueTextBox<T> { ValueTextBox::new(self, formatter) } } impl<T: Data> ValueTextBox<T> { /// Create a new `ValueTextBox` from a normal [`TextBox`] and a [`Formatter`]. /// /// [`TextBox`]: crate::widget::TextBox /// [`Formatter`]: crate::text::format::Formatter pub fn new(mut child: TextBox<String>, formatter: impl Formatter<T> +'static) -> Self { child.text_mut().borrow_mut().send_notification_on_return = true; child.text_mut().borrow_mut().send_notification_on_cancel = true; child.handles_tab_notifications = false; ValueTextBox { child, formatter: Box::new(formatter), callback: None, is_editing: false, last_known_data: None, validate_while_editing: true, update_data_while_editing: false, old_buffer: String::new(), buffer: String::new(), force_selection: None, } } /// Builder-style method to set an optional [`ValidationDelegate`] on this /// textbox. pub fn delegate(mut self, delegate: impl ValidationDelegate +'static) -> Self { self.callback = Some(Box::new(delegate)); self } /// Builder-style method to set whether or not this text box validates /// its contents during editing. /// /// If `true` (the default) edits that fail validation /// ([`Formatter::validate_partial_input`]) will be rejected. If `false`, /// those edits will be accepted, and the text box will be updated. pub fn validate_while_editing(mut self, validate: bool) -> Self { self.validate_while_editing = validate; self } /// Builder-style method to set whether or not this text box updates the /// incoming data during editing. /// /// If `false` (the default) the data is only updated when editing completes. pub fn update_data_while_editing(mut self, flag: bool) -> Self { self.update_data_while_editing = flag; self } fn complete(&mut self, ctx: &mut EventCtx, data: &mut T) -> bool
} self.send_event(ctx, TextBoxEvent::Invalid(err)); // our content isn't valid // ideally we would flash the background or something false } } } fn cancel(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = false; self.buffer = self.formatter.format(data); ctx.request_update(); ctx.resign_focus(); self.send_event(ctx, TextBoxEvent::Cancel); } fn begin(&mut self, ctx: &mut EventCtx, data: &T) { self.is_editing = true; self.buffer = self.formatter.format_for_editing(data); self.last_known_data = Some(data.clone()); ctx.request_update(); self.send_event(ctx, TextBoxEvent::Began); } fn send_event(&mut self, ctx: &mut EventCtx, event: TextBoxEvent) { if let Some(delegate) = self.callback.as_mut() { delegate.event(ctx, event, &self.buffer) } } } impl<T: Data + std::fmt::Debug> Widget<T> for ValueTextBox<T> { #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut T, env: &Env) { if matches!(event, Event::Command(cmd) if cmd.is(BEGIN_EDITING)) { return self.begin(ctx, data); } if self.is_editing { // if we reject an edit we want to reset the selection let pre_sel = if self.child.text().can_read() { Some(self.child.text().borrow().selection()) } else { None }; match event { // this is caused by an external focus change, like the mouse being clicked // elsewhere. Event::Command(cmd) if cmd.is(COMPLETE_EDITING) => { if!self.complete(ctx, data) { self.cancel(ctx, data); } return; } Event::Notification(cmd) if cmd.is(TextComponent::TAB) => { ctx.set_handled(); ctx.request_paint(); if self.complete(ctx, data) { ctx.focus_next(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::BACKTAB) => { ctx.request_paint(); ctx.set_handled(); if self.complete(ctx, data) { ctx.focus_prev(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::RETURN) => { ctx.set_handled(); if self.complete(ctx, data) { ctx.resign_focus(); } return; } Event::Notification(cmd) if cmd.is(TextComponent::CANCEL) => { ctx.set_handled(); self.cancel(ctx, data); return; } event => { self.child.event(ctx, event, &mut self.buffer, env); } } // if an edit occured, validate it with the formatter // notifications can arrive before update, so we always ignore them if!matches!(event, Event::Notification(_)) && self.buffer!= self.old_buffer { let mut validation = self .formatter .validate_partial_input(&self.buffer, &self.child.text().borrow().selection()); if self.validate_while_editing { let new_buf = match (validation.text_change.take(), validation.is_err()) { (Some(new_text), _) => { // be helpful: if the formatter is misbehaved, log it. if self .formatter .validate_partial_input(&new_text, &Selection::caret(0)) .is_err() { tracing::warn!( "formatter replacement text does not validate: '{}'", &new_text ); None } else { Some(new_text) } } (None, true) => Some(self.old_buffer.clone()), _ => None, }; let new_sel = match (validation.selection_change.take(), validation.is_err()) { (Some(new_sel), _) => Some(new_sel), (None, true) if pre_sel.is_some() => pre_sel, _ => None, }; if let Some(new_buf) = new_buf { self.buffer = new_buf; } self.force_selection = new_sel; if self.update_data_while_editing &&!validation.is_err() { if let Ok(new_data) = self.formatter.value(&self.buffer) { *data = new_data; self.last_known_data = Some(data.clone()); } } } match validation.error() { Some(err) => { self.send_event(ctx, TextBoxEvent::PartiallyInvalid(err.to_owned())) } None => self.send_event(ctx, TextBoxEvent::Changed), }; ctx.request_update(); } // if we *aren't* editing: } else { if let Event::MouseDown(_) = event { self.begin(ctx, data); } self.child.event(ctx, event, &mut self.buffer, env); } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, event, data, env) )] fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &T, env: &Env) { match event { LifeCycle::WidgetAdded => { self.buffer = self.formatter.format(data); self.old_buffer = self.buffer.clone(); } LifeCycle::FocusChanged(true) if!self.is_editing => { ctx.submit_command(BEGIN_EDITING.to(ctx.widget_id())); } LifeCycle::FocusChanged(false) => { ctx.submit_command(COMPLETE_EDITING.to(ctx.widget_id())); } _ => (), } self.child.lifecycle(ctx, event, &self.buffer, env); } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, old, data, env) )] fn update(&mut self, ctx: &mut UpdateCtx, old: &T, data: &T, env: &Env) { if let Some(sel) = self.force_selection.take() { if self.child.text().can_write() { if let Some(change) = self.child.text_mut().borrow_mut().set_selection(sel) { ctx.invalidate_text_input(change); } } } let changed_by_us = self .last_known_data .as_ref() .map(|d| d.same(data)) .unwrap_or(false); if self.is_editing { if changed_by_us { self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else { // textbox is not well equipped to deal with the fact that, in // druid, data can change anywhere in the tree. If we are actively // editing, and new data arrives, we ignore the new data and keep // editing; the alternative would be to cancel editing, which // could also make sense. tracing::warn!( "ValueTextBox data changed externally, idk: '{}'", self.formatter.format(data) ); } } else { if!old.same(data) { // we aren't editing and data changed let new_text = self.formatter.format(data); // it's possible for different data inputs to produce the same formatted // output, in which case we would overwrite our actual previous data if!new_text.same(&self.buffer) { self.old_buffer = std::mem::replace(&mut self.buffer, new_text); } } if!self.old_buffer.same(&self.buffer) { // child widget handles calling request_layout, as needed self.child.update(ctx, &self.old_buffer, &self.buffer, env); self.old_buffer = self.buffer.clone(); } else if ctx.env_changed() { self.child.update(ctx, &self.buffer, &self.buffer, env); } } } #[instrument( name = "ValueTextBox", level = "trace", skip(self, ctx, bc, _data, env) )] fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &T, env: &Env) -> Size { self.child.layout(ctx, bc, &self.buffer, env) } #[instrument(name = "ValueTextBox", level = "trace", skip(self, ctx, _data, env))] fn paint(&mut self, ctx: &mut PaintCtx, _data: &T, env: &Env) { self.child.paint(ctx, &self.buffer, env); } }
{ match self.formatter.value(&self.buffer) { Ok(new_data) => { *data = new_data; self.buffer = self.formatter.format(data); self.is_editing = false; ctx.request_update(); self.send_event(ctx, TextBoxEvent::Complete); true } Err(err) => { if self.child.text().can_write() { if let Some(inval) = self .child .text_mut() .borrow_mut() .set_selection(Selection::new(0, self.buffer.len())) { ctx.invalidate_text_input(inval); }
identifier_body
has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasLoc impl. /// /// The build rules are as follows: /// - For a struct it just looks for a field with a type of LocId. /// - For an enum it does a match on each variant. /// - For either tuple variants or struct variants it looks for a field with a /// type of LocId. /// - For a tuple variant with a single non-LocId type and calls `.loc_id()` /// on that field. /// - Otherwise you can specify `#[has_loc(n)]` where `n` is the index of the /// field to call `.loc_id()` on. `#[has_loc(n)]` can also be used on the /// whole enum to provide a default index. /// pub(crate) fn
(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_loc_enum(&input, data), Data::Struct(data) => build_has_loc_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_loc_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "ClassId" || ident == "ConstId" || ident == "ValueId" || ident == "LocalId" || ident == "MethodId" || ident == "ParamId" || ident == "VarId" || ident == "usize" || ident == "u32") } else { true } } fn build_has_loc_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let default_select_field = handle_has_loc_attr(&input.attrs)?; let loc_field = if let Some(f) = default_select_field { match f.kind { FieldKind::Named(name) => { let name = name.to_string(); let field = data .fields .iter() .find(|field| field.ident.as_ref().map_or(false, |id| id == &name)) .ok_or_else(|| Error::new(input.span(), format!("Field '{name}' not found")))? .ident .as_ref() .unwrap(); quote!(#field.loc_id()) } FieldKind::None => todo!(), FieldKind::Numbered(_) => todo!(), } } else { let field = data .fields .iter() .enumerate() .map(|(i, field)| (i, field, SimpleType::from_type(&field.ty))) .find(|(_, _, ty)| ty.is_based_on("LocId")); let (idx, field, _) = field.ok_or_else(|| Error::new(input.span(), "No field with type LocId found"))?; if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() } }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #struct_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { self.#loc_field } }); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_loc_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("LocId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar {.., loc: LocId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., LocId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_loc_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to LocId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } match interesting_fields { InterestingFields::None => { let kind = FieldKind::None; let ty = SimpleType::Unknown; Ok(Some(Field { kind, ty })) } InterestingFields::One(idx, ident, ty) => { // There's only a single field that could possibly contain a buried // LocId. let kind = ident.map_or_else( || FieldKind::Numbered(idx), |id| FieldKind::Named(Cow::Borrowed(id)), ); Ok(Some(Field { kind, ty })) } InterestingFields::Many => Ok(None), } } fn build_has_loc_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz {.., loc: LocId }, // } let default_select_field = handle_has_loc_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("LocId field not found in variant {}", variant.ident,), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #enum_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { match self { #(#variants),* } } }); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = match (&field.kind, &field.ty) { (FieldKind::None, _) => quote!(LocId::NONE), (_, SimpleType::Unknown) => quote!(f.loc_id()), (_, SimpleType::Unit(_)) => quote!(*f), (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) | (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled type: {:?}", field.ty) } }; let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f,.. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({.. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(quote!(#enum_name::#variant_name #params => #reference)); } fn handle_has_loc_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_loc") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // has_loc(A, B, C) if list.nested.len()!= 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown, })); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_list) => { todo!(); } } } } Ok(None) }
build_has_loc
identifier_name
has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasLoc impl. /// /// The build rules are as follows: /// - For a struct it just looks for a field with a type of LocId. /// - For an enum it does a match on each variant. /// - For either tuple variants or struct variants it looks for a field with a /// type of LocId. /// - For a tuple variant with a single non-LocId type and calls `.loc_id()` /// on that field. /// - Otherwise you can specify `#[has_loc(n)]` where `n` is the index of the /// field to call `.loc_id()` on. `#[has_loc(n)]` can also be used on the /// whole enum to provide a default index. /// pub(crate) fn build_has_loc(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_loc_enum(&input, data), Data::Struct(data) => build_has_loc_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_loc_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "ClassId" || ident == "ConstId" || ident == "ValueId" || ident == "LocalId" || ident == "MethodId" || ident == "ParamId" || ident == "VarId" || ident == "usize" || ident == "u32") } else { true } } fn build_has_loc_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream> { // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let default_select_field = handle_has_loc_attr(&input.attrs)?; let loc_field = if let Some(f) = default_select_field { match f.kind { FieldKind::Named(name) => { let name = name.to_string(); let field = data .fields .iter() .find(|field| field.ident.as_ref().map_or(false, |id| id == &name)) .ok_or_else(|| Error::new(input.span(), format!("Field '{name}' not found")))? .ident .as_ref() .unwrap(); quote!(#field.loc_id()) } FieldKind::None => todo!(), FieldKind::Numbered(_) => todo!(), } } else { let field = data .fields .iter() .enumerate() .map(|(i, field)| (i, field, SimpleType::from_type(&field.ty))) .find(|(_, _, ty)| ty.is_based_on("LocId")); let (idx, field, _) = field.ok_or_else(|| Error::new(input.span(), "No field with type LocId found"))?; if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() } }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #struct_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { self.#loc_field } }); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_loc_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("LocId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar {.., loc: LocId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., LocId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_loc_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to LocId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } match interesting_fields { InterestingFields::None => { let kind = FieldKind::None; let ty = SimpleType::Unknown; Ok(Some(Field { kind, ty })) } InterestingFields::One(idx, ident, ty) => { // There's only a single field that could possibly contain a buried // LocId. let kind = ident.map_or_else( || FieldKind::Numbered(idx), |id| FieldKind::Named(Cow::Borrowed(id)), ); Ok(Some(Field { kind, ty })) } InterestingFields::Many => Ok(None), } } fn build_has_loc_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz {.., loc: LocId }, // } let default_select_field = handle_has_loc_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("LocId field not found in variant {}", variant.ident,), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #enum_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { match self { #(#variants),* } } }); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = match (&field.kind, &field.ty) { (FieldKind::None, _) => quote!(LocId::NONE), (_, SimpleType::Unknown) => quote!(f.loc_id()), (_, SimpleType::Unit(_)) => quote!(*f), (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) | (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled type: {:?}", field.ty) } }; let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f,.. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({.. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(quote!(#enum_name::#variant_name #params => #reference)); } fn handle_has_loc_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_loc") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // has_loc(A, B, C) if list.nested.len()!= 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown,
})); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_list) => { todo!(); } } } } Ok(None) }
random_line_split
has_loc.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use std::borrow::Cow; use proc_macro2::Ident; use proc_macro2::Span; use proc_macro2::TokenStream; use quote::quote; use quote::ToTokens; use syn::spanned::Spanned; use syn::Attribute; use syn::Data; use syn::DataEnum; use syn::DataStruct; use syn::DeriveInput; use syn::Error; use syn::Lit; use syn::Meta; use syn::NestedMeta; use syn::Result; use syn::Variant; use crate::simple_type::SimpleType; use crate::util::InterestingFields; /// Builds a HasLoc impl. /// /// The build rules are as follows: /// - For a struct it just looks for a field with a type of LocId. /// - For an enum it does a match on each variant. /// - For either tuple variants or struct variants it looks for a field with a /// type of LocId. /// - For a tuple variant with a single non-LocId type and calls `.loc_id()` /// on that field. /// - Otherwise you can specify `#[has_loc(n)]` where `n` is the index of the /// field to call `.loc_id()` on. `#[has_loc(n)]` can also be used on the /// whole enum to provide a default index. /// pub(crate) fn build_has_loc(input: TokenStream) -> Result<TokenStream> { let input = syn::parse2::<DeriveInput>(input)?; match &input.data { Data::Enum(data) => build_has_loc_enum(&input, data), Data::Struct(data) => build_has_loc_struct(&input, data), Data::Union(_) => Err(Error::new(input.span(), "Union not handled")), } } fn field_might_contain_buried_loc_id(ty: &SimpleType<'_>) -> bool { if let Some(ident) = ty.get_ident() { !(ident == "BlockId" || ident == "ClassId" || ident == "ConstId" || ident == "ValueId" || ident == "LocalId" || ident == "MethodId" || ident == "ParamId" || ident == "VarId" || ident == "usize" || ident == "u32") } else { true } } fn build_has_loc_struct(input: &DeriveInput, data: &DataStruct) -> Result<TokenStream>
quote!(#field.loc_id()) } FieldKind::None => todo!(), FieldKind::Numbered(_) => todo!(), } } else { let field = data .fields .iter() .enumerate() .map(|(i, field)| (i, field, SimpleType::from_type(&field.ty))) .find(|(_, _, ty)| ty.is_based_on("LocId")); let (idx, field, _) = field.ok_or_else(|| Error::new(input.span(), "No field with type LocId found"))?; if let Some(ident) = field.ident.as_ref() { ident.to_token_stream() } else { syn::Index::from(idx).to_token_stream() } }; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #struct_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { self.#loc_field } }); Ok(output) } fn get_select_field<'a>( variant: &'a Variant, default_select_field: &Option<Field<'a>>, ) -> Result<Option<Field<'a>>> { if let Some(f) = handle_has_loc_attr(&variant.attrs)? { return Ok(Some(f)); } if let Some(f) = default_select_field.as_ref() { return Ok(Some(f.clone())); } let mut interesting_fields = InterestingFields::None; for (idx, field) in variant.fields.iter().enumerate() { let ty = SimpleType::from_type(&field.ty); if ty.is_based_on("LocId") { let kind = if let Some(ident) = field.ident.as_ref() { // Bar {.., loc: LocId } FieldKind::Named(Cow::Borrowed(ident)) } else { // Bar(.., LocId) FieldKind::Numbered(idx) }; return Ok(Some(Field { kind, ty })); } else if field_might_contain_buried_loc_id(&ty) { // Report the type as 'unknown' because it's not a type that's // related to LocId. interesting_fields.add(idx, field.ident.as_ref(), SimpleType::Unknown); } } match interesting_fields { InterestingFields::None => { let kind = FieldKind::None; let ty = SimpleType::Unknown; Ok(Some(Field { kind, ty })) } InterestingFields::One(idx, ident, ty) => { // There's only a single field that could possibly contain a buried // LocId. let kind = ident.map_or_else( || FieldKind::Numbered(idx), |id| FieldKind::Named(Cow::Borrowed(id)), ); Ok(Some(Field { kind, ty })) } InterestingFields::Many => Ok(None), } } fn build_has_loc_enum(input: &DeriveInput, data: &DataEnum) -> Result<TokenStream> { // enum Foo { // Bar(.., LocId), // Baz {.., loc: LocId }, // } let default_select_field = handle_has_loc_attr(&input.attrs)?; let enum_name = &input.ident; let mut variants: Vec<TokenStream> = Vec::new(); for variant in data.variants.iter() { let select_field = get_select_field(variant, &default_select_field)?; if let Some(select_field) = select_field { push_handler(&mut variants, enum_name, variant, select_field); } else { return Err(Error::new( variant.span(), format!("LocId field not found in variant {}", variant.ident,), )); } } let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = quote!(impl #impl_generics HasLoc for #enum_name #ty_generics #where_clause { fn loc_id(&self) -> LocId { match self { #(#variants),* } } }); Ok(output) } #[derive(Clone)] struct Field<'a> { kind: FieldKind<'a>, ty: SimpleType<'a>, } #[derive(Clone)] enum FieldKind<'a> { Named(Cow<'a, Ident>), None, Numbered(usize), } fn push_handler( variants: &mut Vec<TokenStream>, enum_name: &Ident, variant: &Variant, field: Field<'_>, ) { let variant_name = &variant.ident; let reference = match (&field.kind, &field.ty) { (FieldKind::None, _) => quote!(LocId::NONE), (_, SimpleType::Unknown) => quote!(f.loc_id()), (_, SimpleType::Unit(_)) => quote!(*f), (_, SimpleType::Array(_)) | (_, SimpleType::BoxedSlice(_)) | (_, SimpleType::RefSlice(_)) | (_, SimpleType::Slice(_)) => { todo!("Unhandled type: {:?}", field.ty) } }; let params = match field.kind { FieldKind::Named(id) => { quote!( { #id: f,.. }) } FieldKind::None => match &variant.fields { syn::Fields::Named(_) => quote!({.. }), syn::Fields::Unnamed(_) => quote!((..)), syn::Fields::Unit => TokenStream::default(), }, FieldKind::Numbered(idx) => { let mut fields = Vec::new(); for (field_idx, _) in variant.fields.iter().enumerate() { if field_idx == idx { fields.push(quote!(f)); } else { fields.push(quote!(_)); } } quote!((#(#fields),*)) } }; variants.push(quote!(#enum_name::#variant_name #params => #reference)); } fn handle_has_loc_attr(attrs: &[Attribute]) -> Result<Option<Field<'_>>> { for attr in attrs { if attr.path.is_ident("has_loc") { let meta = attr.parse_meta()?; match meta { Meta::Path(path) => { return Err(Error::new(path.span(), "Arguments expected")); } Meta::List(list) => { // has_loc(A, B, C) if list.nested.len()!= 1 { return Err(Error::new(list.span(), "Only one argument expected")); } match &list.nested[0] { NestedMeta::Lit(Lit::Int(i)) => { return Ok(Some(Field { kind: FieldKind::Numbered(i.base10_parse()?), ty: SimpleType::Unknown, })); } NestedMeta::Lit(Lit::Str(n)) => { return Ok(Some(Field { kind: FieldKind::Named(Cow::Owned(Ident::new( &n.value(), Span::call_site(), ))), ty: SimpleType::Unknown, })); } NestedMeta::Meta(Meta::Path(meta)) if meta.is_ident("none") => { return Ok(Some(Field { kind: FieldKind::None, ty: SimpleType::Unknown, })); } i => { todo!("Unhandled: {:?}", i); } } } Meta::NameValue(_list) => { todo!(); } } } } Ok(None) }
{ // struct Foo { // ... // loc: LocId, // } let struct_name = &input.ident; let default_select_field = handle_has_loc_attr(&input.attrs)?; let loc_field = if let Some(f) = default_select_field { match f.kind { FieldKind::Named(name) => { let name = name.to_string(); let field = data .fields .iter() .find(|field| field.ident.as_ref().map_or(false, |id| id == &name)) .ok_or_else(|| Error::new(input.span(), format!("Field '{name}' not found")))? .ident .as_ref() .unwrap();
identifier_body
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::controller::Axis; use sdl2::ttf; use sdl2::ttf::Font; use sdl2::video::Window; use sdl2::video::WindowContext; use std::i16; use std::thread::sleep; use std::time::Duration; use crate::structs::Vector2; use crate::structs::Spaceship; use crate::structs::Projectile; use crate::structs::GameState; use crate::structs::State; mod structs; //mod subroutines; const DEADZONE: f32 = 0.20; const PLAYER_WIDTH: u32 = 50; const SCREEN_WIDTH: u32 = 1280; const SCREEN_HEIGHT: u32 = 720; fn open_controller(css: &GameControllerSubsystem, index: u32) -> Option<GameController> { match css.open(index) { Ok(cont) => { println!("Successfully opened controller {}", index); Some(cont) } Err(_e) => { println!("Unable to open controller {}", index); None } } } fn check_deadzone(mut stick: Vector2<f32>) -> Vector2<f32> { if stick.x > -DEADZONE && stick.x < DEADZONE && stick.y > -DEADZONE && stick.y < DEADZONE { stick.x = 0.0; stick.y = 0.0; } stick } fn text_texture<'a>(text: &str, texture_creator: &'a TextureCreator<WindowContext>, font: &Font) -> Texture<'a> { let color = Color::RGB(0, 255, 0); match font.render(text).solid(color) { Ok(surface) => { match texture_creator.create_texture_from_surface(surface) { Ok(t) => { t } Err(e) =>
} } Err(e) => { panic!("{}", e); } } } fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { let query = texture.query(); let xpos = (SCREEN_WIDTH / 2 - query.width / 2) as i32; let ypos = (SCREEN_HEIGHT / 2 - query.height / 2) as i32 + y_offset; Rect::new(xpos, ypos, query.width, query.height) }; canvas.copy(texture, None, dst).unwrap(); } fn delete_marked_entities<T>(optionvec: &mut Vec<Option<T>>, marks: Vec<usize>) { for i in marks { optionvec[i] = None; } } fn insert_into_option_vec<T>(optionvec: &mut Vec<Option<T>>, item: T) { let mut index = None; for (i, p) in optionvec.iter().enumerate() { if let None = p { index = Some(i); } } match index { Some(i) => { optionvec[i] = Some(item); } None => { optionvec.push(Some(item)); } } } fn clamp<T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{ let mut clamped_value = value; if clamped_value < lower_bound { clamped_value = lower_bound; } if clamped_value > upper_bound { clamped_value = upper_bound; } clamped_value } fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); //Create the actual window let window = video_subsystem.window("Galaxy Monkey", SCREEN_WIDTH, SCREEN_HEIGHT).position_centered().build().unwrap(); //Create primary drawing interface let mut canvas = window.into_canvas().build().unwrap(); //Create the texture creator let texture_creator = canvas.texture_creator(); //Create the event_pump let mut event_pump = sdl_context.event_pump().unwrap(); //Init the controller subsystem let controller_ss = sdl_context.game_controller().unwrap(); //Init the timer subsystem let mut timer_ss = sdl_context.timer().unwrap(); //Create array of controllers let mut _controllers: [Option<GameController>; 4] = [None, None, None, None]; //Init the ttf subsystem let ttf_context = obtain_result(ttf::init()); //Load the font let font = obtain_result(ttf_context.load_font("fonts/CursedTimerULiL.ttf", 64)); //Create title screen texture let game_title = text_texture("Galaxy Monkey", &texture_creator, &font); //Create press start text let press_start_text = text_texture("Press Start", &texture_creator, &font); let mut press_start_position: i32 = 150; //Round # texture variable let mut round_number_texture = text_texture("Round 0", &texture_creator, &font); //Timer variable for making "Press Start" flash let mut press_start_timer = 0; let mut displaying = true; //Timer variable for transitioning between rounds let mut round_transition_timer = 0; let mut going_to_next_round = false; //Initialize the game state let mut game_state = { let left_joystick = Vector2 { x: 0.0, y: 0.0 }; let right_joystick = Vector2 { x: 0.0, y: 0.0 }; let player = { let x = (SCREEN_WIDTH / 2 - PLAYER_WIDTH) as f32; let y = (SCREEN_HEIGHT / 2 - PLAYER_WIDTH) as f32; let position = Vector2 { x, y }; Spaceship { position } }; let friendly_projectiles = Vec::new(); let enemies = Vec::new(); let round_number = 0; GameState { player, state: State::StartMenu, left_joystick, right_joystick, friendly_projectiles, enemies, round_number } }; let mut old_ticks = 0; 'running: loop { //Get milliseconds since last frame let ticks = timer_ss.ticks(); let time_delta = ticks - old_ticks; match game_state.state { State::StartMenu => { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::ControllerButtonDown {button: Button::Start,..} | Event::KeyDown {..} => { game_state.state = State::Playing; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::MouseWheel {y,..} => { press_start_position -= y * 30; } _ => {} } } //Clear the screen canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the title draw_centered_text(&mut canvas, &game_title, -200); //Draw press start const INTERVAL: u32 = 500; if ticks - press_start_timer > INTERVAL { displaying =!displaying; press_start_timer = ticks; } if displaying { draw_centered_text(&mut canvas, &press_start_text, press_start_position); } } State::Playing => { //Process events for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::ControllerAxisMotion {axis: ax, value: v,..} => { match ax { Axis::LeftX => { game_state.left_joystick.x = v as f32 / i16::MAX as f32; } Axis::LeftY => { game_state.left_joystick.y = v as f32 / i16::MAX as f32; } Axis::RightX => { game_state.right_joystick.x = v as f32 / i16::MAX as f32; } Axis::RightY => { game_state.right_joystick.y = v as f32 / i16::MAX as f32; } _ => {} } game_state.left_joystick = check_deadzone(game_state.left_joystick); game_state.right_joystick = check_deadzone(game_state.right_joystick); } Event::KeyDown {keycode: Some(key),..} => { match key { _ => { println!("You pressed the unbound key: {}", key); } } } _ => {} } } //Check if enemies option-vec is empty let mut enemies_is_empty = true; for enemy in game_state.enemies.iter() { if let Some(_e) = enemy { enemies_is_empty = false; break; } } //This will probably become the trigger for advancing rounds if enemies_is_empty { if!going_to_next_round { //Start the timer round_transition_timer = ticks; //Increment round number game_state.round_number += 1; //Create round # texture round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font); going_to_next_round = true; } const INTERVAL: u32 = 2500; //Timer duration in millis if ticks - round_transition_timer > INTERVAL { let new_enemy = { let position = Vector2 { x: 0.0, y: 30.0 }; Spaceship { position } }; //Insert enemy into vec insert_into_option_vec(&mut game_state.enemies, new_enemy); going_to_next_round = false; } } //If the right stick is not neutral, fire a projectile if game_state.right_joystick.x!= 0.0 || game_state.right_joystick.y!= 0.0 { //Construct this new projectile let projectile = { let xpos = game_state.player.position.x + (PLAYER_WIDTH / 2) as f32; let ypos = game_state.player.position.y + (PLAYER_WIDTH / 2) as f32; let position = Vector2 { x: xpos, y: ypos }; const PROJECTILE_SPEED: f32 = 10.0; let angle = f32::atan(game_state.right_joystick.y / game_state.right_joystick.x); let xvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::cos(angle)) } else { PROJECTILE_SPEED * f32::cos(angle) } }; let yvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::sin(angle)) } else { PROJECTILE_SPEED * f32::sin(angle) } }; let velocity = Vector2 { x: xvel, y: yvel }; Projectile { position, velocity } }; //Insert new projectile into vec insert_into_option_vec(&mut game_state.friendly_projectiles, projectile); } //Update the player const PLAYER_SPEED: f32 = 3.0; game_state.player.position.x += game_state.left_joystick.x * PLAYER_SPEED; game_state.player.position.y += game_state.left_joystick.y * PLAYER_SPEED; game_state.player.position.x = clamp(game_state.player.position.x, 0.0, (SCREEN_WIDTH - PLAYER_WIDTH) as f32); game_state.player.position.y = clamp(game_state.player.position.y, 0.0, (SCREEN_HEIGHT - PLAYER_WIDTH) as f32); //Update all enemies let mut enemies_to_destroy = Vec::new(); for (i, enemy) in game_state.enemies.iter_mut().enumerate() { if let Some(e) = enemy { if e.position.x > SCREEN_WIDTH as f32 { enemies_to_destroy.push(i); } e.position.x += 1.0; } } //Set all offscreen enemies to None delete_marked_entities(&mut game_state.enemies, enemies_to_destroy); //Update all projectiles let mut projectiles_to_destroy = Vec::new(); for (i, projectile) in game_state.friendly_projectiles.iter_mut().enumerate() { if let Some(p) = projectile { if p.position.x < 0.0 || p.position.x > SCREEN_WIDTH as f32 || p.position.y < 0.0 || p.position.y > SCREEN_HEIGHT as f32 { projectiles_to_destroy.push(i); } p.position.x += p.velocity.x; p.position.y += p.velocity.y; } } //Set all offscreen projectiles to None delete_marked_entities(&mut game_state.friendly_projectiles, projectiles_to_destroy); //Clear the canvas canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the spaceship canvas.set_draw_color(Color::RGB(150, 150, 150)); canvas.fill_rect(Rect::new(game_state.player.position.x as i32, game_state.player.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); //Draw all enemies canvas.set_draw_color(Color::RGB(50, 120, 0)); for enemy in game_state.enemies.iter() { if let Some(e) = enemy { canvas.fill_rect(Rect::new(e.position.x as i32, e.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); } } //Draw all projectiles canvas.set_draw_color(Color::RGB(150, 150, 150)); for projectile in game_state.friendly_projectiles.iter() { if let Some(p) = projectile { let point = Point::new(p.position.x as i32, p.position.y as i32); canvas.draw_point(point).unwrap(); } } //Draw the round transition text if necessary if going_to_next_round { draw_centered_text(&mut canvas, &round_number_texture, 0); } } } canvas.present(); //Update old_ticks old_ticks = ticks; if time_delta < 8 { sleep(Duration::from_millis((8 - time_delta) as u64)); } } }
{ panic!("{}", e); }
conditional_block
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::controller::Axis; use sdl2::ttf; use sdl2::ttf::Font; use sdl2::video::Window; use sdl2::video::WindowContext; use std::i16; use std::thread::sleep; use std::time::Duration; use crate::structs::Vector2; use crate::structs::Spaceship; use crate::structs::Projectile; use crate::structs::GameState; use crate::structs::State; mod structs; //mod subroutines; const DEADZONE: f32 = 0.20; const PLAYER_WIDTH: u32 = 50; const SCREEN_WIDTH: u32 = 1280; const SCREEN_HEIGHT: u32 = 720; fn open_controller(css: &GameControllerSubsystem, index: u32) -> Option<GameController> { match css.open(index) { Ok(cont) => { println!("Successfully opened controller {}", index); Some(cont) } Err(_e) => { println!("Unable to open controller {}", index); None } } } fn check_deadzone(mut stick: Vector2<f32>) -> Vector2<f32> { if stick.x > -DEADZONE && stick.x < DEADZONE && stick.y > -DEADZONE && stick.y < DEADZONE { stick.x = 0.0; stick.y = 0.0; } stick } fn text_texture<'a>(text: &str, texture_creator: &'a TextureCreator<WindowContext>, font: &Font) -> Texture<'a>
fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { let query = texture.query(); let xpos = (SCREEN_WIDTH / 2 - query.width / 2) as i32; let ypos = (SCREEN_HEIGHT / 2 - query.height / 2) as i32 + y_offset; Rect::new(xpos, ypos, query.width, query.height) }; canvas.copy(texture, None, dst).unwrap(); } fn delete_marked_entities<T>(optionvec: &mut Vec<Option<T>>, marks: Vec<usize>) { for i in marks { optionvec[i] = None; } } fn insert_into_option_vec<T>(optionvec: &mut Vec<Option<T>>, item: T) { let mut index = None; for (i, p) in optionvec.iter().enumerate() { if let None = p { index = Some(i); } } match index { Some(i) => { optionvec[i] = Some(item); } None => { optionvec.push(Some(item)); } } } fn clamp<T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{ let mut clamped_value = value; if clamped_value < lower_bound { clamped_value = lower_bound; } if clamped_value > upper_bound { clamped_value = upper_bound; } clamped_value } fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); //Create the actual window let window = video_subsystem.window("Galaxy Monkey", SCREEN_WIDTH, SCREEN_HEIGHT).position_centered().build().unwrap(); //Create primary drawing interface let mut canvas = window.into_canvas().build().unwrap(); //Create the texture creator let texture_creator = canvas.texture_creator(); //Create the event_pump let mut event_pump = sdl_context.event_pump().unwrap(); //Init the controller subsystem let controller_ss = sdl_context.game_controller().unwrap(); //Init the timer subsystem let mut timer_ss = sdl_context.timer().unwrap(); //Create array of controllers let mut _controllers: [Option<GameController>; 4] = [None, None, None, None]; //Init the ttf subsystem let ttf_context = obtain_result(ttf::init()); //Load the font let font = obtain_result(ttf_context.load_font("fonts/CursedTimerULiL.ttf", 64)); //Create title screen texture let game_title = text_texture("Galaxy Monkey", &texture_creator, &font); //Create press start text let press_start_text = text_texture("Press Start", &texture_creator, &font); let mut press_start_position: i32 = 150; //Round # texture variable let mut round_number_texture = text_texture("Round 0", &texture_creator, &font); //Timer variable for making "Press Start" flash let mut press_start_timer = 0; let mut displaying = true; //Timer variable for transitioning between rounds let mut round_transition_timer = 0; let mut going_to_next_round = false; //Initialize the game state let mut game_state = { let left_joystick = Vector2 { x: 0.0, y: 0.0 }; let right_joystick = Vector2 { x: 0.0, y: 0.0 }; let player = { let x = (SCREEN_WIDTH / 2 - PLAYER_WIDTH) as f32; let y = (SCREEN_HEIGHT / 2 - PLAYER_WIDTH) as f32; let position = Vector2 { x, y }; Spaceship { position } }; let friendly_projectiles = Vec::new(); let enemies = Vec::new(); let round_number = 0; GameState { player, state: State::StartMenu, left_joystick, right_joystick, friendly_projectiles, enemies, round_number } }; let mut old_ticks = 0; 'running: loop { //Get milliseconds since last frame let ticks = timer_ss.ticks(); let time_delta = ticks - old_ticks; match game_state.state { State::StartMenu => { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::ControllerButtonDown {button: Button::Start,..} | Event::KeyDown {..} => { game_state.state = State::Playing; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::MouseWheel {y,..} => { press_start_position -= y * 30; } _ => {} } } //Clear the screen canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the title draw_centered_text(&mut canvas, &game_title, -200); //Draw press start const INTERVAL: u32 = 500; if ticks - press_start_timer > INTERVAL { displaying =!displaying; press_start_timer = ticks; } if displaying { draw_centered_text(&mut canvas, &press_start_text, press_start_position); } } State::Playing => { //Process events for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::ControllerAxisMotion {axis: ax, value: v,..} => { match ax { Axis::LeftX => { game_state.left_joystick.x = v as f32 / i16::MAX as f32; } Axis::LeftY => { game_state.left_joystick.y = v as f32 / i16::MAX as f32; } Axis::RightX => { game_state.right_joystick.x = v as f32 / i16::MAX as f32; } Axis::RightY => { game_state.right_joystick.y = v as f32 / i16::MAX as f32; } _ => {} } game_state.left_joystick = check_deadzone(game_state.left_joystick); game_state.right_joystick = check_deadzone(game_state.right_joystick); } Event::KeyDown {keycode: Some(key),..} => { match key { _ => { println!("You pressed the unbound key: {}", key); } } } _ => {} } } //Check if enemies option-vec is empty let mut enemies_is_empty = true; for enemy in game_state.enemies.iter() { if let Some(_e) = enemy { enemies_is_empty = false; break; } } //This will probably become the trigger for advancing rounds if enemies_is_empty { if!going_to_next_round { //Start the timer round_transition_timer = ticks; //Increment round number game_state.round_number += 1; //Create round # texture round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font); going_to_next_round = true; } const INTERVAL: u32 = 2500; //Timer duration in millis if ticks - round_transition_timer > INTERVAL { let new_enemy = { let position = Vector2 { x: 0.0, y: 30.0 }; Spaceship { position } }; //Insert enemy into vec insert_into_option_vec(&mut game_state.enemies, new_enemy); going_to_next_round = false; } } //If the right stick is not neutral, fire a projectile if game_state.right_joystick.x!= 0.0 || game_state.right_joystick.y!= 0.0 { //Construct this new projectile let projectile = { let xpos = game_state.player.position.x + (PLAYER_WIDTH / 2) as f32; let ypos = game_state.player.position.y + (PLAYER_WIDTH / 2) as f32; let position = Vector2 { x: xpos, y: ypos }; const PROJECTILE_SPEED: f32 = 10.0; let angle = f32::atan(game_state.right_joystick.y / game_state.right_joystick.x); let xvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::cos(angle)) } else { PROJECTILE_SPEED * f32::cos(angle) } }; let yvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::sin(angle)) } else { PROJECTILE_SPEED * f32::sin(angle) } }; let velocity = Vector2 { x: xvel, y: yvel }; Projectile { position, velocity } }; //Insert new projectile into vec insert_into_option_vec(&mut game_state.friendly_projectiles, projectile); } //Update the player const PLAYER_SPEED: f32 = 3.0; game_state.player.position.x += game_state.left_joystick.x * PLAYER_SPEED; game_state.player.position.y += game_state.left_joystick.y * PLAYER_SPEED; game_state.player.position.x = clamp(game_state.player.position.x, 0.0, (SCREEN_WIDTH - PLAYER_WIDTH) as f32); game_state.player.position.y = clamp(game_state.player.position.y, 0.0, (SCREEN_HEIGHT - PLAYER_WIDTH) as f32); //Update all enemies let mut enemies_to_destroy = Vec::new(); for (i, enemy) in game_state.enemies.iter_mut().enumerate() { if let Some(e) = enemy { if e.position.x > SCREEN_WIDTH as f32 { enemies_to_destroy.push(i); } e.position.x += 1.0; } } //Set all offscreen enemies to None delete_marked_entities(&mut game_state.enemies, enemies_to_destroy); //Update all projectiles let mut projectiles_to_destroy = Vec::new(); for (i, projectile) in game_state.friendly_projectiles.iter_mut().enumerate() { if let Some(p) = projectile { if p.position.x < 0.0 || p.position.x > SCREEN_WIDTH as f32 || p.position.y < 0.0 || p.position.y > SCREEN_HEIGHT as f32 { projectiles_to_destroy.push(i); } p.position.x += p.velocity.x; p.position.y += p.velocity.y; } } //Set all offscreen projectiles to None delete_marked_entities(&mut game_state.friendly_projectiles, projectiles_to_destroy); //Clear the canvas canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the spaceship canvas.set_draw_color(Color::RGB(150, 150, 150)); canvas.fill_rect(Rect::new(game_state.player.position.x as i32, game_state.player.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); //Draw all enemies canvas.set_draw_color(Color::RGB(50, 120, 0)); for enemy in game_state.enemies.iter() { if let Some(e) = enemy { canvas.fill_rect(Rect::new(e.position.x as i32, e.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); } } //Draw all projectiles canvas.set_draw_color(Color::RGB(150, 150, 150)); for projectile in game_state.friendly_projectiles.iter() { if let Some(p) = projectile { let point = Point::new(p.position.x as i32, p.position.y as i32); canvas.draw_point(point).unwrap(); } } //Draw the round transition text if necessary if going_to_next_round { draw_centered_text(&mut canvas, &round_number_texture, 0); } } } canvas.present(); //Update old_ticks old_ticks = ticks; if time_delta < 8 { sleep(Duration::from_millis((8 - time_delta) as u64)); } } }
{ let color = Color::RGB(0, 255, 0); match font.render(text).solid(color) { Ok(surface) => { match texture_creator.create_texture_from_surface(surface) { Ok(t) => { t } Err(e) => { panic!("{}", e); } } } Err(e) => { panic!("{}", e); } } }
identifier_body
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::controller::Axis; use sdl2::ttf; use sdl2::ttf::Font; use sdl2::video::Window; use sdl2::video::WindowContext; use std::i16; use std::thread::sleep; use std::time::Duration; use crate::structs::Vector2; use crate::structs::Spaceship; use crate::structs::Projectile; use crate::structs::GameState; use crate::structs::State; mod structs; //mod subroutines; const DEADZONE: f32 = 0.20; const PLAYER_WIDTH: u32 = 50; const SCREEN_WIDTH: u32 = 1280; const SCREEN_HEIGHT: u32 = 720; fn open_controller(css: &GameControllerSubsystem, index: u32) -> Option<GameController> { match css.open(index) { Ok(cont) => { println!("Successfully opened controller {}", index); Some(cont) } Err(_e) => { println!("Unable to open controller {}", index); None } } } fn check_deadzone(mut stick: Vector2<f32>) -> Vector2<f32> { if stick.x > -DEADZONE && stick.x < DEADZONE && stick.y > -DEADZONE && stick.y < DEADZONE { stick.x = 0.0; stick.y = 0.0; } stick } fn text_texture<'a>(text: &str, texture_creator: &'a TextureCreator<WindowContext>, font: &Font) -> Texture<'a> { let color = Color::RGB(0, 255, 0); match font.render(text).solid(color) { Ok(surface) => { match texture_creator.create_texture_from_surface(surface) { Ok(t) => { t } Err(e) => { panic!("{}", e); } } } Err(e) => { panic!("{}", e); } } } fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { let query = texture.query(); let xpos = (SCREEN_WIDTH / 2 - query.width / 2) as i32; let ypos = (SCREEN_HEIGHT / 2 - query.height / 2) as i32 + y_offset; Rect::new(xpos, ypos, query.width, query.height) }; canvas.copy(texture, None, dst).unwrap(); } fn delete_marked_entities<T>(optionvec: &mut Vec<Option<T>>, marks: Vec<usize>) { for i in marks { optionvec[i] = None; } } fn insert_into_option_vec<T>(optionvec: &mut Vec<Option<T>>, item: T) { let mut index = None; for (i, p) in optionvec.iter().enumerate() { if let None = p { index = Some(i); } } match index { Some(i) => { optionvec[i] = Some(item); } None => { optionvec.push(Some(item)); } } } fn clamp<T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{ let mut clamped_value = value; if clamped_value < lower_bound { clamped_value = lower_bound; } if clamped_value > upper_bound { clamped_value = upper_bound; } clamped_value } fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); //Create the actual window let window = video_subsystem.window("Galaxy Monkey", SCREEN_WIDTH, SCREEN_HEIGHT).position_centered().build().unwrap(); //Create primary drawing interface let mut canvas = window.into_canvas().build().unwrap(); //Create the texture creator let texture_creator = canvas.texture_creator(); //Create the event_pump let mut event_pump = sdl_context.event_pump().unwrap(); //Init the controller subsystem let controller_ss = sdl_context.game_controller().unwrap(); //Init the timer subsystem let mut timer_ss = sdl_context.timer().unwrap(); //Create array of controllers let mut _controllers: [Option<GameController>; 4] = [None, None, None, None]; //Init the ttf subsystem let ttf_context = obtain_result(ttf::init()); //Load the font let font = obtain_result(ttf_context.load_font("fonts/CursedTimerULiL.ttf", 64)); //Create title screen texture let game_title = text_texture("Galaxy Monkey", &texture_creator, &font); //Create press start text let press_start_text = text_texture("Press Start", &texture_creator, &font); let mut press_start_position: i32 = 150; //Round # texture variable let mut round_number_texture = text_texture("Round 0", &texture_creator, &font); //Timer variable for making "Press Start" flash let mut press_start_timer = 0; let mut displaying = true; //Timer variable for transitioning between rounds let mut round_transition_timer = 0; let mut going_to_next_round = false; //Initialize the game state let mut game_state = { let left_joystick = Vector2 { x: 0.0, y: 0.0 }; let right_joystick = Vector2 { x: 0.0, y: 0.0 }; let player = { let x = (SCREEN_WIDTH / 2 - PLAYER_WIDTH) as f32; let y = (SCREEN_HEIGHT / 2 - PLAYER_WIDTH) as f32; let position = Vector2 { x, y }; Spaceship { position } }; let friendly_projectiles = Vec::new(); let enemies = Vec::new(); let round_number = 0; GameState { player, state: State::StartMenu, left_joystick, right_joystick, friendly_projectiles, enemies, round_number } }; let mut old_ticks = 0; 'running: loop { //Get milliseconds since last frame let ticks = timer_ss.ticks(); let time_delta = ticks - old_ticks; match game_state.state { State::StartMenu => { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::ControllerButtonDown {button: Button::Start,..} | Event::KeyDown {..} => { game_state.state = State::Playing; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::MouseWheel {y,..} => { press_start_position -= y * 30; } _ => {} } } //Clear the screen canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the title draw_centered_text(&mut canvas, &game_title, -200); //Draw press start const INTERVAL: u32 = 500; if ticks - press_start_timer > INTERVAL { displaying =!displaying; press_start_timer = ticks; } if displaying { draw_centered_text(&mut canvas, &press_start_text, press_start_position); } } State::Playing => { //Process events for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::ControllerAxisMotion {axis: ax, value: v,..} => { match ax { Axis::LeftX => { game_state.left_joystick.x = v as f32 / i16::MAX as f32; } Axis::LeftY => { game_state.left_joystick.y = v as f32 / i16::MAX as f32; } Axis::RightX => { game_state.right_joystick.x = v as f32 / i16::MAX as f32; } Axis::RightY => { game_state.right_joystick.y = v as f32 / i16::MAX as f32; } _ => {} } game_state.left_joystick = check_deadzone(game_state.left_joystick); game_state.right_joystick = check_deadzone(game_state.right_joystick); } Event::KeyDown {keycode: Some(key),..} => { match key { _ => { println!("You pressed the unbound key: {}", key); } } } _ => {} } } //Check if enemies option-vec is empty let mut enemies_is_empty = true; for enemy in game_state.enemies.iter() { if let Some(_e) = enemy { enemies_is_empty = false; break; } } //This will probably become the trigger for advancing rounds if enemies_is_empty {
if!going_to_next_round { //Start the timer round_transition_timer = ticks; //Increment round number game_state.round_number += 1; //Create round # texture round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font); going_to_next_round = true; } const INTERVAL: u32 = 2500; //Timer duration in millis if ticks - round_transition_timer > INTERVAL { let new_enemy = { let position = Vector2 { x: 0.0, y: 30.0 }; Spaceship { position } }; //Insert enemy into vec insert_into_option_vec(&mut game_state.enemies, new_enemy); going_to_next_round = false; } } //If the right stick is not neutral, fire a projectile if game_state.right_joystick.x!= 0.0 || game_state.right_joystick.y!= 0.0 { //Construct this new projectile let projectile = { let xpos = game_state.player.position.x + (PLAYER_WIDTH / 2) as f32; let ypos = game_state.player.position.y + (PLAYER_WIDTH / 2) as f32; let position = Vector2 { x: xpos, y: ypos }; const PROJECTILE_SPEED: f32 = 10.0; let angle = f32::atan(game_state.right_joystick.y / game_state.right_joystick.x); let xvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::cos(angle)) } else { PROJECTILE_SPEED * f32::cos(angle) } }; let yvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::sin(angle)) } else { PROJECTILE_SPEED * f32::sin(angle) } }; let velocity = Vector2 { x: xvel, y: yvel }; Projectile { position, velocity } }; //Insert new projectile into vec insert_into_option_vec(&mut game_state.friendly_projectiles, projectile); } //Update the player const PLAYER_SPEED: f32 = 3.0; game_state.player.position.x += game_state.left_joystick.x * PLAYER_SPEED; game_state.player.position.y += game_state.left_joystick.y * PLAYER_SPEED; game_state.player.position.x = clamp(game_state.player.position.x, 0.0, (SCREEN_WIDTH - PLAYER_WIDTH) as f32); game_state.player.position.y = clamp(game_state.player.position.y, 0.0, (SCREEN_HEIGHT - PLAYER_WIDTH) as f32); //Update all enemies let mut enemies_to_destroy = Vec::new(); for (i, enemy) in game_state.enemies.iter_mut().enumerate() { if let Some(e) = enemy { if e.position.x > SCREEN_WIDTH as f32 { enemies_to_destroy.push(i); } e.position.x += 1.0; } } //Set all offscreen enemies to None delete_marked_entities(&mut game_state.enemies, enemies_to_destroy); //Update all projectiles let mut projectiles_to_destroy = Vec::new(); for (i, projectile) in game_state.friendly_projectiles.iter_mut().enumerate() { if let Some(p) = projectile { if p.position.x < 0.0 || p.position.x > SCREEN_WIDTH as f32 || p.position.y < 0.0 || p.position.y > SCREEN_HEIGHT as f32 { projectiles_to_destroy.push(i); } p.position.x += p.velocity.x; p.position.y += p.velocity.y; } } //Set all offscreen projectiles to None delete_marked_entities(&mut game_state.friendly_projectiles, projectiles_to_destroy); //Clear the canvas canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the spaceship canvas.set_draw_color(Color::RGB(150, 150, 150)); canvas.fill_rect(Rect::new(game_state.player.position.x as i32, game_state.player.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); //Draw all enemies canvas.set_draw_color(Color::RGB(50, 120, 0)); for enemy in game_state.enemies.iter() { if let Some(e) = enemy { canvas.fill_rect(Rect::new(e.position.x as i32, e.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); } } //Draw all projectiles canvas.set_draw_color(Color::RGB(150, 150, 150)); for projectile in game_state.friendly_projectiles.iter() { if let Some(p) = projectile { let point = Point::new(p.position.x as i32, p.position.y as i32); canvas.draw_point(point).unwrap(); } } //Draw the round transition text if necessary if going_to_next_round { draw_centered_text(&mut canvas, &round_number_texture, 0); } } } canvas.present(); //Update old_ticks old_ticks = ticks; if time_delta < 8 { sleep(Duration::from_millis((8 - time_delta) as u64)); } } }
random_line_split
main.rs
extern crate sdl2; use sdl2::pixels::Color; use sdl2::event::Event; use sdl2::GameControllerSubsystem; use sdl2::controller::GameController; use sdl2::controller::Button; use sdl2::render::Canvas; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::rect::Point; use sdl2::rect::Rect; use sdl2::controller::Axis; use sdl2::ttf; use sdl2::ttf::Font; use sdl2::video::Window; use sdl2::video::WindowContext; use std::i16; use std::thread::sleep; use std::time::Duration; use crate::structs::Vector2; use crate::structs::Spaceship; use crate::structs::Projectile; use crate::structs::GameState; use crate::structs::State; mod structs; //mod subroutines; const DEADZONE: f32 = 0.20; const PLAYER_WIDTH: u32 = 50; const SCREEN_WIDTH: u32 = 1280; const SCREEN_HEIGHT: u32 = 720; fn open_controller(css: &GameControllerSubsystem, index: u32) -> Option<GameController> { match css.open(index) { Ok(cont) => { println!("Successfully opened controller {}", index); Some(cont) } Err(_e) => { println!("Unable to open controller {}", index); None } } } fn check_deadzone(mut stick: Vector2<f32>) -> Vector2<f32> { if stick.x > -DEADZONE && stick.x < DEADZONE && stick.y > -DEADZONE && stick.y < DEADZONE { stick.x = 0.0; stick.y = 0.0; } stick } fn text_texture<'a>(text: &str, texture_creator: &'a TextureCreator<WindowContext>, font: &Font) -> Texture<'a> { let color = Color::RGB(0, 255, 0); match font.render(text).solid(color) { Ok(surface) => { match texture_creator.create_texture_from_surface(surface) { Ok(t) => { t } Err(e) => { panic!("{}", e); } } } Err(e) => { panic!("{}", e); } } } fn obtain_result<T, E: std::fmt::Display>(res: Result<T, E>) -> T { match res { Ok(r) => { r } Err(e) => { panic!("{}", e); } } } fn draw_centered_text(canvas: &mut Canvas<Window>, texture: &Texture, y_offset: i32) { //Draw the title let dst = { let query = texture.query(); let xpos = (SCREEN_WIDTH / 2 - query.width / 2) as i32; let ypos = (SCREEN_HEIGHT / 2 - query.height / 2) as i32 + y_offset; Rect::new(xpos, ypos, query.width, query.height) }; canvas.copy(texture, None, dst).unwrap(); } fn delete_marked_entities<T>(optionvec: &mut Vec<Option<T>>, marks: Vec<usize>) { for i in marks { optionvec[i] = None; } } fn insert_into_option_vec<T>(optionvec: &mut Vec<Option<T>>, item: T) { let mut index = None; for (i, p) in optionvec.iter().enumerate() { if let None = p { index = Some(i); } } match index { Some(i) => { optionvec[i] = Some(item); } None => { optionvec.push(Some(item)); } } } fn
<T: std::cmp::PartialOrd>(value: T, lower_bound: T, upper_bound: T) -> T{ let mut clamped_value = value; if clamped_value < lower_bound { clamped_value = lower_bound; } if clamped_value > upper_bound { clamped_value = upper_bound; } clamped_value } fn main() { let sdl_context = sdl2::init().unwrap(); let video_subsystem = sdl_context.video().unwrap(); //Create the actual window let window = video_subsystem.window("Galaxy Monkey", SCREEN_WIDTH, SCREEN_HEIGHT).position_centered().build().unwrap(); //Create primary drawing interface let mut canvas = window.into_canvas().build().unwrap(); //Create the texture creator let texture_creator = canvas.texture_creator(); //Create the event_pump let mut event_pump = sdl_context.event_pump().unwrap(); //Init the controller subsystem let controller_ss = sdl_context.game_controller().unwrap(); //Init the timer subsystem let mut timer_ss = sdl_context.timer().unwrap(); //Create array of controllers let mut _controllers: [Option<GameController>; 4] = [None, None, None, None]; //Init the ttf subsystem let ttf_context = obtain_result(ttf::init()); //Load the font let font = obtain_result(ttf_context.load_font("fonts/CursedTimerULiL.ttf", 64)); //Create title screen texture let game_title = text_texture("Galaxy Monkey", &texture_creator, &font); //Create press start text let press_start_text = text_texture("Press Start", &texture_creator, &font); let mut press_start_position: i32 = 150; //Round # texture variable let mut round_number_texture = text_texture("Round 0", &texture_creator, &font); //Timer variable for making "Press Start" flash let mut press_start_timer = 0; let mut displaying = true; //Timer variable for transitioning between rounds let mut round_transition_timer = 0; let mut going_to_next_round = false; //Initialize the game state let mut game_state = { let left_joystick = Vector2 { x: 0.0, y: 0.0 }; let right_joystick = Vector2 { x: 0.0, y: 0.0 }; let player = { let x = (SCREEN_WIDTH / 2 - PLAYER_WIDTH) as f32; let y = (SCREEN_HEIGHT / 2 - PLAYER_WIDTH) as f32; let position = Vector2 { x, y }; Spaceship { position } }; let friendly_projectiles = Vec::new(); let enemies = Vec::new(); let round_number = 0; GameState { player, state: State::StartMenu, left_joystick, right_joystick, friendly_projectiles, enemies, round_number } }; let mut old_ticks = 0; 'running: loop { //Get milliseconds since last frame let ticks = timer_ss.ticks(); let time_delta = ticks - old_ticks; match game_state.state { State::StartMenu => { for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::ControllerButtonDown {button: Button::Start,..} | Event::KeyDown {..} => { game_state.state = State::Playing; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::MouseWheel {y,..} => { press_start_position -= y * 30; } _ => {} } } //Clear the screen canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the title draw_centered_text(&mut canvas, &game_title, -200); //Draw press start const INTERVAL: u32 = 500; if ticks - press_start_timer > INTERVAL { displaying =!displaying; press_start_timer = ticks; } if displaying { draw_centered_text(&mut canvas, &press_start_text, press_start_position); } } State::Playing => { //Process events for event in event_pump.poll_iter() { match event { Event::Quit {..} | Event::ControllerButtonDown {button: Button::Back,..} => { break 'running; } Event::JoyDeviceAdded {which: i,..} => { _controllers[i as usize] = open_controller(&controller_ss, i); } Event::ControllerAxisMotion {axis: ax, value: v,..} => { match ax { Axis::LeftX => { game_state.left_joystick.x = v as f32 / i16::MAX as f32; } Axis::LeftY => { game_state.left_joystick.y = v as f32 / i16::MAX as f32; } Axis::RightX => { game_state.right_joystick.x = v as f32 / i16::MAX as f32; } Axis::RightY => { game_state.right_joystick.y = v as f32 / i16::MAX as f32; } _ => {} } game_state.left_joystick = check_deadzone(game_state.left_joystick); game_state.right_joystick = check_deadzone(game_state.right_joystick); } Event::KeyDown {keycode: Some(key),..} => { match key { _ => { println!("You pressed the unbound key: {}", key); } } } _ => {} } } //Check if enemies option-vec is empty let mut enemies_is_empty = true; for enemy in game_state.enemies.iter() { if let Some(_e) = enemy { enemies_is_empty = false; break; } } //This will probably become the trigger for advancing rounds if enemies_is_empty { if!going_to_next_round { //Start the timer round_transition_timer = ticks; //Increment round number game_state.round_number += 1; //Create round # texture round_number_texture = text_texture(&format!("Round {}", game_state.round_number), &texture_creator, &font); going_to_next_round = true; } const INTERVAL: u32 = 2500; //Timer duration in millis if ticks - round_transition_timer > INTERVAL { let new_enemy = { let position = Vector2 { x: 0.0, y: 30.0 }; Spaceship { position } }; //Insert enemy into vec insert_into_option_vec(&mut game_state.enemies, new_enemy); going_to_next_round = false; } } //If the right stick is not neutral, fire a projectile if game_state.right_joystick.x!= 0.0 || game_state.right_joystick.y!= 0.0 { //Construct this new projectile let projectile = { let xpos = game_state.player.position.x + (PLAYER_WIDTH / 2) as f32; let ypos = game_state.player.position.y + (PLAYER_WIDTH / 2) as f32; let position = Vector2 { x: xpos, y: ypos }; const PROJECTILE_SPEED: f32 = 10.0; let angle = f32::atan(game_state.right_joystick.y / game_state.right_joystick.x); let xvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::cos(angle)) } else { PROJECTILE_SPEED * f32::cos(angle) } }; let yvel = { if game_state.right_joystick.x < 0.0 { -(PROJECTILE_SPEED * f32::sin(angle)) } else { PROJECTILE_SPEED * f32::sin(angle) } }; let velocity = Vector2 { x: xvel, y: yvel }; Projectile { position, velocity } }; //Insert new projectile into vec insert_into_option_vec(&mut game_state.friendly_projectiles, projectile); } //Update the player const PLAYER_SPEED: f32 = 3.0; game_state.player.position.x += game_state.left_joystick.x * PLAYER_SPEED; game_state.player.position.y += game_state.left_joystick.y * PLAYER_SPEED; game_state.player.position.x = clamp(game_state.player.position.x, 0.0, (SCREEN_WIDTH - PLAYER_WIDTH) as f32); game_state.player.position.y = clamp(game_state.player.position.y, 0.0, (SCREEN_HEIGHT - PLAYER_WIDTH) as f32); //Update all enemies let mut enemies_to_destroy = Vec::new(); for (i, enemy) in game_state.enemies.iter_mut().enumerate() { if let Some(e) = enemy { if e.position.x > SCREEN_WIDTH as f32 { enemies_to_destroy.push(i); } e.position.x += 1.0; } } //Set all offscreen enemies to None delete_marked_entities(&mut game_state.enemies, enemies_to_destroy); //Update all projectiles let mut projectiles_to_destroy = Vec::new(); for (i, projectile) in game_state.friendly_projectiles.iter_mut().enumerate() { if let Some(p) = projectile { if p.position.x < 0.0 || p.position.x > SCREEN_WIDTH as f32 || p.position.y < 0.0 || p.position.y > SCREEN_HEIGHT as f32 { projectiles_to_destroy.push(i); } p.position.x += p.velocity.x; p.position.y += p.velocity.y; } } //Set all offscreen projectiles to None delete_marked_entities(&mut game_state.friendly_projectiles, projectiles_to_destroy); //Clear the canvas canvas.set_draw_color(Color::RGB(0, 0, 0)); canvas.clear(); //Draw the spaceship canvas.set_draw_color(Color::RGB(150, 150, 150)); canvas.fill_rect(Rect::new(game_state.player.position.x as i32, game_state.player.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); //Draw all enemies canvas.set_draw_color(Color::RGB(50, 120, 0)); for enemy in game_state.enemies.iter() { if let Some(e) = enemy { canvas.fill_rect(Rect::new(e.position.x as i32, e.position.y as i32, PLAYER_WIDTH, PLAYER_WIDTH)).unwrap(); } } //Draw all projectiles canvas.set_draw_color(Color::RGB(150, 150, 150)); for projectile in game_state.friendly_projectiles.iter() { if let Some(p) = projectile { let point = Point::new(p.position.x as i32, p.position.y as i32); canvas.draw_point(point).unwrap(); } } //Draw the round transition text if necessary if going_to_next_round { draw_centered_text(&mut canvas, &round_number_texture, 0); } } } canvas.present(); //Update old_ticks old_ticks = ticks; if time_delta < 8 { sleep(Duration::from_millis((8 - time_delta) as u64)); } } }
clamp
identifier_name
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle; use crate::lib::loader::*; use crate::lib::types::*; use crate::lib::helpers::{input_insert_vec, limit, print_trace}; use differential_dataflow::operators::arrange::ArrangeBySelf; use timely::dataflow::operators::{Probe, Map, Delay}; use std::time::Instant; use std::cmp::{min, max}; pub fn
(path: String, change_path: String, params: &Vec<String>) { // unpack parameters let param_city1 = params[0].parse::<u64>().unwrap(); let param_city2 = params[1].parse::<u64>().unwrap(); timely::execute_from_args(std::env::args(), move |worker| { let mut timer = worker.timer(); let index = worker.index(); let peers = worker.peers(); let mut probe = ProbeHandle::new(); // create dataflow let ( mut trace, mut located_in_input, mut knows_input, mut has_creator_input, mut reply_of_input, ) = worker.dataflow::<usize,_,_>(|scope| { let (located_in_input, locatedin) = scope.new_collection::<DynamicConnection, _>(); let (knows_input, knows) = scope.new_collection::<DynamicConnection, _>(); // creators for comments AND posts let (has_creator_input, has_creator) = scope.new_collection::<DynamicConnection, _>(); // replyOf for comments AND posts let (reply_of_input, reply_of) = scope.new_collection::<DynamicConnection, _>(); // people of city1 let people1 = locatedin .filter(move |conn| param_city1.eq(conn.b())) .map(|conn| conn.a().clone()) ; // people of city2 let people2 = locatedin .filter(move |conn| param_city2.eq(conn.b())) .map(|conn| conn.a().clone()) ; // bidirectional knows relation let bi_knows = knows .map(|conn| (conn.b().clone(), conn.a().clone())) .concat( &knows.map(|conn| (conn.a().clone(), conn.b().clone())) ) ; // calculate weights starting from personB let weights = bi_knows .join_map( // join messages of personB &has_creator.map(|conn| (conn.b().clone(), conn.a().clone())), |pb, pa, m| (m.clone(), (pb.clone(), pa.clone())), ) .join_map( // join a reply of the message &reply_of.map(|conn| (conn.b().clone(), conn.a().clone())), |_mp, (pb, pa), mc| (mc.clone(), (pb.clone(), pa.clone())) ) .join_map( // join creator of last message (personA) &has_creator.map(|conn| (conn.a().clone(), conn.b().clone())), |_m, (pb, pa), pm| (pb.clone(), pa.clone(), pm.clone()) ) .filter( // check if the last message's creator is the other person we started with |(_pb, pa, pm)| pa.eq(pm) ) // drop duplicated message creator, and make sure the lower id is the first in the tuple // this is needed for the aggregation .map( |(pb, pa, _)| (min(pa, pb), max(pa, pb)) ) // aggregate (p1, p2) pairs, // which will result in the number of interactions between these people .count() // map result for next steps .map( // fixme: hack solution as floats cannot be used directly (not implementing Ord) |((p1, p2), c)| (p1, (p2, (((1.0/c as f32)*10000000000.0) as isize))) ) ; // -> (src, (dst, weight)) // create bidirectional weights let weights = weights .concat(&weights.map(|(p1, (p2, c))| (p2, (p1, c)))) ; // root nodes are people from city one. // ((p, p) 0) represents an initial path from p to p with 0 weight. let nodes = people1 .map(|p| ((p, p), 0)) ; // calculate shortest paths from people in city 1 // based on https://github.com/frankmcsherry/blog/blob/master/posts/2019-05-20.md let shortest_paths = nodes .iterate(|dists| { // calculate shortest path to every other node let edges = weights.enter(&dists.scope()); let nodes = nodes.enter(&dists.scope()); dists // -> ((src, dst), distance) .map(|((root, dst), dist)| (dst.clone(), (root.clone(), dist.clone()))) // join next step and calculate weights .join_map( &edges, |_src, (root, distance), (dst, weight)| ((root.clone(), dst.clone()), distance + weight) ) // -> ((root, dst), distance), // add original nodes .concat(&nodes) // -> ((root, dst), distance) // Timely magic, to speed up updates with some time manipulation (see blogpost above) .inner .map_in_place(|((_d, w), t, _r)| t.inner = std::cmp::max(t.inner, *w as u64) ) .delay(|(_, t, _), _| t.clone()) .as_collection() // finally keep only the shortest path between two nodes (grouped by (src, dst)) .reduce(|_key, input, output| output.push((*input[0].0, 1))) }) // -> ((src, dst), distance) // map for semijoin .map(|((src, dst), distance)| (dst, (src, distance))) // filter out result which are not between people from city1 and city2 .semijoin(&people2) ; // add sorting options and final results let result = shortest_paths .map(|(dst, (src, distance))| ( (std::isize::MAX - distance, src, dst), // sort: -distance, +src, +dst vec![src.to_string(), dst.to_string(), (distance as f64/10000000000.0).to_string()] )) ; let arrangement = limit(&result, 20) .arrange_by_self(); arrangement.stream.probe_with(&mut probe); return ( arrangement.trace, located_in_input, knows_input, has_creator_input, reply_of_input ); }); // add inputs let mut next_time: usize = 1; input_insert_vec( load_dynamic_connection("dynamic/person_isLocatedIn_place_0_0.csv", path.as_str(), index, peers), &mut located_in_input, next_time ); input_insert_vec( load_dynamic_connection("dynamic/person_knows_person_0_0.csv", path.as_str(), index, peers), &mut knows_input, next_time ); // insert hasCreator relations input_insert_vec( load_dynamic_connection("dynamic/post_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, next_time ); // insert replyOf relations input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_post_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_comment_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, next_time ); eprintln!("LOADED;{:}", timer.elapsed().as_secs_f64()); timer = Instant::now(); // Compute... while probe.less_than(knows_input.time()) { worker.step(); } eprintln!("CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print results print_trace(&mut trace, next_time); if change_path.eq(&"-".to_string()) { eprintln!("No change set was given."); return; } println!(" ---------------------------------------------------------------------- "); // introduce change set next_time += 1; timer = Instant::now(); // parse change set file for mut change_row in load_data(change_path.as_str(), index, peers) { let create = match change_row.remove(0).as_str() { "create" => true, "remove" => false, x => { panic!("Unknown change. It should be'remove' or 'create': {}", x); } }; let input = change_row.remove(0); let mut row_iter = change_row.into_iter(); let created = parse_datetime(row_iter.next().unwrap()); let id1 = row_iter.next().unwrap().parse::<Id>().unwrap(); let id2 = row_iter.next().unwrap().parse::<Id>().unwrap(); let d = DynamicConnection::new(created, id1, id2); match input.as_str() { "person-knows-person" => { if create { knows_input.insert(d); } else { knows_input.remove(d); } }, "person-islocatedin-place" => { if create { located_in_input.insert(d); } else { located_in_input.remove(d); } } x => { panic!("Unknown change type: {}", x); } } } // advance and flush all inputs... has_creator_input.advance_to(next_time); has_creator_input.flush(); reply_of_input.advance_to(next_time); reply_of_input.flush(); knows_input.advance_to(next_time); knows_input.flush(); located_in_input.advance_to(next_time); located_in_input.flush(); // Compute change set... while probe.less_than(&next_time) { worker.step(); } eprintln!("CHANGE_CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print changed results print_trace(&mut trace, next_time); }).expect("Timely computation failed"); }
run
identifier_name
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle; use crate::lib::loader::*; use crate::lib::types::*; use crate::lib::helpers::{input_insert_vec, limit, print_trace}; use differential_dataflow::operators::arrange::ArrangeBySelf; use timely::dataflow::operators::{Probe, Map, Delay}; use std::time::Instant; use std::cmp::{min, max}; pub fn run(path: String, change_path: String, params: &Vec<String>)
worker.dataflow::<usize,_,_>(|scope| { let (located_in_input, locatedin) = scope.new_collection::<DynamicConnection, _>(); let (knows_input, knows) = scope.new_collection::<DynamicConnection, _>(); // creators for comments AND posts let (has_creator_input, has_creator) = scope.new_collection::<DynamicConnection, _>(); // replyOf for comments AND posts let (reply_of_input, reply_of) = scope.new_collection::<DynamicConnection, _>(); // people of city1 let people1 = locatedin .filter(move |conn| param_city1.eq(conn.b())) .map(|conn| conn.a().clone()) ; // people of city2 let people2 = locatedin .filter(move |conn| param_city2.eq(conn.b())) .map(|conn| conn.a().clone()) ; // bidirectional knows relation let bi_knows = knows .map(|conn| (conn.b().clone(), conn.a().clone())) .concat( &knows.map(|conn| (conn.a().clone(), conn.b().clone())) ) ; // calculate weights starting from personB let weights = bi_knows .join_map( // join messages of personB &has_creator.map(|conn| (conn.b().clone(), conn.a().clone())), |pb, pa, m| (m.clone(), (pb.clone(), pa.clone())), ) .join_map( // join a reply of the message &reply_of.map(|conn| (conn.b().clone(), conn.a().clone())), |_mp, (pb, pa), mc| (mc.clone(), (pb.clone(), pa.clone())) ) .join_map( // join creator of last message (personA) &has_creator.map(|conn| (conn.a().clone(), conn.b().clone())), |_m, (pb, pa), pm| (pb.clone(), pa.clone(), pm.clone()) ) .filter( // check if the last message's creator is the other person we started with |(_pb, pa, pm)| pa.eq(pm) ) // drop duplicated message creator, and make sure the lower id is the first in the tuple // this is needed for the aggregation .map( |(pb, pa, _)| (min(pa, pb), max(pa, pb)) ) // aggregate (p1, p2) pairs, // which will result in the number of interactions between these people .count() // map result for next steps .map( // fixme: hack solution as floats cannot be used directly (not implementing Ord) |((p1, p2), c)| (p1, (p2, (((1.0/c as f32)*10000000000.0) as isize))) ) ; // -> (src, (dst, weight)) // create bidirectional weights let weights = weights .concat(&weights.map(|(p1, (p2, c))| (p2, (p1, c)))) ; // root nodes are people from city one. // ((p, p) 0) represents an initial path from p to p with 0 weight. let nodes = people1 .map(|p| ((p, p), 0)) ; // calculate shortest paths from people in city 1 // based on https://github.com/frankmcsherry/blog/blob/master/posts/2019-05-20.md let shortest_paths = nodes .iterate(|dists| { // calculate shortest path to every other node let edges = weights.enter(&dists.scope()); let nodes = nodes.enter(&dists.scope()); dists // -> ((src, dst), distance) .map(|((root, dst), dist)| (dst.clone(), (root.clone(), dist.clone()))) // join next step and calculate weights .join_map( &edges, |_src, (root, distance), (dst, weight)| ((root.clone(), dst.clone()), distance + weight) ) // -> ((root, dst), distance), // add original nodes .concat(&nodes) // -> ((root, dst), distance) // Timely magic, to speed up updates with some time manipulation (see blogpost above) .inner .map_in_place(|((_d, w), t, _r)| t.inner = std::cmp::max(t.inner, *w as u64) ) .delay(|(_, t, _), _| t.clone()) .as_collection() // finally keep only the shortest path between two nodes (grouped by (src, dst)) .reduce(|_key, input, output| output.push((*input[0].0, 1))) }) // -> ((src, dst), distance) // map for semijoin .map(|((src, dst), distance)| (dst, (src, distance))) // filter out result which are not between people from city1 and city2 .semijoin(&people2) ; // add sorting options and final results let result = shortest_paths .map(|(dst, (src, distance))| ( (std::isize::MAX - distance, src, dst), // sort: -distance, +src, +dst vec![src.to_string(), dst.to_string(), (distance as f64/10000000000.0).to_string()] )) ; let arrangement = limit(&result, 20) .arrange_by_self(); arrangement.stream.probe_with(&mut probe); return ( arrangement.trace, located_in_input, knows_input, has_creator_input, reply_of_input ); }); // add inputs let mut next_time: usize = 1; input_insert_vec( load_dynamic_connection("dynamic/person_isLocatedIn_place_0_0.csv", path.as_str(), index, peers), &mut located_in_input, next_time ); input_insert_vec( load_dynamic_connection("dynamic/person_knows_person_0_0.csv", path.as_str(), index, peers), &mut knows_input, next_time ); // insert hasCreator relations input_insert_vec( load_dynamic_connection("dynamic/post_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, next_time ); // insert replyOf relations input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_post_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_comment_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, next_time ); eprintln!("LOADED;{:}", timer.elapsed().as_secs_f64()); timer = Instant::now(); // Compute... while probe.less_than(knows_input.time()) { worker.step(); } eprintln!("CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print results print_trace(&mut trace, next_time); if change_path.eq(&"-".to_string()) { eprintln!("No change set was given."); return; } println!(" ---------------------------------------------------------------------- "); // introduce change set next_time += 1; timer = Instant::now(); // parse change set file for mut change_row in load_data(change_path.as_str(), index, peers) { let create = match change_row.remove(0).as_str() { "create" => true, "remove" => false, x => { panic!("Unknown change. It should be'remove' or 'create': {}", x); } }; let input = change_row.remove(0); let mut row_iter = change_row.into_iter(); let created = parse_datetime(row_iter.next().unwrap()); let id1 = row_iter.next().unwrap().parse::<Id>().unwrap(); let id2 = row_iter.next().unwrap().parse::<Id>().unwrap(); let d = DynamicConnection::new(created, id1, id2); match input.as_str() { "person-knows-person" => { if create { knows_input.insert(d); } else { knows_input.remove(d); } }, "person-islocatedin-place" => { if create { located_in_input.insert(d); } else { located_in_input.remove(d); } } x => { panic!("Unknown change type: {}", x); } } } // advance and flush all inputs... has_creator_input.advance_to(next_time); has_creator_input.flush(); reply_of_input.advance_to(next_time); reply_of_input.flush(); knows_input.advance_to(next_time); knows_input.flush(); located_in_input.advance_to(next_time); located_in_input.flush(); // Compute change set... while probe.less_than(&next_time) { worker.step(); } eprintln!("CHANGE_CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print changed results print_trace(&mut trace, next_time); }).expect("Timely computation failed"); }
{ // unpack parameters let param_city1 = params[0].parse::<u64>().unwrap(); let param_city2 = params[1].parse::<u64>().unwrap(); timely::execute_from_args(std::env::args(), move |worker| { let mut timer = worker.timer(); let index = worker.index(); let peers = worker.peers(); let mut probe = ProbeHandle::new(); // create dataflow let ( mut trace, mut located_in_input, mut knows_input, mut has_creator_input, mut reply_of_input, ) =
identifier_body
q19.rs
/* LDBC SNB BI query 19. Interaction path between cities https://ldbc.github.io/ldbc_snb_docs_snapshot/bi-read-19.pdf */ use differential_dataflow::collection::AsCollection; use differential_dataflow::input::Input; use differential_dataflow::operators::{Join, Count, Iterate, Reduce}; use timely::dataflow::ProbeHandle; use crate::lib::loader::*; use crate::lib::types::*; use crate::lib::helpers::{input_insert_vec, limit, print_trace}; use differential_dataflow::operators::arrange::ArrangeBySelf; use timely::dataflow::operators::{Probe, Map, Delay}; use std::time::Instant; use std::cmp::{min, max}; pub fn run(path: String, change_path: String, params: &Vec<String>) { // unpack parameters let param_city1 = params[0].parse::<u64>().unwrap(); let param_city2 = params[1].parse::<u64>().unwrap(); timely::execute_from_args(std::env::args(), move |worker| { let mut timer = worker.timer(); let index = worker.index(); let peers = worker.peers(); let mut probe = ProbeHandle::new(); // create dataflow let ( mut trace, mut located_in_input, mut knows_input, mut has_creator_input, mut reply_of_input, ) = worker.dataflow::<usize,_,_>(|scope| { let (located_in_input, locatedin) = scope.new_collection::<DynamicConnection, _>(); let (knows_input, knows) = scope.new_collection::<DynamicConnection, _>(); // creators for comments AND posts let (has_creator_input, has_creator) = scope.new_collection::<DynamicConnection, _>(); // replyOf for comments AND posts let (reply_of_input, reply_of) = scope.new_collection::<DynamicConnection, _>(); // people of city1 let people1 = locatedin .filter(move |conn| param_city1.eq(conn.b())) .map(|conn| conn.a().clone()) ; // people of city2 let people2 = locatedin .filter(move |conn| param_city2.eq(conn.b())) .map(|conn| conn.a().clone()) ; // bidirectional knows relation let bi_knows = knows .map(|conn| (conn.b().clone(), conn.a().clone())) .concat(
&knows.map(|conn| (conn.a().clone(), conn.b().clone())) ) ; // calculate weights starting from personB let weights = bi_knows .join_map( // join messages of personB &has_creator.map(|conn| (conn.b().clone(), conn.a().clone())), |pb, pa, m| (m.clone(), (pb.clone(), pa.clone())), ) .join_map( // join a reply of the message &reply_of.map(|conn| (conn.b().clone(), conn.a().clone())), |_mp, (pb, pa), mc| (mc.clone(), (pb.clone(), pa.clone())) ) .join_map( // join creator of last message (personA) &has_creator.map(|conn| (conn.a().clone(), conn.b().clone())), |_m, (pb, pa), pm| (pb.clone(), pa.clone(), pm.clone()) ) .filter( // check if the last message's creator is the other person we started with |(_pb, pa, pm)| pa.eq(pm) ) // drop duplicated message creator, and make sure the lower id is the first in the tuple // this is needed for the aggregation .map( |(pb, pa, _)| (min(pa, pb), max(pa, pb)) ) // aggregate (p1, p2) pairs, // which will result in the number of interactions between these people .count() // map result for next steps .map( // fixme: hack solution as floats cannot be used directly (not implementing Ord) |((p1, p2), c)| (p1, (p2, (((1.0/c as f32)*10000000000.0) as isize))) ) ; // -> (src, (dst, weight)) // create bidirectional weights let weights = weights .concat(&weights.map(|(p1, (p2, c))| (p2, (p1, c)))) ; // root nodes are people from city one. // ((p, p) 0) represents an initial path from p to p with 0 weight. let nodes = people1 .map(|p| ((p, p), 0)) ; // calculate shortest paths from people in city 1 // based on https://github.com/frankmcsherry/blog/blob/master/posts/2019-05-20.md let shortest_paths = nodes .iterate(|dists| { // calculate shortest path to every other node let edges = weights.enter(&dists.scope()); let nodes = nodes.enter(&dists.scope()); dists // -> ((src, dst), distance) .map(|((root, dst), dist)| (dst.clone(), (root.clone(), dist.clone()))) // join next step and calculate weights .join_map( &edges, |_src, (root, distance), (dst, weight)| ((root.clone(), dst.clone()), distance + weight) ) // -> ((root, dst), distance), // add original nodes .concat(&nodes) // -> ((root, dst), distance) // Timely magic, to speed up updates with some time manipulation (see blogpost above) .inner .map_in_place(|((_d, w), t, _r)| t.inner = std::cmp::max(t.inner, *w as u64) ) .delay(|(_, t, _), _| t.clone()) .as_collection() // finally keep only the shortest path between two nodes (grouped by (src, dst)) .reduce(|_key, input, output| output.push((*input[0].0, 1))) }) // -> ((src, dst), distance) // map for semijoin .map(|((src, dst), distance)| (dst, (src, distance))) // filter out result which are not between people from city1 and city2 .semijoin(&people2) ; // add sorting options and final results let result = shortest_paths .map(|(dst, (src, distance))| ( (std::isize::MAX - distance, src, dst), // sort: -distance, +src, +dst vec![src.to_string(), dst.to_string(), (distance as f64/10000000000.0).to_string()] )) ; let arrangement = limit(&result, 20) .arrange_by_self(); arrangement.stream.probe_with(&mut probe); return ( arrangement.trace, located_in_input, knows_input, has_creator_input, reply_of_input ); }); // add inputs let mut next_time: usize = 1; input_insert_vec( load_dynamic_connection("dynamic/person_isLocatedIn_place_0_0.csv", path.as_str(), index, peers), &mut located_in_input, next_time ); input_insert_vec( load_dynamic_connection("dynamic/person_knows_person_0_0.csv", path.as_str(), index, peers), &mut knows_input, next_time ); // insert hasCreator relations input_insert_vec( load_dynamic_connection("dynamic/post_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_hasCreator_person_0_0.csv", path.as_str(), index, peers), &mut has_creator_input, next_time ); // insert replyOf relations input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_post_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, 0 // do not advance just yet ); input_insert_vec( load_dynamic_connection("dynamic/comment_replyOf_comment_0_0.csv", path.as_str(), index, peers), &mut reply_of_input, next_time ); eprintln!("LOADED;{:}", timer.elapsed().as_secs_f64()); timer = Instant::now(); // Compute... while probe.less_than(knows_input.time()) { worker.step(); } eprintln!("CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print results print_trace(&mut trace, next_time); if change_path.eq(&"-".to_string()) { eprintln!("No change set was given."); return; } println!(" ---------------------------------------------------------------------- "); // introduce change set next_time += 1; timer = Instant::now(); // parse change set file for mut change_row in load_data(change_path.as_str(), index, peers) { let create = match change_row.remove(0).as_str() { "create" => true, "remove" => false, x => { panic!("Unknown change. It should be'remove' or 'create': {}", x); } }; let input = change_row.remove(0); let mut row_iter = change_row.into_iter(); let created = parse_datetime(row_iter.next().unwrap()); let id1 = row_iter.next().unwrap().parse::<Id>().unwrap(); let id2 = row_iter.next().unwrap().parse::<Id>().unwrap(); let d = DynamicConnection::new(created, id1, id2); match input.as_str() { "person-knows-person" => { if create { knows_input.insert(d); } else { knows_input.remove(d); } }, "person-islocatedin-place" => { if create { located_in_input.insert(d); } else { located_in_input.remove(d); } } x => { panic!("Unknown change type: {}", x); } } } // advance and flush all inputs... has_creator_input.advance_to(next_time); has_creator_input.flush(); reply_of_input.advance_to(next_time); reply_of_input.flush(); knows_input.advance_to(next_time); knows_input.flush(); located_in_input.advance_to(next_time); located_in_input.flush(); // Compute change set... while probe.less_than(&next_time) { worker.step(); } eprintln!("CHANGE_CALCULATED;{:.10}", timer.elapsed().as_secs_f64()); // print changed results print_trace(&mut trace, next_time); }).expect("Timely computation failed"); }
random_line_split
lib.rs
HOSTNAME"; /// This variable holds the host name for the parent edge device. This name is used /// by the edge agent to connect to parent edge hub for identity and twin operations. const GATEWAY_HOSTNAME_KEY: &str = "IOTEDGE_GATEWAYHOSTNAME"; /// This variable holds the host name for the edge device. This name is used /// by the edge agent to provide the edge hub container an alias name in the /// network so that TLS cert validation works. const EDGEDEVICE_HOSTNAME_KEY: &str = "EdgeDeviceHostName"; /// This variable holds the IoT Hub device identifier. const DEVICEID_KEY: &str = "IOTEDGE_DEVICEID"; /// This variable holds the IoT Hub module identifier. const MODULEID_KEY: &str = "IOTEDGE_MODULEID"; /// This variable holds the URI to use for connecting to the workload endpoint /// in aziot-edged. This is used by the edge agent to connect to the workload API /// for its own needs and is also used for volume mounting into module /// containers when the URI refers to a Unix domain socket. const WORKLOAD_URI_KEY: &str = "IOTEDGE_WORKLOADURI"; /// This variable holds the URI to use for connecting to the management /// endpoint in aziot-edged. This is used by the edge agent for managing module /// lifetimes and module identities. const MANAGEMENT_URI_KEY: &str = "IOTEDGE_MANAGEMENTURI"; /// This variable holds the authentication scheme that modules are to use when /// connecting to other server modules (like Edge Hub). The authentication /// scheme can mean either that we are to use SAS tokens or a TLS client cert. const AUTHSCHEME_KEY: &str = "IOTEDGE_AUTHSCHEME"; /// This is the key for the edge runtime mode. const EDGE_RUNTIME_MODE_KEY: &str = "Mode"; /// This is the edge runtime mode - it should be iotedged, when aziot-edged starts edge runtime in single node mode. const EDGE_RUNTIME_MODE: &str = "iotedged"; /// This is the key for the largest API version that this edgelet supports const API_VERSION_KEY: &str = "IOTEDGE_APIVERSION"; /// This is the name of the cache subdirectory for settings state const EDGE_SETTINGS_SUBDIR: &str = "cache"; /// This is the name of the settings backup file const EDGE_PROVISIONING_STATE_FILENAME: &str = "provisioning_state"; // This is the name of the directory that contains the module folder // with worlkload sockets inside, on the host const WORKLOAD_LISTEN_MNT_URI: &str = "IOTEDGE_WORKLOADLISTEN_MNTURI"; // 2 hours const AZIOT_EDGE_ID_CERT_MAX_DURATION_SECS: i64 = 2 * 3600; // 90 days const AZIOT_EDGE_SERVER_CERT_MAX_DURATION_SECS: i64 = 90 * 24 * 3600; const STOP_TIME: Duration = Duration::from_secs(30); /// This is the interval at which to poll Identity Service for device information. const IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS: Duration = Duration::from_secs(5); #[derive(Clone, serde::Serialize, serde::Deserialize, Debug)] pub struct ProvisioningResult { device_id: String, gateway_host_name: String, hub_name: String, } pub struct Main<M> where M: MakeModuleRuntime, { settings: M::Settings, } impl<M> Main<M> where M: MakeModuleRuntime + Send +'static, M::ModuleRuntime:'static + Authenticator<Request = Request<Body>> + Clone + Send + Sync, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize + edgelet_core::module::NestedEdgeBodge, M::Settings:'static + Clone + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, <M::ModuleRuntime as Authenticator>::Error: Fail + Sync, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { pub fn new(settings: M::Settings) -> Self { Main { settings } } // Allowing cognitive complexity errors for now. TODO: Refactor method later. #[allow(clippy::cognitive_complexity)] pub fn run_until<F, G>(self, make_shutdown_signal: G) -> Result<(), Error> where F: Future<Item = (), Error = ()> + Send +'static, G: Fn() -> F, { let Main { mut settings } = self; let mut tokio_runtime = tokio::runtime::Runtime::new() .context(ErrorKind::Initialize(InitializeErrorReason::Tokio))?; let cache_subdir_path = Path::new(&settings.homedir()).join(EDGE_SETTINGS_SUBDIR); // make sure the cache directory exists DirBuilder::new() .recursive(true) .create(&cache_subdir_path) .context(ErrorKind::Initialize( InitializeErrorReason::CreateCacheDirectory, ))?; let (create_socket_channel_snd, create_socket_channel_rcv) = mpsc::unbounded::<ModuleAction>(); let runtime = init_runtime::<M>( settings.clone(), &mut tokio_runtime, create_socket_channel_snd, )?; let url = settings.endpoints().aziot_identityd_url().clone(); let client = Arc::new(Mutex::new(identity_client::IdentityClient::new( aziot_identity_common_http::ApiVersion::V2020_09_01, &url, ))); let provisioning_result = loop { info!("Obtaining edge device provisioning data..."); match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::AlwaysOnStartup => { tokio_runtime.block_on(reprovision_device(&client))? } AutoReprovisioningMode::Dynamic | AutoReprovisioningMode::OnErrorOnly => {} } let result = tokio_runtime.block_on( client .lock() .unwrap() .get_device() .map_err(|err| { Error::from(err.context(ErrorKind::Initialize( InitializeErrorReason::GetDeviceInfo, ))) }) .and_then(|identity| match identity { aziot_identity_common::Identity::Aziot(spec) => { debug!("{}:{}", spec.hub_name, spec.device_id.0); Ok(ProvisioningResult { device_id: spec.device_id.0, gateway_host_name: spec.gateway_host, hub_name: spec.hub_name, }) } aziot_identity_common::Identity::Local(_) => Err(Error::from( ErrorKind::Initialize(InitializeErrorReason::InvalidIdentityType), )), }), ); match result { Ok(provisioning_result) => { break provisioning_result; } Err(err) => { log_failure(Level::Warn, &err); std::thread::sleep(IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS); log::warn!("Retrying getting edge device provisioning information."); } }; }; info!("Finished provisioning edge device."); // Normally aziot-edged will stop all modules when it shuts down. But if it crashed, // modules will continue to run. On Linux systems where aziot-edged is responsible for // creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not // support systemd socket activation), modules will be left holding stale file // descriptors for the workload and management APIs and calls on these APIs will // begin to fail. Resilient modules should be able to deal with this, but we'll // restart all modules to ensure a clean start. info!("Stopping all modules..."); tokio_runtime .block_on(runtime.stop_all(Some(STOP_TIME))) .context(ErrorKind::Initialize( InitializeErrorReason::StopExistingModules, ))?; info!("Finished stopping modules."); // Detect if the device was changed and if the device needs to be reconfigured check_device_reconfigure::<M>( &cache_subdir_path, EDGE_PROVISIONING_STATE_FILENAME, &provisioning_result, &runtime, &mut tokio_runtime, )?; settings .agent_mut() .parent_hostname_resolve(&provisioning_result.gateway_host_name); let cfg = WorkloadData::new( provisioning_result.hub_name, provisioning_result.device_id, settings .edge_ca_cert() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .edge_ca_key() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .trust_bundle_cert() .unwrap_or(TRUST_BUNDLE_ALIAS) .to_string(), settings .manifest_trust_bundle_cert() .unwrap_or(MANIFEST_TRUST_BUNDLE_ALIAS) .to_string(), AZIOT_EDGE_ID_CERT_MAX_DURATION_SECS, AZIOT_EDGE_SERVER_CERT_MAX_DURATION_SECS, ); let should_reprovision = start_api::<_, _, M>( &settings, &provisioning_result.gateway_host_name, &runtime, cfg, make_shutdown_signal(), &mut tokio_runtime, create_socket_channel_rcv, )?; if should_reprovision { tokio_runtime.block_on(reprovision_device(&client))?; } info!("Shutdown complete."); Ok(()) } } fn reprovision_device( identity_client: &Arc<Mutex<IdentityClient>>, ) -> impl Future<Item = (), Error = Error> { let id_mgr = identity_client.lock().unwrap(); id_mgr .reprovision_device() .map_err(|err| Error::from(err.context(ErrorKind::ReprovisionFailure))) } fn check_device_reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Detecting if device information has changed..."); let path = subdir.join(filename); let diff = diff_with_cached(provisioning_result, &path); if diff { info!("Change to provisioning state detected."); reconfigure::<M>( subdir, filename, provisioning_result, runtime, tokio_runtime, )?; } Ok(()) } fn compute_provisioning_result_digest( provisioning_result: &ProvisioningResult, ) -> Result<String, DiffError> { let s = serde_json::to_string(provisioning_result)?; Ok(base64::encode(&Sha256::digest_str(&s))) } fn diff_with_cached(provisioning_result: &ProvisioningResult, path: &Path) -> bool { fn diff_with_cached_inner( provisioning_result: &ProvisioningResult, path: &Path, ) -> Result<bool, DiffError> { let mut file = OpenOptions::new().read(true).open(path)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let encoded = compute_provisioning_result_digest(provisioning_result)?; if encoded == buffer { debug!("Provisioning state matches supplied provisioning result."); Ok(false) } else { Ok(true) } } match diff_with_cached_inner(provisioning_result, path) { Ok(result) => result, Err(err) => { log_failure(Level::Debug, &err); debug!("Error reading config backup."); true } } } #[derive(Debug, Fail)] #[fail(display = "Could not load provisioning result")] pub struct DiffError(#[cause] Context<Box<dyn std::fmt::Display + Send + Sync>>); impl From<std::io::Error> for DiffError { fn from(err: std::io::Error) -> Self { DiffError(Context::new(Box::new(err))) } } impl From<serde_json::Error> for DiffError { fn from(err: serde_json::Error) -> Self { DiffError(Context::new(Box::new(err))) } } fn reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Removing all modules..."); tokio_runtime .block_on(runtime.remove_all()) .context(ErrorKind::Initialize( InitializeErrorReason::RemoveExistingModules, ))?; info!("Finished removing modules."); let path = subdir.join(filename); // store provisioning result let digest = compute_provisioning_result_digest(provisioning_result).context( ErrorKind::Initialize(InitializeErrorReason::SaveProvisioning), )?; std::fs::write(path, digest.into_bytes()).context(ErrorKind::Initialize( InitializeErrorReason::SaveProvisioning, ))?; Ok(()) } #[allow(clippy::too_many_arguments)] fn start_api<F, W, M>( settings: &M::Settings, parent_hostname: &str, runtime: &M::ModuleRuntime, workload_config: W, shutdown_signal: F, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_rcv: UnboundedReceiver<ModuleAction>, ) -> Result<bool, Error> where F: Future<Item = (), Error = ()> + Send +'static, W: WorkloadConfig + Clone + Send + Sync +'static, M::ModuleRuntime: Authenticator<Request = Request<Body>> + Send + Sync + Clone +'static, M: MakeModuleRuntime +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, M::Settings:'static, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, <M::ModuleRuntime as Authenticator>::Error: Fail + Sync, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>,
&iot_hub_name, parent_hostname, &device_id, &settings, runt_rx, )?; // This mpsc sender/receiver is used for getting notifications from the mgmt service // indicating that the daemon should shut down and attempt to reprovision the device. let mgmt_stop_and_reprovision_signaled = mgmt_stop_and_reprovision_rx .into_future() .then(|res| match res { Ok((Some(()), _)) | Ok((None, _)) => Ok(()), Err(((), _)) => Err(Error::from(ErrorKind::ManagementService)), }); let mgmt_stop_and_reprovision_signaled = match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::Dynamic => { futures::future::Either::B(mgmt_stop_and_reprovision_signaled) } AutoReprovisioningMode::AlwaysOnStartup | AutoReprovisioningMode::OnErrorOnly => { futures::future::Either::A(future::empty()) } }; let edge_rt_with_mgmt_signal = edge_rt.select2(mgmt_stop_and_reprovision_signaled).then( |res| match res { Ok(Either::A((_edge_rt_ok, _mgmt_stop_and_reprovision_signaled_future))) => { info!("Edge runtime will stop because of the shutdown signal."); future::ok(false) } Ok(Either::B((_mgmt_stop_and_reprovision_signaled_ok, _edge_rt_future))) => { info!("Edge runtime will stop because of the device reprovisioning signal."); future::ok(true) } Err(Either::A((edge_rt_err, _mgmt_stop_and_reprovision_signaled_future))) => { error!("Edge runtime will stop because the shutdown signal raised an error."); future::err(edge_rt_err) }, Err(Either::B((mgmt_stop_and_reprovision_signaled_err, _edge_rt_future))) => { error!("Edge runtime will stop because the device reprovisioning signal raised an error."); future::err(mgmt_stop_and_reprovision_signaled_err) } }, ); // Wait for the watchdog to finish, and then send signal to the workload and management services. // This way the edgeAgent can finish shutting down all modules. let edge_rt_with_cleanup = edge_rt_with_mgmt_signal.then(move |res| { mgmt_tx.send(()).unwrap_or(()); // A -> EdgeRt + Mgmt Stop and Reprovision Signal Future // B -> Restart Signal Future match res { Ok(should_reprovision) => future::ok(should_reprovision), Err(err) => future::err(err), } }); let shutdown = shutdown_signal.map(move |_| { debug!("shutdown signaled"); // Signal the watchdog to shutdown runt_tx.send(()).unwrap_or(()); }); tokio_runtime.spawn(shutdown); let services = mgmt.join(edge_rt_with_cleanup).then(|result| match result { Ok(((), should_reprovision)) => Ok(should_reprovision), Err(err) => Err(err), }); let should_reprovision = tokio_runtime.block_on(services)?; Ok(should_reprovision) } fn init_runtime<M>( settings: M::Settings, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_snd: UnboundedSender<ModuleAction>, ) -> Result<M::ModuleRuntime, Error> where M: MakeModuleRuntime + Send +'static, M::ModuleRuntime: Send, M::Future:'static, { info!("Initializing the module runtime..."); let runtime = tokio_runtime .block_on(M::make_runtime(settings, create_socket_channel_snd)) .context(ErrorKind::Initialize(InitializeErrorReason::ModuleRuntime))?; info!("Finished initializing the module runtime."); Ok(runtime) } fn start_runtime<M>( runtime: M::ModuleRuntime, hostname: &str, parent_hostname: &str, device_id: &str, settings: &M::Settings, shutdown: Receiver<()>, ) -> Result<impl Future<Item = (), Error = Error>, Error> where M: MakeModuleRuntime, M::ModuleRuntime: Clone +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { let spec = settings.agent().clone(); let env = build_env(spec.env(), hostname, parent_hostname, device_id, settings); let spec = ModuleSpec::<<M::ModuleRuntime as ModuleRuntime>::Config>::new( EDGE_RUNTIME_MODULE_NAME.to_string(), spec.type_().to_string(), spec.config().clone(), env, spec.image_pull_policy(), ) .context(ErrorKind::Initialize(InitializeErrorReason::EdgeRuntime))?; let watchdog = Watchdog::new( runtime, settings.watchdog().max_retries(), settings.endpoints().aziot_identityd_url(), ); let runtime_future = watchdog .run_until(spec, EDGE_RUNTIME_MODULEID, shutdown.map_err(|_| ())) .map_err(Error::from); Ok(runtime_future) } // Add the environment variables needed by the EdgeAgent. fn build_env<S>( spec_env: &BTreeMap<String, String>, hostname: &str, parent_hostname: &str, device_id: &str, settings: &S, ) -> BTreeMap<String, String> where S: RuntimeSettings, { let mut env = BTreeMap::new();
{ let iot_hub_name = workload_config.iot_hub_name().to_string(); let device_id = workload_config.device_id().to_string(); let (mgmt_tx, mgmt_rx) = oneshot::channel(); let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded(); let mgmt = start_management::<M>(settings, runtime, mgmt_rx, mgmt_stop_and_reprovision_tx); WorkloadManager::start_manager::<M>( settings, runtime, workload_config, tokio_runtime, create_socket_channel_rcv, )?; let (runt_tx, runt_rx) = oneshot::channel(); let edge_rt = start_runtime::<M>( runtime.clone(),
identifier_body
lib.rs
_runtime, create_socket_channel_snd, )?; let url = settings.endpoints().aziot_identityd_url().clone(); let client = Arc::new(Mutex::new(identity_client::IdentityClient::new( aziot_identity_common_http::ApiVersion::V2020_09_01, &url, ))); let provisioning_result = loop { info!("Obtaining edge device provisioning data..."); match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::AlwaysOnStartup => { tokio_runtime.block_on(reprovision_device(&client))? } AutoReprovisioningMode::Dynamic | AutoReprovisioningMode::OnErrorOnly => {} } let result = tokio_runtime.block_on( client .lock() .unwrap() .get_device() .map_err(|err| { Error::from(err.context(ErrorKind::Initialize( InitializeErrorReason::GetDeviceInfo, ))) }) .and_then(|identity| match identity { aziot_identity_common::Identity::Aziot(spec) => { debug!("{}:{}", spec.hub_name, spec.device_id.0); Ok(ProvisioningResult { device_id: spec.device_id.0, gateway_host_name: spec.gateway_host, hub_name: spec.hub_name, }) } aziot_identity_common::Identity::Local(_) => Err(Error::from( ErrorKind::Initialize(InitializeErrorReason::InvalidIdentityType), )), }), ); match result { Ok(provisioning_result) => { break provisioning_result; } Err(err) => { log_failure(Level::Warn, &err); std::thread::sleep(IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS); log::warn!("Retrying getting edge device provisioning information."); } }; }; info!("Finished provisioning edge device."); // Normally aziot-edged will stop all modules when it shuts down. But if it crashed, // modules will continue to run. On Linux systems where aziot-edged is responsible for // creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not // support systemd socket activation), modules will be left holding stale file // descriptors for the workload and management APIs and calls on these APIs will // begin to fail. Resilient modules should be able to deal with this, but we'll // restart all modules to ensure a clean start. info!("Stopping all modules..."); tokio_runtime .block_on(runtime.stop_all(Some(STOP_TIME))) .context(ErrorKind::Initialize( InitializeErrorReason::StopExistingModules, ))?; info!("Finished stopping modules."); // Detect if the device was changed and if the device needs to be reconfigured check_device_reconfigure::<M>( &cache_subdir_path, EDGE_PROVISIONING_STATE_FILENAME, &provisioning_result, &runtime, &mut tokio_runtime, )?; settings .agent_mut() .parent_hostname_resolve(&provisioning_result.gateway_host_name); let cfg = WorkloadData::new( provisioning_result.hub_name, provisioning_result.device_id, settings .edge_ca_cert() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .edge_ca_key() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .trust_bundle_cert() .unwrap_or(TRUST_BUNDLE_ALIAS) .to_string(), settings .manifest_trust_bundle_cert() .unwrap_or(MANIFEST_TRUST_BUNDLE_ALIAS) .to_string(), AZIOT_EDGE_ID_CERT_MAX_DURATION_SECS, AZIOT_EDGE_SERVER_CERT_MAX_DURATION_SECS, ); let should_reprovision = start_api::<_, _, M>( &settings, &provisioning_result.gateway_host_name, &runtime, cfg, make_shutdown_signal(), &mut tokio_runtime, create_socket_channel_rcv, )?; if should_reprovision { tokio_runtime.block_on(reprovision_device(&client))?; } info!("Shutdown complete."); Ok(()) } } fn reprovision_device( identity_client: &Arc<Mutex<IdentityClient>>, ) -> impl Future<Item = (), Error = Error> { let id_mgr = identity_client.lock().unwrap(); id_mgr .reprovision_device() .map_err(|err| Error::from(err.context(ErrorKind::ReprovisionFailure))) } fn check_device_reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Detecting if device information has changed..."); let path = subdir.join(filename); let diff = diff_with_cached(provisioning_result, &path); if diff { info!("Change to provisioning state detected."); reconfigure::<M>( subdir, filename, provisioning_result, runtime, tokio_runtime, )?; } Ok(()) } fn compute_provisioning_result_digest( provisioning_result: &ProvisioningResult, ) -> Result<String, DiffError> { let s = serde_json::to_string(provisioning_result)?; Ok(base64::encode(&Sha256::digest_str(&s))) } fn diff_with_cached(provisioning_result: &ProvisioningResult, path: &Path) -> bool { fn diff_with_cached_inner( provisioning_result: &ProvisioningResult, path: &Path, ) -> Result<bool, DiffError> { let mut file = OpenOptions::new().read(true).open(path)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let encoded = compute_provisioning_result_digest(provisioning_result)?; if encoded == buffer { debug!("Provisioning state matches supplied provisioning result."); Ok(false) } else { Ok(true) } } match diff_with_cached_inner(provisioning_result, path) { Ok(result) => result, Err(err) => { log_failure(Level::Debug, &err); debug!("Error reading config backup."); true } } } #[derive(Debug, Fail)] #[fail(display = "Could not load provisioning result")] pub struct DiffError(#[cause] Context<Box<dyn std::fmt::Display + Send + Sync>>); impl From<std::io::Error> for DiffError { fn from(err: std::io::Error) -> Self { DiffError(Context::new(Box::new(err))) } } impl From<serde_json::Error> for DiffError { fn from(err: serde_json::Error) -> Self { DiffError(Context::new(Box::new(err))) } } fn reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Removing all modules..."); tokio_runtime .block_on(runtime.remove_all()) .context(ErrorKind::Initialize( InitializeErrorReason::RemoveExistingModules, ))?; info!("Finished removing modules."); let path = subdir.join(filename); // store provisioning result let digest = compute_provisioning_result_digest(provisioning_result).context( ErrorKind::Initialize(InitializeErrorReason::SaveProvisioning), )?; std::fs::write(path, digest.into_bytes()).context(ErrorKind::Initialize( InitializeErrorReason::SaveProvisioning, ))?; Ok(()) } #[allow(clippy::too_many_arguments)] fn start_api<F, W, M>( settings: &M::Settings, parent_hostname: &str, runtime: &M::ModuleRuntime, workload_config: W, shutdown_signal: F, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_rcv: UnboundedReceiver<ModuleAction>, ) -> Result<bool, Error> where F: Future<Item = (), Error = ()> + Send +'static, W: WorkloadConfig + Clone + Send + Sync +'static, M::ModuleRuntime: Authenticator<Request = Request<Body>> + Send + Sync + Clone +'static, M: MakeModuleRuntime +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, M::Settings:'static, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, <M::ModuleRuntime as Authenticator>::Error: Fail + Sync, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { let iot_hub_name = workload_config.iot_hub_name().to_string(); let device_id = workload_config.device_id().to_string(); let (mgmt_tx, mgmt_rx) = oneshot::channel(); let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded(); let mgmt = start_management::<M>(settings, runtime, mgmt_rx, mgmt_stop_and_reprovision_tx); WorkloadManager::start_manager::<M>( settings, runtime, workload_config, tokio_runtime, create_socket_channel_rcv, )?; let (runt_tx, runt_rx) = oneshot::channel(); let edge_rt = start_runtime::<M>( runtime.clone(), &iot_hub_name, parent_hostname, &device_id, &settings, runt_rx, )?; // This mpsc sender/receiver is used for getting notifications from the mgmt service // indicating that the daemon should shut down and attempt to reprovision the device. let mgmt_stop_and_reprovision_signaled = mgmt_stop_and_reprovision_rx .into_future() .then(|res| match res { Ok((Some(()), _)) | Ok((None, _)) => Ok(()), Err(((), _)) => Err(Error::from(ErrorKind::ManagementService)), }); let mgmt_stop_and_reprovision_signaled = match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::Dynamic => { futures::future::Either::B(mgmt_stop_and_reprovision_signaled) } AutoReprovisioningMode::AlwaysOnStartup | AutoReprovisioningMode::OnErrorOnly => { futures::future::Either::A(future::empty()) } }; let edge_rt_with_mgmt_signal = edge_rt.select2(mgmt_stop_and_reprovision_signaled).then( |res| match res { Ok(Either::A((_edge_rt_ok, _mgmt_stop_and_reprovision_signaled_future))) => { info!("Edge runtime will stop because of the shutdown signal."); future::ok(false) } Ok(Either::B((_mgmt_stop_and_reprovision_signaled_ok, _edge_rt_future))) => { info!("Edge runtime will stop because of the device reprovisioning signal."); future::ok(true) } Err(Either::A((edge_rt_err, _mgmt_stop_and_reprovision_signaled_future))) => { error!("Edge runtime will stop because the shutdown signal raised an error."); future::err(edge_rt_err) }, Err(Either::B((mgmt_stop_and_reprovision_signaled_err, _edge_rt_future))) => { error!("Edge runtime will stop because the device reprovisioning signal raised an error."); future::err(mgmt_stop_and_reprovision_signaled_err) } }, ); // Wait for the watchdog to finish, and then send signal to the workload and management services. // This way the edgeAgent can finish shutting down all modules. let edge_rt_with_cleanup = edge_rt_with_mgmt_signal.then(move |res| { mgmt_tx.send(()).unwrap_or(()); // A -> EdgeRt + Mgmt Stop and Reprovision Signal Future // B -> Restart Signal Future match res { Ok(should_reprovision) => future::ok(should_reprovision), Err(err) => future::err(err), } }); let shutdown = shutdown_signal.map(move |_| { debug!("shutdown signaled"); // Signal the watchdog to shutdown runt_tx.send(()).unwrap_or(()); }); tokio_runtime.spawn(shutdown); let services = mgmt.join(edge_rt_with_cleanup).then(|result| match result { Ok(((), should_reprovision)) => Ok(should_reprovision), Err(err) => Err(err), }); let should_reprovision = tokio_runtime.block_on(services)?; Ok(should_reprovision) } fn init_runtime<M>( settings: M::Settings, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_snd: UnboundedSender<ModuleAction>, ) -> Result<M::ModuleRuntime, Error> where M: MakeModuleRuntime + Send +'static, M::ModuleRuntime: Send, M::Future:'static, { info!("Initializing the module runtime..."); let runtime = tokio_runtime .block_on(M::make_runtime(settings, create_socket_channel_snd)) .context(ErrorKind::Initialize(InitializeErrorReason::ModuleRuntime))?; info!("Finished initializing the module runtime."); Ok(runtime) } fn start_runtime<M>( runtime: M::ModuleRuntime, hostname: &str, parent_hostname: &str, device_id: &str, settings: &M::Settings, shutdown: Receiver<()>, ) -> Result<impl Future<Item = (), Error = Error>, Error> where M: MakeModuleRuntime, M::ModuleRuntime: Clone +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { let spec = settings.agent().clone(); let env = build_env(spec.env(), hostname, parent_hostname, device_id, settings); let spec = ModuleSpec::<<M::ModuleRuntime as ModuleRuntime>::Config>::new( EDGE_RUNTIME_MODULE_NAME.to_string(), spec.type_().to_string(), spec.config().clone(), env, spec.image_pull_policy(), ) .context(ErrorKind::Initialize(InitializeErrorReason::EdgeRuntime))?; let watchdog = Watchdog::new( runtime, settings.watchdog().max_retries(), settings.endpoints().aziot_identityd_url(), ); let runtime_future = watchdog .run_until(spec, EDGE_RUNTIME_MODULEID, shutdown.map_err(|_| ())) .map_err(Error::from); Ok(runtime_future) } // Add the environment variables needed by the EdgeAgent. fn build_env<S>( spec_env: &BTreeMap<String, String>, hostname: &str, parent_hostname: &str, device_id: &str, settings: &S, ) -> BTreeMap<String, String> where S: RuntimeSettings, { let mut env = BTreeMap::new(); env.insert(HOSTNAME_KEY.to_string(), hostname.to_string()); env.insert( EDGEDEVICE_HOSTNAME_KEY.to_string(), settings.hostname().to_string().to_lowercase(), ); if parent_hostname.to_lowercase()!= hostname.to_lowercase() { env.insert( GATEWAY_HOSTNAME_KEY.to_string(), parent_hostname.to_string(), ); } env.insert(DEVICEID_KEY.to_string(), device_id.to_string()); env.insert(MODULEID_KEY.to_string(), EDGE_RUNTIME_MODULEID.to_string()); #[cfg(feature = "runtime-docker")] let (workload_uri, management_uri, home_dir) = ( settings.connect().workload_uri().to_string(), settings.connect().management_uri().to_string(), settings.homedir().to_str().unwrap().to_string(), ); env.insert(WORKLOAD_URI_KEY.to_string(), workload_uri); env.insert(MANAGEMENT_URI_KEY.to_string(), management_uri); env.insert( WORKLOAD_LISTEN_MNT_URI.to_string(), Listen::workload_mnt_uri(&home_dir), ); env.insert(AUTHSCHEME_KEY.to_string(), AUTH_SCHEME.to_string()); env.insert( EDGE_RUNTIME_MODE_KEY.to_string(), EDGE_RUNTIME_MODE.to_string(), ); for (key, val) in spec_env.iter() { env.insert(key.clone(), val.clone()); } env.insert(API_VERSION_KEY.to_string(), API_VERSION.to_string()); env } fn start_management<M>( settings: &M::Settings, runtime: &M::ModuleRuntime, shutdown: Receiver<()>, initiate_shutdown_and_reprovision: mpsc::UnboundedSender<()>, ) -> impl Future<Item = (), Error = Error> where M: MakeModuleRuntime, M::ModuleRuntime: Authenticator<Request = Request<Body>> + Send + Sync + Clone +'static, <<M::ModuleRuntime as Authenticator>::AuthenticateFuture as Future>::Error: Fail, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: DeserializeOwned + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, { info!("Starting management API..."); let label = "mgmt".to_string(); let url = settings.listen().management_uri().clone(); let identity_uri = settings.endpoints().aziot_identityd_url().clone(); let identity_client = Arc::new(Mutex::new(identity_client::IdentityClient::new( aziot_identity_common_http::ApiVersion::V2020_09_01, &identity_uri, ))); ManagementService::new(runtime, identity_client, initiate_shutdown_and_reprovision) .then(move |service| -> Result<_, Error> { let service = service.context(ErrorKind::Initialize( InitializeErrorReason::ManagementService, ))?; let service = LoggingService::new(label, service); let run = Http::new() .bind_url(url.clone(), service, MGMT_SOCKET_DEFAULT_PERMISSION) .map_err(|err| { err.context(ErrorKind::Initialize( InitializeErrorReason::ManagementService, )) })? .run_until(shutdown.map_err(|_| ()), ConcurrencyThrottling::NoLimit) .map_err(|err| Error::from(err.context(ErrorKind::ManagementService))); info!("Listening on {} with 1 thread for management API.", url); Ok(run) }) .flatten() } #[cfg(test)] mod tests { use std::fmt; use edgelet_docker::Settings; use super::{Fail, RuntimeSettings}; static GOOD_SETTINGS_EDGE_CA_CERT_ID: &str = "test/linux/sample_settings.edge.ca.id.toml"; #[derive(Clone, Copy, Debug, Fail)] pub struct
Error
identifier_name
lib.rs
UBHOSTNAME"; /// This variable holds the host name for the parent edge device. This name is used /// by the edge agent to connect to parent edge hub for identity and twin operations. const GATEWAY_HOSTNAME_KEY: &str = "IOTEDGE_GATEWAYHOSTNAME"; /// This variable holds the host name for the edge device. This name is used /// by the edge agent to provide the edge hub container an alias name in the /// network so that TLS cert validation works. const EDGEDEVICE_HOSTNAME_KEY: &str = "EdgeDeviceHostName"; /// This variable holds the IoT Hub device identifier. const DEVICEID_KEY: &str = "IOTEDGE_DEVICEID"; /// This variable holds the IoT Hub module identifier. const MODULEID_KEY: &str = "IOTEDGE_MODULEID"; /// This variable holds the URI to use for connecting to the workload endpoint /// in aziot-edged. This is used by the edge agent to connect to the workload API /// for its own needs and is also used for volume mounting into module /// containers when the URI refers to a Unix domain socket. const WORKLOAD_URI_KEY: &str = "IOTEDGE_WORKLOADURI"; /// This variable holds the URI to use for connecting to the management /// endpoint in aziot-edged. This is used by the edge agent for managing module /// lifetimes and module identities. const MANAGEMENT_URI_KEY: &str = "IOTEDGE_MANAGEMENTURI"; /// This variable holds the authentication scheme that modules are to use when /// connecting to other server modules (like Edge Hub). The authentication /// scheme can mean either that we are to use SAS tokens or a TLS client cert. const AUTHSCHEME_KEY: &str = "IOTEDGE_AUTHSCHEME"; /// This is the key for the edge runtime mode. const EDGE_RUNTIME_MODE_KEY: &str = "Mode"; /// This is the edge runtime mode - it should be iotedged, when aziot-edged starts edge runtime in single node mode. const EDGE_RUNTIME_MODE: &str = "iotedged"; /// This is the key for the largest API version that this edgelet supports const API_VERSION_KEY: &str = "IOTEDGE_APIVERSION"; /// This is the name of the cache subdirectory for settings state const EDGE_SETTINGS_SUBDIR: &str = "cache"; /// This is the name of the settings backup file const EDGE_PROVISIONING_STATE_FILENAME: &str = "provisioning_state"; // This is the name of the directory that contains the module folder // with worlkload sockets inside, on the host const WORKLOAD_LISTEN_MNT_URI: &str = "IOTEDGE_WORKLOADLISTEN_MNTURI"; // 2 hours const AZIOT_EDGE_ID_CERT_MAX_DURATION_SECS: i64 = 2 * 3600; // 90 days const AZIOT_EDGE_SERVER_CERT_MAX_DURATION_SECS: i64 = 90 * 24 * 3600; const STOP_TIME: Duration = Duration::from_secs(30); /// This is the interval at which to poll Identity Service for device information. const IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS: Duration = Duration::from_secs(5); #[derive(Clone, serde::Serialize, serde::Deserialize, Debug)] pub struct ProvisioningResult { device_id: String, gateway_host_name: String, hub_name: String, } pub struct Main<M> where M: MakeModuleRuntime, { settings: M::Settings, } impl<M> Main<M> where M: MakeModuleRuntime + Send +'static, M::ModuleRuntime:'static + Authenticator<Request = Request<Body>> + Clone + Send + Sync, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize + edgelet_core::module::NestedEdgeBodge, M::Settings:'static + Clone + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, <M::ModuleRuntime as Authenticator>::Error: Fail + Sync, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { pub fn new(settings: M::Settings) -> Self { Main { settings } } // Allowing cognitive complexity errors for now. TODO: Refactor method later. #[allow(clippy::cognitive_complexity)] pub fn run_until<F, G>(self, make_shutdown_signal: G) -> Result<(), Error> where F: Future<Item = (), Error = ()> + Send +'static, G: Fn() -> F, { let Main { mut settings } = self; let mut tokio_runtime = tokio::runtime::Runtime::new() .context(ErrorKind::Initialize(InitializeErrorReason::Tokio))?; let cache_subdir_path = Path::new(&settings.homedir()).join(EDGE_SETTINGS_SUBDIR); // make sure the cache directory exists DirBuilder::new() .recursive(true) .create(&cache_subdir_path) .context(ErrorKind::Initialize( InitializeErrorReason::CreateCacheDirectory, ))?; let (create_socket_channel_snd, create_socket_channel_rcv) = mpsc::unbounded::<ModuleAction>(); let runtime = init_runtime::<M>( settings.clone(), &mut tokio_runtime, create_socket_channel_snd, )?; let url = settings.endpoints().aziot_identityd_url().clone(); let client = Arc::new(Mutex::new(identity_client::IdentityClient::new( aziot_identity_common_http::ApiVersion::V2020_09_01, &url, ))); let provisioning_result = loop { info!("Obtaining edge device provisioning data..."); match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::AlwaysOnStartup => { tokio_runtime.block_on(reprovision_device(&client))? } AutoReprovisioningMode::Dynamic | AutoReprovisioningMode::OnErrorOnly => {} } let result = tokio_runtime.block_on( client .lock() .unwrap() .get_device() .map_err(|err| { Error::from(err.context(ErrorKind::Initialize( InitializeErrorReason::GetDeviceInfo, ))) }) .and_then(|identity| match identity { aziot_identity_common::Identity::Aziot(spec) => { debug!("{}:{}", spec.hub_name, spec.device_id.0); Ok(ProvisioningResult { device_id: spec.device_id.0, gateway_host_name: spec.gateway_host, hub_name: spec.hub_name, }) } aziot_identity_common::Identity::Local(_) => Err(Error::from( ErrorKind::Initialize(InitializeErrorReason::InvalidIdentityType), )), }), ); match result { Ok(provisioning_result) => { break provisioning_result; } Err(err) => { log_failure(Level::Warn, &err); std::thread::sleep(IS_GET_DEVICE_INFO_RETRY_INTERVAL_SECS); log::warn!("Retrying getting edge device provisioning information."); }
// Normally aziot-edged will stop all modules when it shuts down. But if it crashed, // modules will continue to run. On Linux systems where aziot-edged is responsible for // creating/binding the socket (e.g., CentOS 7.5, which uses systemd but does not // support systemd socket activation), modules will be left holding stale file // descriptors for the workload and management APIs and calls on these APIs will // begin to fail. Resilient modules should be able to deal with this, but we'll // restart all modules to ensure a clean start. info!("Stopping all modules..."); tokio_runtime .block_on(runtime.stop_all(Some(STOP_TIME))) .context(ErrorKind::Initialize( InitializeErrorReason::StopExistingModules, ))?; info!("Finished stopping modules."); // Detect if the device was changed and if the device needs to be reconfigured check_device_reconfigure::<M>( &cache_subdir_path, EDGE_PROVISIONING_STATE_FILENAME, &provisioning_result, &runtime, &mut tokio_runtime, )?; settings .agent_mut() .parent_hostname_resolve(&provisioning_result.gateway_host_name); let cfg = WorkloadData::new( provisioning_result.hub_name, provisioning_result.device_id, settings .edge_ca_cert() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .edge_ca_key() .unwrap_or(AZIOT_EDGED_CA_ALIAS) .to_string(), settings .trust_bundle_cert() .unwrap_or(TRUST_BUNDLE_ALIAS) .to_string(), settings .manifest_trust_bundle_cert() .unwrap_or(MANIFEST_TRUST_BUNDLE_ALIAS) .to_string(), AZIOT_EDGE_ID_CERT_MAX_DURATION_SECS, AZIOT_EDGE_SERVER_CERT_MAX_DURATION_SECS, ); let should_reprovision = start_api::<_, _, M>( &settings, &provisioning_result.gateway_host_name, &runtime, cfg, make_shutdown_signal(), &mut tokio_runtime, create_socket_channel_rcv, )?; if should_reprovision { tokio_runtime.block_on(reprovision_device(&client))?; } info!("Shutdown complete."); Ok(()) } } fn reprovision_device( identity_client: &Arc<Mutex<IdentityClient>>, ) -> impl Future<Item = (), Error = Error> { let id_mgr = identity_client.lock().unwrap(); id_mgr .reprovision_device() .map_err(|err| Error::from(err.context(ErrorKind::ReprovisionFailure))) } fn check_device_reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Detecting if device information has changed..."); let path = subdir.join(filename); let diff = diff_with_cached(provisioning_result, &path); if diff { info!("Change to provisioning state detected."); reconfigure::<M>( subdir, filename, provisioning_result, runtime, tokio_runtime, )?; } Ok(()) } fn compute_provisioning_result_digest( provisioning_result: &ProvisioningResult, ) -> Result<String, DiffError> { let s = serde_json::to_string(provisioning_result)?; Ok(base64::encode(&Sha256::digest_str(&s))) } fn diff_with_cached(provisioning_result: &ProvisioningResult, path: &Path) -> bool { fn diff_with_cached_inner( provisioning_result: &ProvisioningResult, path: &Path, ) -> Result<bool, DiffError> { let mut file = OpenOptions::new().read(true).open(path)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let encoded = compute_provisioning_result_digest(provisioning_result)?; if encoded == buffer { debug!("Provisioning state matches supplied provisioning result."); Ok(false) } else { Ok(true) } } match diff_with_cached_inner(provisioning_result, path) { Ok(result) => result, Err(err) => { log_failure(Level::Debug, &err); debug!("Error reading config backup."); true } } } #[derive(Debug, Fail)] #[fail(display = "Could not load provisioning result")] pub struct DiffError(#[cause] Context<Box<dyn std::fmt::Display + Send + Sync>>); impl From<std::io::Error> for DiffError { fn from(err: std::io::Error) -> Self { DiffError(Context::new(Box::new(err))) } } impl From<serde_json::Error> for DiffError { fn from(err: serde_json::Error) -> Self { DiffError(Context::new(Box::new(err))) } } fn reconfigure<M>( subdir: &Path, filename: &str, provisioning_result: &ProvisioningResult, runtime: &M::ModuleRuntime, tokio_runtime: &mut tokio::runtime::Runtime, ) -> Result<(), Error> where M: MakeModuleRuntime +'static, { info!("Removing all modules..."); tokio_runtime .block_on(runtime.remove_all()) .context(ErrorKind::Initialize( InitializeErrorReason::RemoveExistingModules, ))?; info!("Finished removing modules."); let path = subdir.join(filename); // store provisioning result let digest = compute_provisioning_result_digest(provisioning_result).context( ErrorKind::Initialize(InitializeErrorReason::SaveProvisioning), )?; std::fs::write(path, digest.into_bytes()).context(ErrorKind::Initialize( InitializeErrorReason::SaveProvisioning, ))?; Ok(()) } #[allow(clippy::too_many_arguments)] fn start_api<F, W, M>( settings: &M::Settings, parent_hostname: &str, runtime: &M::ModuleRuntime, workload_config: W, shutdown_signal: F, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_rcv: UnboundedReceiver<ModuleAction>, ) -> Result<bool, Error> where F: Future<Item = (), Error = ()> + Send +'static, W: WorkloadConfig + Clone + Send + Sync +'static, M::ModuleRuntime: Authenticator<Request = Request<Body>> + Send + Sync + Clone +'static, M: MakeModuleRuntime +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, M::Settings:'static, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, <M::ModuleRuntime as Authenticator>::Error: Fail + Sync, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { let iot_hub_name = workload_config.iot_hub_name().to_string(); let device_id = workload_config.device_id().to_string(); let (mgmt_tx, mgmt_rx) = oneshot::channel(); let (mgmt_stop_and_reprovision_tx, mgmt_stop_and_reprovision_rx) = mpsc::unbounded(); let mgmt = start_management::<M>(settings, runtime, mgmt_rx, mgmt_stop_and_reprovision_tx); WorkloadManager::start_manager::<M>( settings, runtime, workload_config, tokio_runtime, create_socket_channel_rcv, )?; let (runt_tx, runt_rx) = oneshot::channel(); let edge_rt = start_runtime::<M>( runtime.clone(), &iot_hub_name, parent_hostname, &device_id, &settings, runt_rx, )?; // This mpsc sender/receiver is used for getting notifications from the mgmt service // indicating that the daemon should shut down and attempt to reprovision the device. let mgmt_stop_and_reprovision_signaled = mgmt_stop_and_reprovision_rx .into_future() .then(|res| match res { Ok((Some(()), _)) | Ok((None, _)) => Ok(()), Err(((), _)) => Err(Error::from(ErrorKind::ManagementService)), }); let mgmt_stop_and_reprovision_signaled = match settings.auto_reprovisioning_mode() { AutoReprovisioningMode::Dynamic => { futures::future::Either::B(mgmt_stop_and_reprovision_signaled) } AutoReprovisioningMode::AlwaysOnStartup | AutoReprovisioningMode::OnErrorOnly => { futures::future::Either::A(future::empty()) } }; let edge_rt_with_mgmt_signal = edge_rt.select2(mgmt_stop_and_reprovision_signaled).then( |res| match res { Ok(Either::A((_edge_rt_ok, _mgmt_stop_and_reprovision_signaled_future))) => { info!("Edge runtime will stop because of the shutdown signal."); future::ok(false) } Ok(Either::B((_mgmt_stop_and_reprovision_signaled_ok, _edge_rt_future))) => { info!("Edge runtime will stop because of the device reprovisioning signal."); future::ok(true) } Err(Either::A((edge_rt_err, _mgmt_stop_and_reprovision_signaled_future))) => { error!("Edge runtime will stop because the shutdown signal raised an error."); future::err(edge_rt_err) }, Err(Either::B((mgmt_stop_and_reprovision_signaled_err, _edge_rt_future))) => { error!("Edge runtime will stop because the device reprovisioning signal raised an error."); future::err(mgmt_stop_and_reprovision_signaled_err) } }, ); // Wait for the watchdog to finish, and then send signal to the workload and management services. // This way the edgeAgent can finish shutting down all modules. let edge_rt_with_cleanup = edge_rt_with_mgmt_signal.then(move |res| { mgmt_tx.send(()).unwrap_or(()); // A -> EdgeRt + Mgmt Stop and Reprovision Signal Future // B -> Restart Signal Future match res { Ok(should_reprovision) => future::ok(should_reprovision), Err(err) => future::err(err), } }); let shutdown = shutdown_signal.map(move |_| { debug!("shutdown signaled"); // Signal the watchdog to shutdown runt_tx.send(()).unwrap_or(()); }); tokio_runtime.spawn(shutdown); let services = mgmt.join(edge_rt_with_cleanup).then(|result| match result { Ok(((), should_reprovision)) => Ok(should_reprovision), Err(err) => Err(err), }); let should_reprovision = tokio_runtime.block_on(services)?; Ok(should_reprovision) } fn init_runtime<M>( settings: M::Settings, tokio_runtime: &mut tokio::runtime::Runtime, create_socket_channel_snd: UnboundedSender<ModuleAction>, ) -> Result<M::ModuleRuntime, Error> where M: MakeModuleRuntime + Send +'static, M::ModuleRuntime: Send, M::Future:'static, { info!("Initializing the module runtime..."); let runtime = tokio_runtime .block_on(M::make_runtime(settings, create_socket_channel_snd)) .context(ErrorKind::Initialize(InitializeErrorReason::ModuleRuntime))?; info!("Finished initializing the module runtime."); Ok(runtime) } fn start_runtime<M>( runtime: M::ModuleRuntime, hostname: &str, parent_hostname: &str, device_id: &str, settings: &M::Settings, shutdown: Receiver<()>, ) -> Result<impl Future<Item = (), Error = Error>, Error> where M: MakeModuleRuntime, M::ModuleRuntime: Clone +'static, <<M::ModuleRuntime as ModuleRuntime>::Module as Module>::Config: Clone + DeserializeOwned + Serialize, <M::ModuleRuntime as ModuleRuntime>::Logs: Into<Body>, for<'r> &'r <M::ModuleRuntime as ModuleRuntime>::Error: Into<ModuleRuntimeErrorReason>, { let spec = settings.agent().clone(); let env = build_env(spec.env(), hostname, parent_hostname, device_id, settings); let spec = ModuleSpec::<<M::ModuleRuntime as ModuleRuntime>::Config>::new( EDGE_RUNTIME_MODULE_NAME.to_string(), spec.type_().to_string(), spec.config().clone(), env, spec.image_pull_policy(), ) .context(ErrorKind::Initialize(InitializeErrorReason::EdgeRuntime))?; let watchdog = Watchdog::new( runtime, settings.watchdog().max_retries(), settings.endpoints().aziot_identityd_url(), ); let runtime_future = watchdog .run_until(spec, EDGE_RUNTIME_MODULEID, shutdown.map_err(|_| ())) .map_err(Error::from); Ok(runtime_future) } // Add the environment variables needed by the EdgeAgent. fn build_env<S>( spec_env: &BTreeMap<String, String>, hostname: &str, parent_hostname: &str, device_id: &str, settings: &S, ) -> BTreeMap<String, String> where S: RuntimeSettings, { let mut env = BTreeMap::new();
}; }; info!("Finished provisioning edge device.");
random_line_split
day04.rs
//! # --- Day 4: Passport Processing --- //! //! You arrive at the airport only to realize that you grabbed your North Pole //! Credentials instead of your passport. While these documents are extremely //! similar, North Pole Credentials aren't issued by a country and therefore //! aren't actually valid documentation for travel in most of the world. //! //! It seems like you're not the only one having problems, though; a very long //! line has formed for the automatic passport scanners, and the delay could //! upset your travel itinerary. //! //! Due to some questionable network security, you realize you might be able to //! solve both of these problems at the same time. //! //! The automatic passport scanners are slow because they're having trouble //! **detecting which passports have all required fields**. The expected fields //! are as follows: //! //! - `byr` (Birth Year) //! - `iyr` (Issue Year) //! - `eyr` (Expiration Year) //! - `hgt` (Height) //! - `hcl` (Hair Color) //! - `ecl` (Eye Color) //! - `pid` (Passport ID) //! - `cid` (Country ID) //! //! Passport data is validated in batch files (your puzzle input). Each passport //! is represented as a sequence of `key:value` pairs separated by spaces or //! newlines. Passports are separated by blank lines. //! //! Here is an example batch file containing four passports: //! //! ``` //! ecl:gry pid:860033327 eyr:2020 hcl:#fffffd //! byr:1937 iyr:2017 cid:147 hgt:183cm //! //! iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 //! hcl:#cfa07d byr:1929 //! //! hcl:#ae17e1 iyr:2013 //! eyr:2024 //! ecl:brn pid:760753108 byr:1931 //! hgt:179cm //! //! hcl:#cfa07d eyr:2025 pid:166559648 //! iyr:2011 ecl:brn hgt:59in //! ``` //! //! The first passport is **valid** - all eight fields are present. The second //! passport is **invalid** - it is missing `hgt` (the Height field). //! //! The third passport is interesting; the **only missing field** is `cid`, so //! it looks like data from North Pole Credentials, not a passport at all! //! Surely, nobody would mind if you made the system temporarily ignore missing //! `cid` fields. Treat this "passport" as valid. //! //! The fourth passport is missing two fields, `cid` and `byr`. Missing `cid` is //! fine, but missing any other field is not, so this passport is **invalid**. //! //! According to the above rules, your improved system would report `2` valid //! passports. //! //! Count the number of **valid** passports - those that have all required //! fields. Treat `cid` as optional. //! **In your batch file, how many passports are valid?** //! //! ## --- Part Two --- //! //! The line is moving more quickly now, but you overhear airport security //! talking about how passports with invalid data are getting through. Better //! add some data validation, quick! //! //! You can continue to ignore the `cid` field, but each other field has strict //! rules about what values are valid for automatic validation: //! //! - `byr` (Birth Year) - four digits; at least `1920` and at most `2002`. //! - `iyr` (Issue Year) - four digits; at least `2010` and at most `2020`. //! - `eyr` (Expiration Year) - four digits; at least `2020` and at most `2030`. //! - `hgt` (Height) - a number followed by either `cm` or `in`: //! - If `cm`, the number must be at least `150` and at most `193`. //! - If `in`, the number must be at least `59` and at most `76`. //! - `hcl` (Hair Color) - a `#` followed by exactly six characters `0-9` or `a-f`. //! - `ecl` (Eye Color) - exactly one of: `amb` `blu` `brn` `gry` `grn` `hzl` `oth`. //! - `pid` (Passport ID) - a nine-digit number, including leading zeroes. //! - `cid` (Country ID) - ignored, missing or not. //! //! Your job is to count the passports where all required fields are both //! **present** and **valid** according to the above rules. Here are some //! example values: //! //! ``` //! byr valid: 2002 //! byr invalid: 2003 //! //! hgt valid: 60in //! hgt valid: 190cm //! hgt invalid: 190in //! hgt invalid: 190 //! //! hcl valid: #123abc //! hcl invalid: #123abz //! hcl invalid: 123abc //! //! ecl valid: brn //! ecl invalid: wat //! //! pid valid: 000000001 //! pid invalid: 0123456789 //! ``` //! //! Here are some invalid passports: //! //! ``` //! eyr:1972 cid:100 //! hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 //! //! iyr:2019 //! hcl:#602927 eyr:1967 hgt:170cm //! ecl:grn pid:012533040 byr:1946 //! //! hcl:dab227 iyr:2012 //! ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 //! //! hgt:59cm ecl:zzz //! eyr:2038 hcl:74454a iyr:2023 //! pid:3556412378 byr:2007 //! ``` //! //! Here are some valid passports: //! //! ``` //! pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 //! hcl:#623a2f //! //! eyr:2029 ecl:blu cid:129 byr:1989 //! iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm //! //! hcl:#888785 //! hgt:164cm byr:2001 iyr:2015 cid:88 //! pid:545766238 ecl:hzl //! eyr:2022 //! //! iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 //! ``` //! //! Count the number of **valid** passports - those that have all required //! fields **and valid values**. Continue to treat cid as optional. //! **In your batch file, how many passports are valid?** #[macro_use] extern crate lazy_static; use std::collections::{HashMap, HashSet}; use std::env; use std::fs; use nom::{ branch::alt, bytes::complete::tag, bytes::complete::take_while, character::complete::multispace1, multi::separated_list0, sequence::tuple, IResult, }; lazy_static! { static ref MUST_FIELDS: HashSet<&'static str> = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] .into_iter() .collect(); static ref HAIR_COLORS: HashSet<&'static str> = vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] .into_iter() .collect(); } #[derive(Debug, Eq, PartialEq)] enum HeightUnit { Cm, In, } #[derive(Debug, Eq, PartialEq)] struct Height { hight: usize, unit: HeightUnit, } #[derive(Debug, Eq, PartialEq)] struct Passport { byr: usize, // birth year iyr: usize, // issue year eyr: usize, // expiration year hgt: Height, // height hcl: String, // hair color ecl: String, // eye color pid: String, // passport id cid: Option<usize>, // country id } impl Passport { fn from_hashmap(kvs: &HashMap<&str, &str>) -> Option<Passport> { // `byr` (Birth Year) - four digits; at least `1920` and at most `2002`. let byr = match kvs.get("byr").unwrap().parse::<usize>() { Ok(i @ 1920..=2002) => i, Err(_) => return None, _ => return None, }; // `iyr` (Issue Year) - four digits; at least `2010` and at most `2020`. let iyr = match kvs.get("iyr").unwrap().parse::<usize>() { Ok(i @ 2010..=2020) => i, Err(_) => return None, _ => return None, }; // `eyr` (Expiration Year) - four digits; at least `2020` and at most `2030`. let eyr = match kvs.get("eyr").unwrap().parse::<usize>() { Ok(i @ 2020..=2030) => i, Err(_) => return None, _ => return None, }; // - `hgt` (Height) - a number followed by either `cm` or `in`: // - If `cm`, the number must be at least `150` and at most `193`. // - If `in`, the number must be at least `59` and at most `76`. let hgt_str = kvs.get("hgt").unwrap(); let hgt = if hgt_str.ends_with("cm") { let high = hgt_str.strip_suffix("cm").unwrap().parse::<usize>(); match high { Ok(i @ 150..=193) => Height { hight: i, unit: HeightUnit::Cm, }, _ => return None, } } else if hgt_str.ends_with("in") { let high = hgt_str.strip_suffix("in").unwrap().parse::<usize>(); match high { Ok(i @ 59..=76) => Height { hight: i, unit: HeightUnit::In, }, _ => return None, } } else { return None; }; // `hcl` (Hair Color) - a `#` followed by exactly six characters `0-9` or `a-f`. let hcl_str = kvs.get("hcl").unwrap(); let hcl = if hcl_str.starts_with('#') && hcl_str.len() == 7 && hcl_str[1..].chars().all(|x| x.is_digit(16)) { (*hcl_str).into() } else { return None; }; // `ecl` (Eye Color) - exactly one of: `amb` `blu` `brn` `gry` `grn` `hzl` `oth`. let ecl_str = kvs.get("ecl").unwrap(); let ecl = if HAIR_COLORS.contains(ecl_str) { (*ecl_str).into() } else { return None; }; // `pid` (Passport ID) - a nine-digit number, including leading zeroes. let pid_str = kvs.get("pid").unwrap(); let pid = if (*pid_str).parse::<usize>().is_ok() && (*pid_str).trim().len() == 9 { (*pid_str).into() } else { return None; }; // `cid` (Country ID) - ignored, missing or not. let cid = match kvs.get("cid") { Some(x) => match x.parse::<usize>() { Ok(i) => Some(i), Err(_) => return None, }, None => None, }; Some(Passport { byr, iyr, eyr, hgt, hcl, ecl, pid, cid, }) } } fn is_valid_char(c: char) -> bool { c.is_alphanumeric() || c == '#' } fn kv_parser(input: &str) -> IResult<&str, (&str, &str)> { let keys = alt(( tag("byr"), tag("iyr"), tag("eyr"), tag("hgt"), tag("hcl"), tag("ecl"), tag("pid"), tag("cid"), )); let (input, (k, _, v)) = tuple((keys, tag(":"), take_while(is_valid_char)))(input)?; Ok((input, (k, v))) } fn kvlist_parser(input: &str) -> IResult<&str, Vec<(&str, &str)>> { let (input, kv_group) = separated_list0(multispace1, kv_parser)(input)?; // println!("{:?}", kv_group); Ok((input, kv_group)) } fn parse_input(input: &str) -> Vec<HashMap<&str, &str>> { let group = input.split("\n\n"); group .filter_map(|x| { let (_, kv_list) = kvlist_parser(x).unwrap(); let kv_map = kv_list.into_iter().collect::<HashMap<&str, &str>>(); let keys_set = kv_map.keys().cloned().collect::<HashSet<&str>>(); if MUST_FIELDS.is_subset(&keys_set) { Some(kv_map) } else { None } }) .collect::<Vec<HashMap<&str, &str>>>() } fn main() -> Result<(), &'static str> { let args: Vec<String> = env::args().collect(); if args.len() < 2 { return Err("not enough arguments"); } let filename = &args[1]; println!("Load input file {}.", filename); let input = fs::read_to_string(filename).expect("Something went wrong reading the file"); let valid_kvs = parse_input(&input); println!( "The number of valid passports have all required fields is {}.", valid_kvs.len() ); let passports: Vec<Passport> = valid_kvs .iter() .filter_map(|x| Passport::from_hashmap(x)) .collect(); println!( "The number of passports satisfy all restrictions is {}.", passports.len() ); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_kv_parser() { let (left, (k, v)) = kv_parser("ecl:gry").unwrap(); assert_eq!(left, ""); assert_eq!((k, v), ("ecl", "gry")); let (_, (k, v)) = kv_parser("hcl:#fffffd").unwrap(); assert_eq!((k, v), ("hcl", "#fffffd")); let (left, (k, v)) = kv_parser("pid:860033327~rust").unwrap(); assert_eq!(left, "~rust"); assert_eq!((k, v), ("pid", "860033327")); } #[test] fn test_kvlist_parser() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm"; let (_, kvs) = kvlist_parser(input).unwrap(); assert_eq!( kvs, vec![ ("ecl", "gry"), ("pid", "860033327"), ("eyr", "2020"), ("hcl", "#fffffd"), ("byr", "1937"), ("iyr", "2017"), ("cid", "147"), ("hgt", "183cm"), ], ) } #[test] fn test_parse_input() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in "; let passports_dict = parse_input(input); assert_eq!( passports_dict, vec![ vec![ ("ecl", "gry"), ("pid", "860033327"), ("eyr", "2020"), ("hcl", "#fffffd"), ("byr", "1937"), ("iyr", "2017"), ("cid", "147"), ("hgt", "183cm") ] .into_iter() .collect(), vec![ ("hcl", "#ae17e1"), ("iyr", "2013"), ("eyr", "2024"), ("ecl", "brn"), ("pid", "760753108"), ("byr", "1931"), ("hgt", "179cm") ] .into_iter() .collect(), ] ) } #[test] fn test_passport_valid() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm "; let kvs = parse_input(&input); let passports: Vec<Passport> = kvs .iter()
.filter_map(|x| Passport::from_hashmap(x)) .collect(); assert_eq!( passports, vec![ Passport { ecl: "gry".into(), pid: "860033327".into(), eyr: 2020, hcl: "#fffffd".into(), byr: 1937, iyr: 2017, cid: Some(147), hgt: Height { hight: 183, unit: HeightUnit::Cm, }, }, Passport { hcl: "#ae17e1".into(), iyr: 2013, eyr: 2024, ecl: "brn".into(), pid: "760753108".into(), byr: 1931, hgt: Height { hight: 179, unit: HeightUnit::Cm, }, cid: None, }, ] ); } #[test] fn test_passport_invalid() { let input = "eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007"; let kvs = parse_input(&input); let passports: Vec<Passport> = kvs .iter() .filter_map(|x| Passport::from_hashmap(x)) .collect(); assert_eq!(passports, vec![]); } }
random_line_split
day04.rs
//! # --- Day 4: Passport Processing --- //! //! You arrive at the airport only to realize that you grabbed your North Pole //! Credentials instead of your passport. While these documents are extremely //! similar, North Pole Credentials aren't issued by a country and therefore //! aren't actually valid documentation for travel in most of the world. //! //! It seems like you're not the only one having problems, though; a very long //! line has formed for the automatic passport scanners, and the delay could //! upset your travel itinerary. //! //! Due to some questionable network security, you realize you might be able to //! solve both of these problems at the same time. //! //! The automatic passport scanners are slow because they're having trouble //! **detecting which passports have all required fields**. The expected fields //! are as follows: //! //! - `byr` (Birth Year) //! - `iyr` (Issue Year) //! - `eyr` (Expiration Year) //! - `hgt` (Height) //! - `hcl` (Hair Color) //! - `ecl` (Eye Color) //! - `pid` (Passport ID) //! - `cid` (Country ID) //! //! Passport data is validated in batch files (your puzzle input). Each passport //! is represented as a sequence of `key:value` pairs separated by spaces or //! newlines. Passports are separated by blank lines. //! //! Here is an example batch file containing four passports: //! //! ``` //! ecl:gry pid:860033327 eyr:2020 hcl:#fffffd //! byr:1937 iyr:2017 cid:147 hgt:183cm //! //! iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 //! hcl:#cfa07d byr:1929 //! //! hcl:#ae17e1 iyr:2013 //! eyr:2024 //! ecl:brn pid:760753108 byr:1931 //! hgt:179cm //! //! hcl:#cfa07d eyr:2025 pid:166559648 //! iyr:2011 ecl:brn hgt:59in //! ``` //! //! The first passport is **valid** - all eight fields are present. The second //! passport is **invalid** - it is missing `hgt` (the Height field). //! //! The third passport is interesting; the **only missing field** is `cid`, so //! it looks like data from North Pole Credentials, not a passport at all! //! Surely, nobody would mind if you made the system temporarily ignore missing //! `cid` fields. Treat this "passport" as valid. //! //! The fourth passport is missing two fields, `cid` and `byr`. Missing `cid` is //! fine, but missing any other field is not, so this passport is **invalid**. //! //! According to the above rules, your improved system would report `2` valid //! passports. //! //! Count the number of **valid** passports - those that have all required //! fields. Treat `cid` as optional. //! **In your batch file, how many passports are valid?** //! //! ## --- Part Two --- //! //! The line is moving more quickly now, but you overhear airport security //! talking about how passports with invalid data are getting through. Better //! add some data validation, quick! //! //! You can continue to ignore the `cid` field, but each other field has strict //! rules about what values are valid for automatic validation: //! //! - `byr` (Birth Year) - four digits; at least `1920` and at most `2002`. //! - `iyr` (Issue Year) - four digits; at least `2010` and at most `2020`. //! - `eyr` (Expiration Year) - four digits; at least `2020` and at most `2030`. //! - `hgt` (Height) - a number followed by either `cm` or `in`: //! - If `cm`, the number must be at least `150` and at most `193`. //! - If `in`, the number must be at least `59` and at most `76`. //! - `hcl` (Hair Color) - a `#` followed by exactly six characters `0-9` or `a-f`. //! - `ecl` (Eye Color) - exactly one of: `amb` `blu` `brn` `gry` `grn` `hzl` `oth`. //! - `pid` (Passport ID) - a nine-digit number, including leading zeroes. //! - `cid` (Country ID) - ignored, missing or not. //! //! Your job is to count the passports where all required fields are both //! **present** and **valid** according to the above rules. Here are some //! example values: //! //! ``` //! byr valid: 2002 //! byr invalid: 2003 //! //! hgt valid: 60in //! hgt valid: 190cm //! hgt invalid: 190in //! hgt invalid: 190 //! //! hcl valid: #123abc //! hcl invalid: #123abz //! hcl invalid: 123abc //! //! ecl valid: brn //! ecl invalid: wat //! //! pid valid: 000000001 //! pid invalid: 0123456789 //! ``` //! //! Here are some invalid passports: //! //! ``` //! eyr:1972 cid:100 //! hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 //! //! iyr:2019 //! hcl:#602927 eyr:1967 hgt:170cm //! ecl:grn pid:012533040 byr:1946 //! //! hcl:dab227 iyr:2012 //! ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 //! //! hgt:59cm ecl:zzz //! eyr:2038 hcl:74454a iyr:2023 //! pid:3556412378 byr:2007 //! ``` //! //! Here are some valid passports: //! //! ``` //! pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 //! hcl:#623a2f //! //! eyr:2029 ecl:blu cid:129 byr:1989 //! iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm //! //! hcl:#888785 //! hgt:164cm byr:2001 iyr:2015 cid:88 //! pid:545766238 ecl:hzl //! eyr:2022 //! //! iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 //! ``` //! //! Count the number of **valid** passports - those that have all required //! fields **and valid values**. Continue to treat cid as optional. //! **In your batch file, how many passports are valid?** #[macro_use] extern crate lazy_static; use std::collections::{HashMap, HashSet}; use std::env; use std::fs; use nom::{ branch::alt, bytes::complete::tag, bytes::complete::take_while, character::complete::multispace1, multi::separated_list0, sequence::tuple, IResult, }; lazy_static! { static ref MUST_FIELDS: HashSet<&'static str> = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] .into_iter() .collect(); static ref HAIR_COLORS: HashSet<&'static str> = vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"] .into_iter() .collect(); } #[derive(Debug, Eq, PartialEq)] enum HeightUnit { Cm, In, } #[derive(Debug, Eq, PartialEq)] struct Height { hight: usize, unit: HeightUnit, } #[derive(Debug, Eq, PartialEq)] struct Passport { byr: usize, // birth year iyr: usize, // issue year eyr: usize, // expiration year hgt: Height, // height hcl: String, // hair color ecl: String, // eye color pid: String, // passport id cid: Option<usize>, // country id } impl Passport { fn from_hashmap(kvs: &HashMap<&str, &str>) -> Option<Passport> { // `byr` (Birth Year) - four digits; at least `1920` and at most `2002`. let byr = match kvs.get("byr").unwrap().parse::<usize>() { Ok(i @ 1920..=2002) => i, Err(_) => return None, _ => return None, }; // `iyr` (Issue Year) - four digits; at least `2010` and at most `2020`. let iyr = match kvs.get("iyr").unwrap().parse::<usize>() { Ok(i @ 2010..=2020) => i, Err(_) => return None, _ => return None, }; // `eyr` (Expiration Year) - four digits; at least `2020` and at most `2030`. let eyr = match kvs.get("eyr").unwrap().parse::<usize>() { Ok(i @ 2020..=2030) => i, Err(_) => return None, _ => return None, }; // - `hgt` (Height) - a number followed by either `cm` or `in`: // - If `cm`, the number must be at least `150` and at most `193`. // - If `in`, the number must be at least `59` and at most `76`. let hgt_str = kvs.get("hgt").unwrap(); let hgt = if hgt_str.ends_with("cm") { let high = hgt_str.strip_suffix("cm").unwrap().parse::<usize>(); match high { Ok(i @ 150..=193) => Height { hight: i, unit: HeightUnit::Cm, }, _ => return None, } } else if hgt_str.ends_with("in") { let high = hgt_str.strip_suffix("in").unwrap().parse::<usize>(); match high { Ok(i @ 59..=76) => Height { hight: i, unit: HeightUnit::In, }, _ => return None, } } else { return None; }; // `hcl` (Hair Color) - a `#` followed by exactly six characters `0-9` or `a-f`. let hcl_str = kvs.get("hcl").unwrap(); let hcl = if hcl_str.starts_with('#') && hcl_str.len() == 7 && hcl_str[1..].chars().all(|x| x.is_digit(16)) { (*hcl_str).into() } else { return None; }; // `ecl` (Eye Color) - exactly one of: `amb` `blu` `brn` `gry` `grn` `hzl` `oth`. let ecl_str = kvs.get("ecl").unwrap(); let ecl = if HAIR_COLORS.contains(ecl_str) { (*ecl_str).into() } else { return None; }; // `pid` (Passport ID) - a nine-digit number, including leading zeroes. let pid_str = kvs.get("pid").unwrap(); let pid = if (*pid_str).parse::<usize>().is_ok() && (*pid_str).trim().len() == 9 { (*pid_str).into() } else { return None; }; // `cid` (Country ID) - ignored, missing or not. let cid = match kvs.get("cid") { Some(x) => match x.parse::<usize>() { Ok(i) => Some(i), Err(_) => return None, }, None => None, }; Some(Passport { byr, iyr, eyr, hgt, hcl, ecl, pid, cid, }) } } fn is_valid_char(c: char) -> bool { c.is_alphanumeric() || c == '#' } fn kv_parser(input: &str) -> IResult<&str, (&str, &str)> { let keys = alt(( tag("byr"), tag("iyr"), tag("eyr"), tag("hgt"), tag("hcl"), tag("ecl"), tag("pid"), tag("cid"), )); let (input, (k, _, v)) = tuple((keys, tag(":"), take_while(is_valid_char)))(input)?; Ok((input, (k, v))) } fn kvlist_parser(input: &str) -> IResult<&str, Vec<(&str, &str)>> { let (input, kv_group) = separated_list0(multispace1, kv_parser)(input)?; // println!("{:?}", kv_group); Ok((input, kv_group)) } fn parse_input(input: &str) -> Vec<HashMap<&str, &str>> { let group = input.split("\n\n"); group .filter_map(|x| { let (_, kv_list) = kvlist_parser(x).unwrap(); let kv_map = kv_list.into_iter().collect::<HashMap<&str, &str>>(); let keys_set = kv_map.keys().cloned().collect::<HashSet<&str>>(); if MUST_FIELDS.is_subset(&keys_set) { Some(kv_map) } else { None } }) .collect::<Vec<HashMap<&str, &str>>>() } fn main() -> Result<(), &'static str> { let args: Vec<String> = env::args().collect(); if args.len() < 2 { return Err("not enough arguments"); } let filename = &args[1]; println!("Load input file {}.", filename); let input = fs::read_to_string(filename).expect("Something went wrong reading the file"); let valid_kvs = parse_input(&input); println!( "The number of valid passports have all required fields is {}.", valid_kvs.len() ); let passports: Vec<Passport> = valid_kvs .iter() .filter_map(|x| Passport::from_hashmap(x)) .collect(); println!( "The number of passports satisfy all restrictions is {}.", passports.len() ); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_kv_parser() { let (left, (k, v)) = kv_parser("ecl:gry").unwrap(); assert_eq!(left, ""); assert_eq!((k, v), ("ecl", "gry")); let (_, (k, v)) = kv_parser("hcl:#fffffd").unwrap(); assert_eq!((k, v), ("hcl", "#fffffd")); let (left, (k, v)) = kv_parser("pid:860033327~rust").unwrap(); assert_eq!(left, "~rust"); assert_eq!((k, v), ("pid", "860033327")); } #[test] fn
() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm"; let (_, kvs) = kvlist_parser(input).unwrap(); assert_eq!( kvs, vec![ ("ecl", "gry"), ("pid", "860033327"), ("eyr", "2020"), ("hcl", "#fffffd"), ("byr", "1937"), ("iyr", "2017"), ("cid", "147"), ("hgt", "183cm"), ], ) } #[test] fn test_parse_input() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in "; let passports_dict = parse_input(input); assert_eq!( passports_dict, vec![ vec![ ("ecl", "gry"), ("pid", "860033327"), ("eyr", "2020"), ("hcl", "#fffffd"), ("byr", "1937"), ("iyr", "2017"), ("cid", "147"), ("hgt", "183cm") ] .into_iter() .collect(), vec![ ("hcl", "#ae17e1"), ("iyr", "2013"), ("eyr", "2024"), ("ecl", "brn"), ("pid", "760753108"), ("byr", "1931"), ("hgt", "179cm") ] .into_iter() .collect(), ] ) } #[test] fn test_passport_valid() { let input = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm "; let kvs = parse_input(&input); let passports: Vec<Passport> = kvs .iter() .filter_map(|x| Passport::from_hashmap(x)) .collect(); assert_eq!( passports, vec![ Passport { ecl: "gry".into(), pid: "860033327".into(), eyr: 2020, hcl: "#fffffd".into(), byr: 1937, iyr: 2017, cid: Some(147), hgt: Height { hight: 183, unit: HeightUnit::Cm, }, }, Passport { hcl: "#ae17e1".into(), iyr: 2013, eyr: 2024, ecl: "brn".into(), pid: "760753108".into(), byr: 1931, hgt: Height { hight: 179, unit: HeightUnit::Cm, }, cid: None, }, ] ); } #[test] fn test_passport_invalid() { let input = "eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007"; let kvs = parse_input(&input); let passports: Vec<Passport> = kvs .iter() .filter_map(|x| Passport::from_hashmap(x)) .collect(); assert_eq!(passports, vec![]); } }
test_kvlist_parser
identifier_name
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut pstm_int) -> int32; #[no_mangle] fn s_pstm_sub(a: *mut pstm_int, b: *mut pstm_int, c: *mut pstm_int) -> int32; } use crate::librb::size_t; /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* Interface glue between bbox code and minimally tweaked matrixssl * code. All C files (matrixssl and bbox (ones which need TLS)) * include this file, and guaranteed to see a consistent API, * defines, types, etc. */ /* Config tweaks */ /* pstm: multiprecision numbers */ //#if defined(__GNUC__) && defined(__x86_64__) // /* PSTM_X86_64 works correctly, but +782 bytes. */ // /* Looks like most of the growth is because of PSTM_64BIT. */ //# define PSTM_64BIT //# define PSTM_X86_64 //#endif //#if SOME_COND #define PSTM_MIPS, #define PSTM_32BIT //#if SOME_COND #define PSTM_ARM, #define PSTM_32BIT /* Failure due to bad function param */ /* Failure as a result of system call error */ /* Failure to allocate requested memory */ /* Failure on sanity/limit tests */ pub type uint64 = u64; pub type uint32 = u32; pub type int32 = i32; pub type pstm_digit = uint32; pub type pstm_word = uint64; #[derive(Copy, Clone)] #[repr(C)] pub struct pstm_int { pub used: libc::c_int, pub alloc: libc::c_int, pub sign: libc::c_int, pub dp: *mut pstm_digit, } /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm.h * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * multiple-precision integer library. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved * * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ /* Define this here to avoid including circular limits.h on some platforms */ /* *****************************************************************************/ /* If native 64 bit integers are not supported, we do not support 32x32->64 in hardware, so we must set the 16 bit flag to produce 16x16->32 products. */ /*! HAVE_NATIVE_INT64 */ /* *****************************************************************************/ /* Some default configurations. pstm_word should be the largest value the processor can hold as the product of a multiplication. Most platforms support a 32x32->64 MAC instruction, so 64bits is the default pstm_word size. pstm_digit should be half the size of pstm_word */ /* This is the default case, 32-bit digits, 64-bit word products */ /* digit and word size */ /* *****************************************************************************/ /* equalities */ /* less than */ /* equal to */ /* greater than */ /* positive integer */ /* negative */ /* *****************************************************************************/ /* Various build options */ /* default (64) digits of allocation */ //bbox: was int16 //bbox psPool_t *pool; /* *****************************************************************************/ /* Operations on large integers */ //made static:extern void pstm_set(pstm_int *a, pstm_digit b); //made static:extern void pstm_zero(pstm_int * a); //bbox: pool unused //made static:extern int32 pstm_init(psPool_t *pool, pstm_int * a); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, //made static: int toSqr); //bbox: was int16 toSqr //made static:extern int pstm_count_bits (pstm_int * a) FAST_FUNC; //bbox: was returning int16 //bbox: pool unused //made static:extern void pstm_exch(pstm_int * a, pstm_int * b); //bbox: was int16 size //made static:extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x //made static:extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b //bbox: pool unused //made static:extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c, //made static: pstm_int *d); //bbox: pool unused //made static:extern int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c, //made static: pstm_int *d); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho); //bbox: pool unused /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm_montgomery_reduce.c * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * Multiprecision Montgomery Reduction. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved * * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ //bbox //#include "../cryptoApi.h" /* *****************************************************************************/ /* ISO C code */ /* *****************************************************************************/ /* computes x/R == x (mod N) via Montgomery Reduction */ #[no_mangle] pub unsafe extern "C" fn
( mut a: *mut pstm_int, mut m: *mut pstm_int, mut mp: pstm_digit, mut paD: *mut pstm_digit, mut paDlen: uint32, ) -> int32 { let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16 let mut _c: *mut pstm_digit = 0 as *mut pstm_digit; let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit; let mut mu: pstm_digit = 0; let mut oldused: int32 = 0; let mut x: int32 = 0; let mut y: int32 = 0; let mut pa: libc::c_int = 0; pa = (*m).used; if pa > (*a).alloc { /* Sanity test for bad numbers. This will confirm no buffer overruns */ return -9i32; } if!paD.is_null() && paDlen >= (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { c = paD; memset(c as *mut libc::c_void, 0i32, paDlen as libc::c_ulong); } else { c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit //bbox } /* copy the input */ oldused = (*a).used; x = 0i32; while x < oldused { *c.offset(x as isize) = *(*a).dp.offset(x as isize); x += 1 } x = 0i32; while x < pa { let mut cy: pstm_digit = 0i32 as pstm_digit; /* get Mu for this round */ mu = (*c.offset(x as isize)).wrapping_mul(mp); _c = c.offset(x as isize); tmpm = (*m).dp; y = 0i32; /* PSTM_X86_64 */ while y < pa { let mut t: pstm_word = 0; let fresh0 = tmpm; tmpm = tmpm.offset(1); t = (*_c.offset(0) as pstm_word) .wrapping_add(cy as pstm_word) .wrapping_add((mu as pstm_word).wrapping_mul(*fresh0 as pstm_word)); *_c.offset(0) = t as pstm_digit; cy = (t >> 32i32) as pstm_digit; _c = _c.offset(1); y += 1 } while cy!= 0 { let ref mut fresh1 = *_c.offset(0); *fresh1 = (*fresh1 as libc::c_uint).wrapping_add(cy) as pstm_digit as pstm_digit; let mut t_0: pstm_digit = *fresh1; cy = (t_0 < cy) as libc::c_int as pstm_digit; _c = _c.offset(1) } x += 1 } /* now copy out */ _c = c.offset(pa as isize); tmpm = (*a).dp; x = 0i32; while x < pa + 1i32 { let fresh2 = _c; _c = _c.offset(1); let fresh3 = tmpm; tmpm = tmpm.offset(1); *fresh3 = *fresh2; x += 1 } while x < oldused { let fresh4 = tmpm; tmpm = tmpm.offset(1); *fresh4 = 0i32 as pstm_digit; x += 1 } (*a).used = pa + 1i32; pstm_clamp(a); /* reuse x as return code */ x = 0i32; /* if A >= m then A = A - m */ if pstm_cmp_mag(a, m)!= -1i32 { if s_pstm_sub(a, m, a)!= 0i32 { x = -8i32 } } if paDlen < (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { free(c as *mut libc::c_void); } return x; } /* *****************************************************************************/ /*!DISABLE_PSTM */
pstm_montgomery_reduce
identifier_name
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut pstm_int) -> int32; #[no_mangle] fn s_pstm_sub(a: *mut pstm_int, b: *mut pstm_int, c: *mut pstm_int) -> int32; } use crate::librb::size_t; /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* Interface glue between bbox code and minimally tweaked matrixssl * code. All C files (matrixssl and bbox (ones which need TLS)) * include this file, and guaranteed to see a consistent API, * defines, types, etc. */ /* Config tweaks */ /* pstm: multiprecision numbers */ //#if defined(__GNUC__) && defined(__x86_64__) // /* PSTM_X86_64 works correctly, but +782 bytes. */ // /* Looks like most of the growth is because of PSTM_64BIT. */ //# define PSTM_64BIT //# define PSTM_X86_64 //#endif //#if SOME_COND #define PSTM_MIPS, #define PSTM_32BIT //#if SOME_COND #define PSTM_ARM, #define PSTM_32BIT /* Failure due to bad function param */ /* Failure as a result of system call error */ /* Failure to allocate requested memory */ /* Failure on sanity/limit tests */ pub type uint64 = u64; pub type uint32 = u32; pub type int32 = i32; pub type pstm_digit = uint32; pub type pstm_word = uint64; #[derive(Copy, Clone)] #[repr(C)] pub struct pstm_int { pub used: libc::c_int, pub alloc: libc::c_int, pub sign: libc::c_int, pub dp: *mut pstm_digit, } /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm.h * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * multiple-precision integer library. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved * * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ /* Define this here to avoid including circular limits.h on some platforms */ /* *****************************************************************************/ /* If native 64 bit integers are not supported, we do not support 32x32->64 in hardware, so we must set the 16 bit flag to produce 16x16->32 products. */ /*! HAVE_NATIVE_INT64 */ /* *****************************************************************************/ /* Some default configurations. pstm_word should be the largest value the processor can hold as the product of a multiplication. Most platforms support a 32x32->64 MAC instruction, so 64bits is the default pstm_word size. pstm_digit should be half the size of pstm_word */ /* This is the default case, 32-bit digits, 64-bit word products */ /* digit and word size */ /* *****************************************************************************/ /* equalities */ /* less than */ /* equal to */ /* greater than */ /* positive integer */ /* negative */ /* *****************************************************************************/ /* Various build options */ /* default (64) digits of allocation */ //bbox: was int16 //bbox psPool_t *pool; /* *****************************************************************************/ /* Operations on large integers */ //made static:extern void pstm_set(pstm_int *a, pstm_digit b); //made static:extern void pstm_zero(pstm_int * a); //bbox: pool unused //made static:extern int32 pstm_init(psPool_t *pool, pstm_int * a); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, //made static: int toSqr); //bbox: was int16 toSqr //made static:extern int pstm_count_bits (pstm_int * a) FAST_FUNC; //bbox: was returning int16 //bbox: pool unused //made static:extern void pstm_exch(pstm_int * a, pstm_int * b); //bbox: was int16 size //made static:extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x //made static:extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b //bbox: pool unused //made static:extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c, //made static: pstm_int *d); //bbox: pool unused //made static:extern int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c, //made static: pstm_int *d); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho); //bbox: pool unused /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm_montgomery_reduce.c * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * Multiprecision Montgomery Reduction. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved * * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ //bbox //#include "../cryptoApi.h" /* *****************************************************************************/ /* ISO C code */ /* *****************************************************************************/ /* computes x/R == x (mod N) via Montgomery Reduction */ #[no_mangle] pub unsafe extern "C" fn pstm_montgomery_reduce( mut a: *mut pstm_int, mut m: *mut pstm_int, mut mp: pstm_digit, mut paD: *mut pstm_digit, mut paDlen: uint32, ) -> int32 { let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16 let mut _c: *mut pstm_digit = 0 as *mut pstm_digit; let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit; let mut mu: pstm_digit = 0; let mut oldused: int32 = 0; let mut x: int32 = 0; let mut y: int32 = 0; let mut pa: libc::c_int = 0; pa = (*m).used; if pa > (*a).alloc { /* Sanity test for bad numbers. This will confirm no buffer overruns */ return -9i32; } if!paD.is_null() && paDlen >= (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { c = paD; memset(c as *mut libc::c_void, 0i32, paDlen as libc::c_ulong); } else
/* copy the input */ oldused = (*a).used; x = 0i32; while x < oldused { *c.offset(x as isize) = *(*a).dp.offset(x as isize); x += 1 } x = 0i32; while x < pa { let mut cy: pstm_digit = 0i32 as pstm_digit; /* get Mu for this round */ mu = (*c.offset(x as isize)).wrapping_mul(mp); _c = c.offset(x as isize); tmpm = (*m).dp; y = 0i32; /* PSTM_X86_64 */ while y < pa { let mut t: pstm_word = 0; let fresh0 = tmpm; tmpm = tmpm.offset(1); t = (*_c.offset(0) as pstm_word) .wrapping_add(cy as pstm_word) .wrapping_add((mu as pstm_word).wrapping_mul(*fresh0 as pstm_word)); *_c.offset(0) = t as pstm_digit; cy = (t >> 32i32) as pstm_digit; _c = _c.offset(1); y += 1 } while cy!= 0 { let ref mut fresh1 = *_c.offset(0); *fresh1 = (*fresh1 as libc::c_uint).wrapping_add(cy) as pstm_digit as pstm_digit; let mut t_0: pstm_digit = *fresh1; cy = (t_0 < cy) as libc::c_int as pstm_digit; _c = _c.offset(1) } x += 1 } /* now copy out */ _c = c.offset(pa as isize); tmpm = (*a).dp; x = 0i32; while x < pa + 1i32 { let fresh2 = _c; _c = _c.offset(1); let fresh3 = tmpm; tmpm = tmpm.offset(1); *fresh3 = *fresh2; x += 1 } while x < oldused { let fresh4 = tmpm; tmpm = tmpm.offset(1); *fresh4 = 0i32 as pstm_digit; x += 1 } (*a).used = pa + 1i32; pstm_clamp(a); /* reuse x as return code */ x = 0i32; /* if A >= m then A = A - m */ if pstm_cmp_mag(a, m)!= -1i32 { if s_pstm_sub(a, m, a)!= 0i32 { x = -8i32 } } if paDlen < (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { free(c as *mut libc::c_void); } return x; } /* *****************************************************************************/ /*!DISABLE_PSTM */
{ c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit //bbox }
conditional_block
tls_pstm_montgomery_reduce.rs
use libc; use libc::free; extern "C" { #[no_mangle] fn memset(_: *mut libc::c_void, _: libc::c_int, _: libc::c_ulong) -> *mut libc::c_void; #[no_mangle] fn xzalloc(size: size_t) -> *mut libc::c_void; #[no_mangle] fn pstm_clamp(a: *mut pstm_int); #[no_mangle] fn pstm_cmp_mag(a: *mut pstm_int, b: *mut pstm_int) -> int32; #[no_mangle] fn s_pstm_sub(a: *mut pstm_int, b: *mut pstm_int, c: *mut pstm_int) -> int32; } use crate::librb::size_t; /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* Interface glue between bbox code and minimally tweaked matrixssl * code. All C files (matrixssl and bbox (ones which need TLS)) * include this file, and guaranteed to see a consistent API, * defines, types, etc. */ /* Config tweaks */ /* pstm: multiprecision numbers */ //#if defined(__GNUC__) && defined(__x86_64__) // /* PSTM_X86_64 works correctly, but +782 bytes. */ // /* Looks like most of the growth is because of PSTM_64BIT. */ //# define PSTM_64BIT //# define PSTM_X86_64 //#endif //#if SOME_COND #define PSTM_MIPS, #define PSTM_32BIT //#if SOME_COND #define PSTM_ARM, #define PSTM_32BIT /* Failure due to bad function param */ /* Failure as a result of system call error */ /* Failure to allocate requested memory */ /* Failure on sanity/limit tests */ pub type uint64 = u64; pub type uint32 = u32; pub type int32 = i32; pub type pstm_digit = uint32; pub type pstm_word = uint64; #[derive(Copy, Clone)] #[repr(C)] pub struct pstm_int { pub used: libc::c_int, pub alloc: libc::c_int, pub sign: libc::c_int, pub dp: *mut pstm_digit, } /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm.h * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * multiple-precision integer library. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved
* the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ /* Define this here to avoid including circular limits.h on some platforms */ /* *****************************************************************************/ /* If native 64 bit integers are not supported, we do not support 32x32->64 in hardware, so we must set the 16 bit flag to produce 16x16->32 products. */ /*! HAVE_NATIVE_INT64 */ /* *****************************************************************************/ /* Some default configurations. pstm_word should be the largest value the processor can hold as the product of a multiplication. Most platforms support a 32x32->64 MAC instruction, so 64bits is the default pstm_word size. pstm_digit should be half the size of pstm_word */ /* This is the default case, 32-bit digits, 64-bit word products */ /* digit and word size */ /* *****************************************************************************/ /* equalities */ /* less than */ /* equal to */ /* greater than */ /* positive integer */ /* negative */ /* *****************************************************************************/ /* Various build options */ /* default (64) digits of allocation */ //bbox: was int16 //bbox psPool_t *pool; /* *****************************************************************************/ /* Operations on large integers */ //made static:extern void pstm_set(pstm_int *a, pstm_digit b); //made static:extern void pstm_zero(pstm_int * a); //bbox: pool unused //made static:extern int32 pstm_init(psPool_t *pool, pstm_int * a); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_init_copy(psPool_t *pool, pstm_int * a, pstm_int * b, //made static: int toSqr); //bbox: was int16 toSqr //made static:extern int pstm_count_bits (pstm_int * a) FAST_FUNC; //bbox: was returning int16 //bbox: pool unused //made static:extern void pstm_exch(pstm_int * a, pstm_int * b); //bbox: was int16 size //made static:extern void pstm_rshd(pstm_int *a, int x); //bbox: was int16 x //made static:extern int32 pstm_lshd(pstm_int * a, int b); //bbox: was int16 b //bbox: pool unused //made static:extern int32 pstm_div(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c, //made static: pstm_int *d); //bbox: pool unused //made static:extern int32 pstm_div_2d(psPool_t *pool, pstm_int *a, int b, pstm_int *c, //made static: pstm_int *d); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_mod(psPool_t *pool, pstm_int *a, pstm_int *b, pstm_int *c); //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_2expt(pstm_int *a, int b); //bbox: was int16 b //bbox: pool unused //bbox: pool unused //made static:extern int32 pstm_montgomery_setup(pstm_int *a, pstm_digit *rho); //bbox: pool unused /* * Copyright (C) 2017 Denys Vlasenko * * Licensed under GPLv2, see file LICENSE in this source tree. */ /* The file is taken almost verbatim from matrixssl-3-7-2b-open/crypto/math/. * Changes are flagged with //bbox */ /* * * @file pstm_montgomery_reduce.c * @version 33ef80f (HEAD, tag: MATRIXSSL-3-7-2-OPEN, tag: MATRIXSSL-3-7-2-COMM, origin/master, origin/HEAD, master) * * Multiprecision Montgomery Reduction. */ /* * Copyright (c) 2013-2015 INSIDE Secure Corporation * Copyright (c) PeerSec Networks, 2002-2011 * All Rights Reserved * * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This General Public License does NOT permit incorporating this software * into proprietary programs. If you are unable to comply with the GPL, a * commercial license for this software may be purchased from INSIDE at * http://www.insidesecure.com/eng/Company/Locations * * This program is distributed in WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * http://www.gnu.org/copyleft/gpl.html */ /* *****************************************************************************/ //bbox //#include "../cryptoApi.h" /* *****************************************************************************/ /* ISO C code */ /* *****************************************************************************/ /* computes x/R == x (mod N) via Montgomery Reduction */ #[no_mangle] pub unsafe extern "C" fn pstm_montgomery_reduce( mut a: *mut pstm_int, mut m: *mut pstm_int, mut mp: pstm_digit, mut paD: *mut pstm_digit, mut paDlen: uint32, ) -> int32 { let mut c: *mut pstm_digit = 0 as *mut pstm_digit; //bbox: was int16 let mut _c: *mut pstm_digit = 0 as *mut pstm_digit; let mut tmpm: *mut pstm_digit = 0 as *mut pstm_digit; let mut mu: pstm_digit = 0; let mut oldused: int32 = 0; let mut x: int32 = 0; let mut y: int32 = 0; let mut pa: libc::c_int = 0; pa = (*m).used; if pa > (*a).alloc { /* Sanity test for bad numbers. This will confirm no buffer overruns */ return -9i32; } if!paD.is_null() && paDlen >= (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { c = paD; memset(c as *mut libc::c_void, 0i32, paDlen as libc::c_ulong); } else { c = xzalloc((2i32 * pa + 1i32) as size_t) as *mut pstm_digit //bbox } /* copy the input */ oldused = (*a).used; x = 0i32; while x < oldused { *c.offset(x as isize) = *(*a).dp.offset(x as isize); x += 1 } x = 0i32; while x < pa { let mut cy: pstm_digit = 0i32 as pstm_digit; /* get Mu for this round */ mu = (*c.offset(x as isize)).wrapping_mul(mp); _c = c.offset(x as isize); tmpm = (*m).dp; y = 0i32; /* PSTM_X86_64 */ while y < pa { let mut t: pstm_word = 0; let fresh0 = tmpm; tmpm = tmpm.offset(1); t = (*_c.offset(0) as pstm_word) .wrapping_add(cy as pstm_word) .wrapping_add((mu as pstm_word).wrapping_mul(*fresh0 as pstm_word)); *_c.offset(0) = t as pstm_digit; cy = (t >> 32i32) as pstm_digit; _c = _c.offset(1); y += 1 } while cy!= 0 { let ref mut fresh1 = *_c.offset(0); *fresh1 = (*fresh1 as libc::c_uint).wrapping_add(cy) as pstm_digit as pstm_digit; let mut t_0: pstm_digit = *fresh1; cy = (t_0 < cy) as libc::c_int as pstm_digit; _c = _c.offset(1) } x += 1 } /* now copy out */ _c = c.offset(pa as isize); tmpm = (*a).dp; x = 0i32; while x < pa + 1i32 { let fresh2 = _c; _c = _c.offset(1); let fresh3 = tmpm; tmpm = tmpm.offset(1); *fresh3 = *fresh2; x += 1 } while x < oldused { let fresh4 = tmpm; tmpm = tmpm.offset(1); *fresh4 = 0i32 as pstm_digit; x += 1 } (*a).used = pa + 1i32; pstm_clamp(a); /* reuse x as return code */ x = 0i32; /* if A >= m then A = A - m */ if pstm_cmp_mag(a, m)!= -1i32 { if s_pstm_sub(a, m, a)!= 0i32 { x = -8i32 } } if paDlen < (2i32 as uint32) .wrapping_mul(pa as libc::c_uint) .wrapping_add(1i32 as libc::c_uint) { free(c as *mut libc::c_void); } return x; } /* *****************************************************************************/ /*!DISABLE_PSTM */
* * The latest version of this code is available at http://www.matrixssl.org * * This software is open source; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by
random_line_split
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] enum Command { /// Dump the firmware version and Config Dump(Dump), /// Configure the button mapping Button(Buttons), /// Configure DPI profiles Dpi(Dpi), /// Configure macros Macro(Macro), /// Configure the RGB effect // This is weird due to https://github.com/clap-rs/clap/issues/2005 Rgb { #[clap(subcommand)] rgbcmd: Rgb, }, } #[derive(Clap)] struct Dump {} #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The format of a mapping is button:action-type[:action-params...] where button is a number from 1 to 6 and action-type:action-params] is one of the following: - disable - mouse:button (button is one of 'left', 'right','middle', 'back', 'forward') - scroll:amount (amount can also be 'up' and 'down', corresponding to 1 and -1) - repeat:button:count[:interval=50] (button is same as'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the default configuration is used. The default configuration can be represented as: 1:mouse:left 2:mouse:right 3:mouse:middle 4:mouse:back 5:mouse:forward 6:dpi:loop")] struct Buttons { mappings: Vec<SingleButton>, } struct SingleButton { which: usize, action: ButtonAction, } impl FromStr for SingleButton { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (btn, act) = s .split_once(':') .context("Format: button:action-type[:action-params]")?; let which = usize::from_str(btn)?; let action = ButtonAction::from_str(act)?; Ok(Self { which, action }) } } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The mouse has support for 8 dpi profiles, of which each has a configured dpi value and a color (which is displayed on the LED on the bottom of the mouse. For example, to change the color of dpi profile number 3, you could use gloryctl dpi -c 00ffff 3 At this point, it is not possible to enable or disable profiles.")] // TODO struct Dpi { #[clap(possible_values = &["1", "2", "3", "4", "5", "6", "7", "8"])] which: usize, #[clap(short, long)] color: Option<Color>, #[clap(short, long)] dpi: Option<u16>, // TODO independent X and Y } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: This subcommand can be used to program macros. The first argument is the bank number. Following is a list of events. Each event has a format of state:type:key:duration. - state is either 'up' or 'down' - type is one of 'keyboard','modifier','mouse' - key takes on values depending on type, similar to button mappings - duration is in milliseconds, how long to pause before continuing")] struct Macro { bank: u8, events: Vec<Event>, } #[derive(Clap)] enum Rgb { /// Lighting disabled Off, /// Rotating rainbow (default for new mice) Glorious { #[clap(arg_enum, long, short)] direction: Option<Direction>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color Single { #[clap(long, short)] color: Option<Color>, #[clap(arg_enum, long, short)] brightness: Option<Brightness>, }, /// Slowly cycles through the given list of colors Breathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, //#[clap(long, short, max_values = 7)] // we are not using max_values here, because it // leads to confusing behaviour when more values are passed #[clap(long, short)] colors: Vec<Color>, }, /// Tail { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Cycle through colors seamlessly SeamlessBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Constant color for each of the six LEDs ConstantRgb { #[clap(long, short, number_of_values = 6)] colors: Vec<Color>, }, /// Switching between two configured colors Rave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short, number_of_values = 2)] colors: Vec<Color>, }, /// Randomly changing colors Random { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, Wave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color breathing SingleBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short)] color: Option<Color>, }, } #[derive(ArgEnum)] enum Direction { Up, Down, } #[derive(ArgEnum)] enum Speed { Slow, Medium, Fast, } #[derive(ArgEnum)] enum Brightness { _0, _25, _50, _75, _100, } impl From<&Direction> for u8 { fn from(d: &Direction) -> u8 { match d { Direction::Up => 1, Direction::Down => 0, } } } impl From<&Speed> for u8 { fn from(s: &Speed) -> u8 { match s { Speed::Slow => 1, Speed::Medium => 2, Speed::Fast => 3, } } } impl From<&Brightness> for u8 { fn from(b: &Brightness) -> u8 { match b { Brightness::_0 => 0, Brightness::_25 => 1, Brightness::_50 => 2, Brightness::_75 => 3, Brightness::_100 => 4, } } } impl Dump { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { dbg!(dev.read_fw_version()?); dbg!(dev.read_config()?); //dbg!(dev.read_buttonmap()?); Ok(()) } } impl Buttons { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut map = gloryctl::DEFAULT_MAP; for b in &self.mappings { if b.which < 1 || b.which > 6 { return Err(anyhow!("Invalid button number {}", b.which)); } let i = b.which - 1; map[i] = b.action; } dev.send_buttonmap(&map) } } impl Dpi { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; assert!(self.which >= 1 && self.which <= 8); let i = self.which - 1; let prof = &mut conf.dpi_profiles[i]; if let Some(color) = self.color { prof.color = color; } if let Some(dpi) = self.dpi { prof.value = DpiValue::Single(dpi) } conf.fixup_dpi_metadata(); dev.send_config(&conf)?; Ok(()) } } impl Macro { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { if self.bank > 3 { return Err(anyhow!( r"Only 2 macro banks are supported for now, TODO find out how many the hardware supports without bricking it" )); } dev.send_macro_bank(self.bank, &self.events) } } impl Rgb { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; match self { Rgb::Off => { conf.rgb_current_effect = Effect::Off; } Rgb::Glorious { direction, speed } => { conf.rgb_current_effect = Effect::Glorious; if let Some(dir) = direction { conf.rgb_effect_parameters.glorious.direction = dir.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.glorious.speed = spd.into(); } } Rgb::Single { color, brightness } => { conf.rgb_current_effect = Effect::SingleColor; if let Some(clr) = color { conf.rgb_effect_parameters.single_color.color = *clr; } if let Some(br) = brightness { conf.rgb_effect_parameters.single_color.brightness = br.into(); } } Rgb::Breathing { speed, colors } => { conf.rgb_current_effect = Effect::Breathing; if let Some(spd) = speed { conf.rgb_effect_parameters.breathing.speed = spd.into(); } if colors.len() > 7 { return Err(anyhow::Error::msg("At most 7 colors are supported.")); } if colors.len() > 0
} Rgb::Tail { speed, brightness } => { conf.rgb_current_effect = Effect::Tail; if let Some(spd) = speed { conf.rgb_effect_parameters.tail.speed = spd.into(); } if let Some(br) = brightness { conf.rgb_effect_parameters.tail.brightness = br.into(); } } Rgb::SeamlessBreathing { speed } => { conf.rgb_current_effect = Effect::SeamlessBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.seamless_breathing.speed = spd.into(); } } Rgb::ConstantRgb { colors } => { conf.rgb_current_effect = Effect::ConstantRgb; assert!(colors.len() <= 6); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.constant_rgb.colors[i] = *c; } } Rgb::Rave { brightness, speed, colors, } => { conf.rgb_current_effect = Effect::Rave; if let Some(br) = brightness { conf.rgb_effect_parameters.rave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.rave.speed = spd.into(); } assert!(colors.len() <= 2); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.rave.colors[i] = *c; } } Rgb::Random { speed } => { conf.rgb_current_effect = Effect::Random; // HACK: this effect is not available officialy, and it is not properly // intialized, with the speed set to 0 (which is likely not a valid value, // as it behaves the same as if 0 is set for the speed of other effects, // that is the effect is extremely fast). // Initialize the value if needed. if conf.rgb_effect_parameters.random.speed == 0 { conf.rgb_effect_parameters.random.speed = 1; } if let Some(spd) = speed { conf.rgb_effect_parameters.random.speed = spd.into(); } } Rgb::Wave { brightness, speed } => { conf.rgb_current_effect = Effect::Wave; if let Some(br) = brightness { conf.rgb_effect_parameters.wave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.wave.speed = spd.into(); } } Rgb::SingleBreathing { speed, color } => { conf.rgb_current_effect = Effect::SingleBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.single_breathing.speed = spd.into(); } if let Some(clr) = color { conf.rgb_effect_parameters.single_breathing.color = *clr; } } }; dev.send_config(&conf) } } fn main() -> Result<()> { //Dump {}.run()?; let opts = Opts::parse(); let hid = hidapi::HidApi::new()?; let mut dev = GloriousDevice::open_first(&hid)?; dev.send_msg(0x02, 1)?; match opts.cmd { Command::Dump(dump) => dump.run(&mut dev), Command::Button(b) => b.run(&mut dev), Command::Rgb { rgbcmd } => rgbcmd.run(&mut dev), Command::Dpi(dpi) => dpi.run(&mut dev), Command::Macro(macro_) => macro_.run(&mut dev), } }
{ conf.rgb_effect_parameters.breathing.count = colors.len().try_into()?; for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.breathing.colors[i] = *c; } }
conditional_block
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] enum Command { /// Dump the firmware version and Config Dump(Dump), /// Configure the button mapping Button(Buttons), /// Configure DPI profiles Dpi(Dpi), /// Configure macros Macro(Macro), /// Configure the RGB effect // This is weird due to https://github.com/clap-rs/clap/issues/2005 Rgb { #[clap(subcommand)] rgbcmd: Rgb, }, } #[derive(Clap)] struct Dump {} #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The format of a mapping is button:action-type[:action-params...] where button is a number from 1 to 6 and action-type:action-params] is one of the following: - disable - mouse:button (button is one of 'left', 'right','middle', 'back', 'forward') - scroll:amount (amount can also be 'up' and 'down', corresponding to 1 and -1) - repeat:button:count[:interval=50] (button is same as'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the default configuration is used. The default configuration can be represented as: 1:mouse:left 2:mouse:right 3:mouse:middle 4:mouse:back 5:mouse:forward 6:dpi:loop")] struct Buttons { mappings: Vec<SingleButton>, } struct SingleButton { which: usize, action: ButtonAction, } impl FromStr for SingleButton { type Err = anyhow::Error; fn
(s: &str) -> Result<Self, Self::Err> { let (btn, act) = s .split_once(':') .context("Format: button:action-type[:action-params]")?; let which = usize::from_str(btn)?; let action = ButtonAction::from_str(act)?; Ok(Self { which, action }) } } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The mouse has support for 8 dpi profiles, of which each has a configured dpi value and a color (which is displayed on the LED on the bottom of the mouse. For example, to change the color of dpi profile number 3, you could use gloryctl dpi -c 00ffff 3 At this point, it is not possible to enable or disable profiles.")] // TODO struct Dpi { #[clap(possible_values = &["1", "2", "3", "4", "5", "6", "7", "8"])] which: usize, #[clap(short, long)] color: Option<Color>, #[clap(short, long)] dpi: Option<u16>, // TODO independent X and Y } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: This subcommand can be used to program macros. The first argument is the bank number. Following is a list of events. Each event has a format of state:type:key:duration. - state is either 'up' or 'down' - type is one of 'keyboard','modifier','mouse' - key takes on values depending on type, similar to button mappings - duration is in milliseconds, how long to pause before continuing")] struct Macro { bank: u8, events: Vec<Event>, } #[derive(Clap)] enum Rgb { /// Lighting disabled Off, /// Rotating rainbow (default for new mice) Glorious { #[clap(arg_enum, long, short)] direction: Option<Direction>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color Single { #[clap(long, short)] color: Option<Color>, #[clap(arg_enum, long, short)] brightness: Option<Brightness>, }, /// Slowly cycles through the given list of colors Breathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, //#[clap(long, short, max_values = 7)] // we are not using max_values here, because it // leads to confusing behaviour when more values are passed #[clap(long, short)] colors: Vec<Color>, }, /// Tail { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Cycle through colors seamlessly SeamlessBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Constant color for each of the six LEDs ConstantRgb { #[clap(long, short, number_of_values = 6)] colors: Vec<Color>, }, /// Switching between two configured colors Rave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short, number_of_values = 2)] colors: Vec<Color>, }, /// Randomly changing colors Random { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, Wave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color breathing SingleBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short)] color: Option<Color>, }, } #[derive(ArgEnum)] enum Direction { Up, Down, } #[derive(ArgEnum)] enum Speed { Slow, Medium, Fast, } #[derive(ArgEnum)] enum Brightness { _0, _25, _50, _75, _100, } impl From<&Direction> for u8 { fn from(d: &Direction) -> u8 { match d { Direction::Up => 1, Direction::Down => 0, } } } impl From<&Speed> for u8 { fn from(s: &Speed) -> u8 { match s { Speed::Slow => 1, Speed::Medium => 2, Speed::Fast => 3, } } } impl From<&Brightness> for u8 { fn from(b: &Brightness) -> u8 { match b { Brightness::_0 => 0, Brightness::_25 => 1, Brightness::_50 => 2, Brightness::_75 => 3, Brightness::_100 => 4, } } } impl Dump { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { dbg!(dev.read_fw_version()?); dbg!(dev.read_config()?); //dbg!(dev.read_buttonmap()?); Ok(()) } } impl Buttons { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut map = gloryctl::DEFAULT_MAP; for b in &self.mappings { if b.which < 1 || b.which > 6 { return Err(anyhow!("Invalid button number {}", b.which)); } let i = b.which - 1; map[i] = b.action; } dev.send_buttonmap(&map) } } impl Dpi { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; assert!(self.which >= 1 && self.which <= 8); let i = self.which - 1; let prof = &mut conf.dpi_profiles[i]; if let Some(color) = self.color { prof.color = color; } if let Some(dpi) = self.dpi { prof.value = DpiValue::Single(dpi) } conf.fixup_dpi_metadata(); dev.send_config(&conf)?; Ok(()) } } impl Macro { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { if self.bank > 3 { return Err(anyhow!( r"Only 2 macro banks are supported for now, TODO find out how many the hardware supports without bricking it" )); } dev.send_macro_bank(self.bank, &self.events) } } impl Rgb { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; match self { Rgb::Off => { conf.rgb_current_effect = Effect::Off; } Rgb::Glorious { direction, speed } => { conf.rgb_current_effect = Effect::Glorious; if let Some(dir) = direction { conf.rgb_effect_parameters.glorious.direction = dir.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.glorious.speed = spd.into(); } } Rgb::Single { color, brightness } => { conf.rgb_current_effect = Effect::SingleColor; if let Some(clr) = color { conf.rgb_effect_parameters.single_color.color = *clr; } if let Some(br) = brightness { conf.rgb_effect_parameters.single_color.brightness = br.into(); } } Rgb::Breathing { speed, colors } => { conf.rgb_current_effect = Effect::Breathing; if let Some(spd) = speed { conf.rgb_effect_parameters.breathing.speed = spd.into(); } if colors.len() > 7 { return Err(anyhow::Error::msg("At most 7 colors are supported.")); } if colors.len() > 0 { conf.rgb_effect_parameters.breathing.count = colors.len().try_into()?; for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.breathing.colors[i] = *c; } } } Rgb::Tail { speed, brightness } => { conf.rgb_current_effect = Effect::Tail; if let Some(spd) = speed { conf.rgb_effect_parameters.tail.speed = spd.into(); } if let Some(br) = brightness { conf.rgb_effect_parameters.tail.brightness = br.into(); } } Rgb::SeamlessBreathing { speed } => { conf.rgb_current_effect = Effect::SeamlessBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.seamless_breathing.speed = spd.into(); } } Rgb::ConstantRgb { colors } => { conf.rgb_current_effect = Effect::ConstantRgb; assert!(colors.len() <= 6); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.constant_rgb.colors[i] = *c; } } Rgb::Rave { brightness, speed, colors, } => { conf.rgb_current_effect = Effect::Rave; if let Some(br) = brightness { conf.rgb_effect_parameters.rave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.rave.speed = spd.into(); } assert!(colors.len() <= 2); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.rave.colors[i] = *c; } } Rgb::Random { speed } => { conf.rgb_current_effect = Effect::Random; // HACK: this effect is not available officialy, and it is not properly // intialized, with the speed set to 0 (which is likely not a valid value, // as it behaves the same as if 0 is set for the speed of other effects, // that is the effect is extremely fast). // Initialize the value if needed. if conf.rgb_effect_parameters.random.speed == 0 { conf.rgb_effect_parameters.random.speed = 1; } if let Some(spd) = speed { conf.rgb_effect_parameters.random.speed = spd.into(); } } Rgb::Wave { brightness, speed } => { conf.rgb_current_effect = Effect::Wave; if let Some(br) = brightness { conf.rgb_effect_parameters.wave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.wave.speed = spd.into(); } } Rgb::SingleBreathing { speed, color } => { conf.rgb_current_effect = Effect::SingleBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.single_breathing.speed = spd.into(); } if let Some(clr) = color { conf.rgb_effect_parameters.single_breathing.color = *clr; } } }; dev.send_config(&conf) } } fn main() -> Result<()> { //Dump {}.run()?; let opts = Opts::parse(); let hid = hidapi::HidApi::new()?; let mut dev = GloriousDevice::open_first(&hid)?; dev.send_msg(0x02, 1)?; match opts.cmd { Command::Dump(dump) => dump.run(&mut dev), Command::Button(b) => b.run(&mut dev), Command::Rgb { rgbcmd } => rgbcmd.run(&mut dev), Command::Dpi(dpi) => dpi.run(&mut dev), Command::Macro(macro_) => macro_.run(&mut dev), } }
from_str
identifier_name
main.rs
use std::convert::TryInto; use std::str::FromStr; use anyhow::{anyhow, Context, Result}; use clap::{ArgEnum, Clap}; use gloryctl::macros::Event; use gloryctl::{rgb::Effect, ButtonAction, Color, DpiValue, GloriousDevice}; #[derive(Clap)] pub struct Opts { #[clap(subcommand)] cmd: Command, } #[derive(Clap)] enum Command { /// Dump the firmware version and Config Dump(Dump), /// Configure the button mapping Button(Buttons), /// Configure DPI profiles Dpi(Dpi), /// Configure macros Macro(Macro), /// Configure the RGB effect // This is weird due to https://github.com/clap-rs/clap/issues/2005 Rgb { #[clap(subcommand)] rgbcmd: Rgb, }, } #[derive(Clap)] struct Dump {} #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The format of a mapping is button:action-type[:action-params...] where button is a number from 1 to 6 and action-type:action-params] is one of the following: - disable - mouse:button (button is one of 'left', 'right','middle', 'back', 'forward') - scroll:amount (amount can also be 'up' and 'down', corresponding to 1 and -1) - repeat:button:count[:interval=50] (button is same as'mouse', ) - dpi:direction, direction is one of 'loop', 'up', 'down' - dpi-lock:value - media:key - macro:bank - keyboard:modifiers:key The provided mappings are always applied over the default configuration, not the current one. If no mappings are provided, the default configuration is used. The default configuration can be represented as: 1:mouse:left 2:mouse:right 3:mouse:middle 4:mouse:back 5:mouse:forward 6:dpi:loop")] struct Buttons { mappings: Vec<SingleButton>, } struct SingleButton { which: usize, action: ButtonAction, } impl FromStr for SingleButton { type Err = anyhow::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let (btn, act) = s .split_once(':') .context("Format: button:action-type[:action-params]")?; let which = usize::from_str(btn)?; let action = ButtonAction::from_str(act)?; Ok(Self { which, action }) } } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: The mouse has support for 8 dpi profiles, of which each has a configured dpi value and a color (which is displayed on the LED on the bottom of the mouse. For example, to change the color of dpi profile number 3, you could use gloryctl dpi -c 00ffff 3 At this point, it is not possible to enable or disable profiles.")] // TODO struct Dpi { #[clap(possible_values = &["1", "2", "3", "4", "5", "6", "7", "8"])] which: usize, #[clap(short, long)] color: Option<Color>, #[clap(short, long)] dpi: Option<u16>, // TODO independent X and Y } #[derive(Clap)] #[clap(after_help = r"DISCUSSION: This subcommand can be used to program macros. The first argument is the bank number. Following is a list of events. Each event has a format of state:type:key:duration. - state is either 'up' or 'down' - type is one of 'keyboard','modifier','mouse' - key takes on values depending on type, similar to button mappings - duration is in milliseconds, how long to pause before continuing")] struct Macro { bank: u8, events: Vec<Event>, } #[derive(Clap)] enum Rgb { /// Lighting disabled Off, /// Rotating rainbow (default for new mice) Glorious { #[clap(arg_enum, long, short)] direction: Option<Direction>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color Single { #[clap(long, short)] color: Option<Color>, #[clap(arg_enum, long, short)] brightness: Option<Brightness>, }, /// Slowly cycles through the given list of colors Breathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, //#[clap(long, short, max_values = 7)] // we are not using max_values here, because it // leads to confusing behaviour when more values are passed #[clap(long, short)] colors: Vec<Color>, }, /// Tail { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Cycle through colors seamlessly SeamlessBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Constant color for each of the six LEDs ConstantRgb { #[clap(long, short, number_of_values = 6)] colors: Vec<Color>, }, /// Switching between two configured colors Rave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short, number_of_values = 2)] colors: Vec<Color>, }, /// Randomly changing colors Random { #[clap(arg_enum, long, short)] speed: Option<Speed>, }, Wave { #[clap(arg_enum, long, short)] brightness: Option<Brightness>, #[clap(arg_enum, long, short)] speed: Option<Speed>, }, /// Single color breathing SingleBreathing { #[clap(arg_enum, long, short)] speed: Option<Speed>, #[clap(long, short)] color: Option<Color>, }, } #[derive(ArgEnum)] enum Direction { Up, Down, } #[derive(ArgEnum)] enum Speed { Slow, Medium, Fast, } #[derive(ArgEnum)] enum Brightness { _0, _25, _50, _75, _100, } impl From<&Direction> for u8 { fn from(d: &Direction) -> u8 { match d { Direction::Up => 1, Direction::Down => 0, } } } impl From<&Speed> for u8 { fn from(s: &Speed) -> u8 { match s { Speed::Slow => 1, Speed::Medium => 2, Speed::Fast => 3, } } } impl From<&Brightness> for u8 { fn from(b: &Brightness) -> u8 { match b { Brightness::_0 => 0, Brightness::_25 => 1, Brightness::_50 => 2, Brightness::_75 => 3, Brightness::_100 => 4, } } } impl Dump { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { dbg!(dev.read_fw_version()?); dbg!(dev.read_config()?); //dbg!(dev.read_buttonmap()?); Ok(()) } } impl Buttons { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut map = gloryctl::DEFAULT_MAP; for b in &self.mappings { if b.which < 1 || b.which > 6 { return Err(anyhow!("Invalid button number {}", b.which)); } let i = b.which - 1; map[i] = b.action; } dev.send_buttonmap(&map) } } impl Dpi { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; assert!(self.which >= 1 && self.which <= 8); let i = self.which - 1; let prof = &mut conf.dpi_profiles[i]; if let Some(color) = self.color { prof.color = color; } if let Some(dpi) = self.dpi { prof.value = DpiValue::Single(dpi) }
} } impl Macro { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { if self.bank > 3 { return Err(anyhow!( r"Only 2 macro banks are supported for now, TODO find out how many the hardware supports without bricking it" )); } dev.send_macro_bank(self.bank, &self.events) } } impl Rgb { fn run(&self, dev: &mut GloriousDevice) -> Result<()> { let mut conf = dev.read_config()?; match self { Rgb::Off => { conf.rgb_current_effect = Effect::Off; } Rgb::Glorious { direction, speed } => { conf.rgb_current_effect = Effect::Glorious; if let Some(dir) = direction { conf.rgb_effect_parameters.glorious.direction = dir.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.glorious.speed = spd.into(); } } Rgb::Single { color, brightness } => { conf.rgb_current_effect = Effect::SingleColor; if let Some(clr) = color { conf.rgb_effect_parameters.single_color.color = *clr; } if let Some(br) = brightness { conf.rgb_effect_parameters.single_color.brightness = br.into(); } } Rgb::Breathing { speed, colors } => { conf.rgb_current_effect = Effect::Breathing; if let Some(spd) = speed { conf.rgb_effect_parameters.breathing.speed = spd.into(); } if colors.len() > 7 { return Err(anyhow::Error::msg("At most 7 colors are supported.")); } if colors.len() > 0 { conf.rgb_effect_parameters.breathing.count = colors.len().try_into()?; for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.breathing.colors[i] = *c; } } } Rgb::Tail { speed, brightness } => { conf.rgb_current_effect = Effect::Tail; if let Some(spd) = speed { conf.rgb_effect_parameters.tail.speed = spd.into(); } if let Some(br) = brightness { conf.rgb_effect_parameters.tail.brightness = br.into(); } } Rgb::SeamlessBreathing { speed } => { conf.rgb_current_effect = Effect::SeamlessBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.seamless_breathing.speed = spd.into(); } } Rgb::ConstantRgb { colors } => { conf.rgb_current_effect = Effect::ConstantRgb; assert!(colors.len() <= 6); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.constant_rgb.colors[i] = *c; } } Rgb::Rave { brightness, speed, colors, } => { conf.rgb_current_effect = Effect::Rave; if let Some(br) = brightness { conf.rgb_effect_parameters.rave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.rave.speed = spd.into(); } assert!(colors.len() <= 2); for (i, c) in colors.iter().enumerate() { conf.rgb_effect_parameters.rave.colors[i] = *c; } } Rgb::Random { speed } => { conf.rgb_current_effect = Effect::Random; // HACK: this effect is not available officialy, and it is not properly // intialized, with the speed set to 0 (which is likely not a valid value, // as it behaves the same as if 0 is set for the speed of other effects, // that is the effect is extremely fast). // Initialize the value if needed. if conf.rgb_effect_parameters.random.speed == 0 { conf.rgb_effect_parameters.random.speed = 1; } if let Some(spd) = speed { conf.rgb_effect_parameters.random.speed = spd.into(); } } Rgb::Wave { brightness, speed } => { conf.rgb_current_effect = Effect::Wave; if let Some(br) = brightness { conf.rgb_effect_parameters.wave.brightness = br.into(); } if let Some(spd) = speed { conf.rgb_effect_parameters.wave.speed = spd.into(); } } Rgb::SingleBreathing { speed, color } => { conf.rgb_current_effect = Effect::SingleBreathing; if let Some(spd) = speed { conf.rgb_effect_parameters.single_breathing.speed = spd.into(); } if let Some(clr) = color { conf.rgb_effect_parameters.single_breathing.color = *clr; } } }; dev.send_config(&conf) } } fn main() -> Result<()> { //Dump {}.run()?; let opts = Opts::parse(); let hid = hidapi::HidApi::new()?; let mut dev = GloriousDevice::open_first(&hid)?; dev.send_msg(0x02, 1)?; match opts.cmd { Command::Dump(dump) => dump.run(&mut dev), Command::Button(b) => b.run(&mut dev), Command::Rgb { rgbcmd } => rgbcmd.run(&mut dev), Command::Dpi(dpi) => dpi.run(&mut dev), Command::Macro(macro_) => macro_.run(&mut dev), } }
conf.fixup_dpi_metadata(); dev.send_config(&conf)?; Ok(())
random_line_split
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Op { /** Open the current Room, allowing in the general public. */ Open, /** Close the current Room to anyone who hasn't been specifically `Invite`d. */ Close, /** Ban the user with the supplied user name from the Room (even if it's `Open`), removing him if he's currently in it. */ Kick(String), /** Allow the user to enter the current room, even if it's `Close`d. Also sends an invitation message to the user. */ Invite(String), /** Transfer operatorship to another user. (The user must be in the current room to receive the mantle of operatorship.) */ Give(String), } /** The `Msg` enum is the structure that gets serialized to JSON and passed along the TCP connections between the server and the various clients. The first four variants, `Text`, `Ping`, `Priv` and `Logout` are bi-directional, being used to send similar information both from client to server and server to client. The next six, `Name`, `Join`, `Query`, `Block`, `Unblock`, and `Op` are for sending commands or requests from the client to the server. The final three, `Info`, `Err`, and `Misc` are used to send information from the server back to the client. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Msg { // Bi-directional messages /// Typical chunk of text to be exchanged while chatting. Text { #[serde(default)] who: String, lines: Vec<String>, }, /** Request for or acknowledgement of proof of connection. If the server hasn't received any data from the client in a while, it will send one of these. The client can then respond with one to indicate it's still connected. */ Ping, /** A private message delivered only to the recipient. When sent from the client to the server, `who` should be an identifier for the _recipient_; when sent server to client, `who` is the name of the source. */ Priv { who: String, text: String, }, /** A message from the client indicating it would like to disconnect cleanly from the server; in response, the server will send back one of these with a message and close the connection. */ Logout(String), // Client-to-server messages. /// Name-change request from client to server. Name(String), /// Client request to create/join a room. Join(String), /** A request from the client to the server for some type of information, like a list of users matching a pattern. */ Query { what: String, arg: String, }, /** A request from the client to block messages (including private messages) from the user with the matching name. */ Block(String), /** A request to unblock the given user. */ Unblock(String), /** One of the Room operator subcommands. See the `proto2::Op` enum. */ Op(Op), // Server-to-client messages. /** A non-error, miscellaneously-informative message sent form the server to the client. */ Info(String), /** A message from the server to the client indicating the client has done something wrong, like sent an invalid message. */ Err(String), /** The `Misc` variant represents information that the client may want to display in a structured manner (and not just as an unadorned line of text). For any given "type" of `Misc` message, the client is free to either implement its own form of displaying the information, or to just use the contents of the provided `.alt` field. Current Misc variants (with example field values): ``` ignore // in response to a Query { what: "roster".... } Misc { what: "roster".to_string(), data: vec!["user1".to_string(), "user2".to_string()], #... alt: "[ comma-delimited list of Users in room ]".to_string(), }; // when a user joins a channel Misc { what: "join".to_string(), data: vec!["grel user".to_string(), "room name".to_string()], alt: "grel user joins [room name]".to_string(), }; // when a user logs out or leaves a channel Misc { what: "leave".to_string(), data: vec!["grel user".to_string(), "moved to another room".to_string()], alt: "grel user moved to another room".to_string(), }; // when a user is kicked from the current channel Misc { what: "kick_other".to_string(), data: vec!["Bad User".to_string(), "This Room".to_string()], alt: "Bad User has been kicked from This Room.".to_string(), }; // When YOU are kicked from the current channel. Misc { what: "kick_you".to_string(), data: vec!["This Room".to_string()], alt: "You have been kicked from This Room.".to_string(), }; // when a user changes his or her name Misc { what: "name".to_string(), data: vec!["old name".to_string(), "new name".to_string()], alt: "\"old name\" is now known as \"new name\".".to_string(), }; // when the Room operator changes Misc { what: "new_op".to_string(), data: ["New Operator".to_string(), "This Room".to_string()], alt: "New Operator is now the operator of This Room".to_string(), }; // in response to a Query { what: "addr",... } Misc { what: "addr".to_string(), data: vec!["127.0.0.1:33333".to_string()] alt: "Your public address is 127.0.0.1:33333".to_string(), }; // in response to a Query { what: "who",... } Misc { what: "who".to_string(), data: vec!["user1".to_string(), "user2".to_string(),... ], alt: "Matching names: \"user1\", \"user2\",...".to_string(), }; // echoes a private message back to the sender Misc { what: "priv_echo".to_string(), data: vec!["recipient".to_string(), "text of message".to_string()], alt: "$ You @ Recipient: text of message".to_string() }; ``` */ Misc { what: String, data: Vec<String>, alt: String, }, } /** Some of these are convenience functions for instantiating certain variants. */ impl Msg { pub fn logout(msg: &str) -> Msg { Msg::Logout(String::from(msg)) } pub fn info(msg: &str) -> Msg { Msg::Info(String::from(msg)) } pub fn err(msg: &str) -> Msg { Msg::Err(String::from(msg)) } /// Return a JSON-encoded version of a `Msg`. pub fn bytes(&self) -> Vec<u8> { serde_json::to_vec_pretty(&self).unwrap() } /** Return whether a Msg should count against a user's "byte quota" (for rate limiting). Generally, this is anything that causes "noise". */ pub fn counts(&self) -> bool { match self { Msg::Text { who: _, lines: _ } => true, Msg::Priv { who: _, text: _ } => true, Msg::Name(_) => true, Msg::Join(_) => true, _ => false, } } } /** The `Endpoint` enum specifies sources and destinations in an `Env`. `User`s and `Room`s are stored in respective `HashMap`s with unique `u64` IDs as keys. */ #[derive(Copy, Clone, Debug)] pub enum Endpoint { User(u64), Room(u64), Server, All, } /** An `Env` (-elope) wraps the bytes of a JSON-encoded `Msg`, along with unambiguous source and destination information. This metadata is necessary because the encoded JSON is opaque to the server without decoding it. */ #[derive(Clone, Debug)] pub struct Env { pub source: Endpoint, pub dest: Endpoint, data: Vec<u8>, } impl Env { /** Wrap a `Msg`. */ pub fn new(from: Endpoint, to: Endpoint, msg: &Msg) -> Env { Env { source: from, dest: to, data: msg.bytes(), } } /** Get a reference to the encoded bytes. */ pub fn bytes(&self) -> &[u8] { &self.data } /** Consume the `Env`, returning the owned vector of bytes. */ pub fn into_bytes(self) -> Vec<u8> { self.data } } #[cfg(test)] mod test { use super::*; fn test_serde(m: &Msg) { let stringd = serde_json::to_string_pretty(m).unwrap(); println!("{}\n", &stringd); let newm: Msg = serde_json::from_str(&stringd).unwrap(); assert_eq!(*m, newm); } #[test] fn visual_serde()
println!("Msg::Logout variant"); let m = Msg::logout("You have been logged out because you touch yourself at night."); test_serde(&m); println!("Msg::Name variant"); let m = Msg::Name(String::from("New Lewser")); test_serde(&m); println!("Msg::Join variant"); let m = Msg::Join(String::from("Gay Space Communism")); test_serde(&m); println!("Msg::Query variant"); let m = Msg::Query { what: String::from("who"), arg: String::from("fink"), }; test_serde(&m); println!("Msg::Block variant"); let m = Msg::Block(String::from("Dickweed User")); test_serde(&m); println!("Msg::Unblock variant"); let m = Msg::Unblock(String::from("Misunderstood User")); test_serde(&m); println!("A couple of Msg::Op variants"); let m = Msg::Op(Op::Close); test_serde(&m); let m = Msg::Op(Op::Kick("FpS DoUgG".to_string())); test_serde(&m); println!("Msg::Info variant"); let m = Msg::info("Santa isn't real."); test_serde(&m); println!("Msg::Err variant"); let m = Msg::err("Unrecognized Query \"meaning of life\"."); test_serde(&m); println!("Msg::Misc variant"); let m = Msg::Misc { what: String::from("roster"), data: vec!["you".to_string(), "me".to_string(), "a dog named foo".to_string()], alt: String::from("you, me, and a dog named foo"), }; test_serde(&m); } }
{ println!("Msg::Text variant"); let m = Msg::Text { who: String::from("gre luser"), lines: vec!["This is a first line of text.".to_string(), "Following the first is a second line of text.".to_string()], }; test_serde(&m); println!("Msg::Ping variant"); let m = Msg::Ping; test_serde(&m); println!("Msg::Priv variant"); let m = Msg::Priv { who: String::from("naggum"), text: String::from("XML is bascially the Hitler of protocols."), }; test_serde(&m);
identifier_body
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Op { /** Open the current Room, allowing in the general public. */ Open, /** Close the current Room to anyone who hasn't been specifically `Invite`d. */ Close, /** Ban the user with the supplied user name from the Room (even if it's `Open`), removing him if he's currently in it. */ Kick(String), /** Allow the user to enter the current room, even if it's `Close`d. Also sends an invitation message to the user. */ Invite(String), /** Transfer operatorship to another user. (The user must be in the current room to receive the mantle of operatorship.) */ Give(String), } /** The `Msg` enum is the structure that gets serialized to JSON and passed along the TCP connections between the server and the various clients. The first four variants, `Text`, `Ping`, `Priv` and `Logout` are bi-directional, being used to send similar information both from client to server and server to client. The next six, `Name`, `Join`, `Query`, `Block`, `Unblock`, and `Op` are for sending commands or requests from the client to the server. The final three, `Info`, `Err`, and `Misc` are used to send information from the server back to the client. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Msg { // Bi-directional messages /// Typical chunk of text to be exchanged while chatting. Text { #[serde(default)] who: String, lines: Vec<String>, }, /** Request for or acknowledgement of proof of connection. If the server hasn't received any data from the client in a while, it will send one of these. The client can then respond with one to indicate it's still connected. */ Ping, /** A private message delivered only to the recipient. When sent from the client to the server, `who` should be an identifier for the _recipient_; when sent server to client, `who` is the name of the source. */ Priv { who: String, text: String, }, /** A message from the client indicating it would like to disconnect cleanly from the server; in response, the server will send back one of these with a message and close the connection. */ Logout(String), // Client-to-server messages. /// Name-change request from client to server. Name(String), /// Client request to create/join a room. Join(String), /** A request from the client to the server for some type of information, like a list of users matching a pattern. */ Query { what: String, arg: String, }, /** A request from the client to block messages (including private messages) from the user with the matching name. */ Block(String), /** A request to unblock the given user. */ Unblock(String), /** One of the Room operator subcommands. See the `proto2::Op` enum. */ Op(Op), // Server-to-client messages. /** A non-error, miscellaneously-informative message sent form the server to the client. */ Info(String), /** A message from the server to the client indicating the client has done something wrong, like sent an invalid message. */ Err(String), /** The `Misc` variant represents information that the client may want to display in a structured manner (and not just as an unadorned line of text). For any given "type" of `Misc` message, the client is free to either implement its own form of displaying the information, or to just use the contents of the provided `.alt` field. Current Misc variants (with example field values): ``` ignore // in response to a Query { what: "roster".... } Misc { what: "roster".to_string(), data: vec!["user1".to_string(), "user2".to_string()], #... alt: "[ comma-delimited list of Users in room ]".to_string(), }; // when a user joins a channel Misc { what: "join".to_string(), data: vec!["grel user".to_string(), "room name".to_string()], alt: "grel user joins [room name]".to_string(), }; // when a user logs out or leaves a channel Misc { what: "leave".to_string(), data: vec!["grel user".to_string(), "moved to another room".to_string()], alt: "grel user moved to another room".to_string(), }; // when a user is kicked from the current channel Misc { what: "kick_other".to_string(), data: vec!["Bad User".to_string(), "This Room".to_string()], alt: "Bad User has been kicked from This Room.".to_string(), }; // When YOU are kicked from the current channel. Misc { what: "kick_you".to_string(), data: vec!["This Room".to_string()], alt: "You have been kicked from This Room.".to_string(), };
Misc { what: "name".to_string(), data: vec!["old name".to_string(), "new name".to_string()], alt: "\"old name\" is now known as \"new name\".".to_string(), }; // when the Room operator changes Misc { what: "new_op".to_string(), data: ["New Operator".to_string(), "This Room".to_string()], alt: "New Operator is now the operator of This Room".to_string(), }; // in response to a Query { what: "addr",... } Misc { what: "addr".to_string(), data: vec!["127.0.0.1:33333".to_string()] alt: "Your public address is 127.0.0.1:33333".to_string(), }; // in response to a Query { what: "who",... } Misc { what: "who".to_string(), data: vec!["user1".to_string(), "user2".to_string(),... ], alt: "Matching names: \"user1\", \"user2\",...".to_string(), }; // echoes a private message back to the sender Misc { what: "priv_echo".to_string(), data: vec!["recipient".to_string(), "text of message".to_string()], alt: "$ You @ Recipient: text of message".to_string() }; ``` */ Misc { what: String, data: Vec<String>, alt: String, }, } /** Some of these are convenience functions for instantiating certain variants. */ impl Msg { pub fn logout(msg: &str) -> Msg { Msg::Logout(String::from(msg)) } pub fn info(msg: &str) -> Msg { Msg::Info(String::from(msg)) } pub fn err(msg: &str) -> Msg { Msg::Err(String::from(msg)) } /// Return a JSON-encoded version of a `Msg`. pub fn bytes(&self) -> Vec<u8> { serde_json::to_vec_pretty(&self).unwrap() } /** Return whether a Msg should count against a user's "byte quota" (for rate limiting). Generally, this is anything that causes "noise". */ pub fn counts(&self) -> bool { match self { Msg::Text { who: _, lines: _ } => true, Msg::Priv { who: _, text: _ } => true, Msg::Name(_) => true, Msg::Join(_) => true, _ => false, } } } /** The `Endpoint` enum specifies sources and destinations in an `Env`. `User`s and `Room`s are stored in respective `HashMap`s with unique `u64` IDs as keys. */ #[derive(Copy, Clone, Debug)] pub enum Endpoint { User(u64), Room(u64), Server, All, } /** An `Env` (-elope) wraps the bytes of a JSON-encoded `Msg`, along with unambiguous source and destination information. This metadata is necessary because the encoded JSON is opaque to the server without decoding it. */ #[derive(Clone, Debug)] pub struct Env { pub source: Endpoint, pub dest: Endpoint, data: Vec<u8>, } impl Env { /** Wrap a `Msg`. */ pub fn new(from: Endpoint, to: Endpoint, msg: &Msg) -> Env { Env { source: from, dest: to, data: msg.bytes(), } } /** Get a reference to the encoded bytes. */ pub fn bytes(&self) -> &[u8] { &self.data } /** Consume the `Env`, returning the owned vector of bytes. */ pub fn into_bytes(self) -> Vec<u8> { self.data } } #[cfg(test)] mod test { use super::*; fn test_serde(m: &Msg) { let stringd = serde_json::to_string_pretty(m).unwrap(); println!("{}\n", &stringd); let newm: Msg = serde_json::from_str(&stringd).unwrap(); assert_eq!(*m, newm); } #[test] fn visual_serde() { println!("Msg::Text variant"); let m = Msg::Text { who: String::from("gre luser"), lines: vec!["This is a first line of text.".to_string(), "Following the first is a second line of text.".to_string()], }; test_serde(&m); println!("Msg::Ping variant"); let m = Msg::Ping; test_serde(&m); println!("Msg::Priv variant"); let m = Msg::Priv { who: String::from("naggum"), text: String::from("XML is bascially the Hitler of protocols."), }; test_serde(&m); println!("Msg::Logout variant"); let m = Msg::logout("You have been logged out because you touch yourself at night."); test_serde(&m); println!("Msg::Name variant"); let m = Msg::Name(String::from("New Lewser")); test_serde(&m); println!("Msg::Join variant"); let m = Msg::Join(String::from("Gay Space Communism")); test_serde(&m); println!("Msg::Query variant"); let m = Msg::Query { what: String::from("who"), arg: String::from("fink"), }; test_serde(&m); println!("Msg::Block variant"); let m = Msg::Block(String::from("Dickweed User")); test_serde(&m); println!("Msg::Unblock variant"); let m = Msg::Unblock(String::from("Misunderstood User")); test_serde(&m); println!("A couple of Msg::Op variants"); let m = Msg::Op(Op::Close); test_serde(&m); let m = Msg::Op(Op::Kick("FpS DoUgG".to_string())); test_serde(&m); println!("Msg::Info variant"); let m = Msg::info("Santa isn't real."); test_serde(&m); println!("Msg::Err variant"); let m = Msg::err("Unrecognized Query \"meaning of life\"."); test_serde(&m); println!("Msg::Misc variant"); let m = Msg::Misc { what: String::from("roster"), data: vec!["you".to_string(), "me".to_string(), "a dog named foo".to_string()], alt: String::from("you, me, and a dog named foo"), }; test_serde(&m); } }
// when a user changes his or her name
random_line_split
proto2.rs
/*! proto2.rs A newer, simpler, more easily-extensible `grel` protocol. As of 2020-12-29, this supersedes the `grel::protocol` lib. 2020-01-23 */ use serde::{Serialize, Deserialize}; /** The `Op` enum represents one of the `Room` operator subcommands. It is used in the `Msg::Op(...)` variant of the `Msg` enum. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Op { /** Open the current Room, allowing in the general public. */ Open, /** Close the current Room to anyone who hasn't been specifically `Invite`d. */ Close, /** Ban the user with the supplied user name from the Room (even if it's `Open`), removing him if he's currently in it. */ Kick(String), /** Allow the user to enter the current room, even if it's `Close`d. Also sends an invitation message to the user. */ Invite(String), /** Transfer operatorship to another user. (The user must be in the current room to receive the mantle of operatorship.) */ Give(String), } /** The `Msg` enum is the structure that gets serialized to JSON and passed along the TCP connections between the server and the various clients. The first four variants, `Text`, `Ping`, `Priv` and `Logout` are bi-directional, being used to send similar information both from client to server and server to client. The next six, `Name`, `Join`, `Query`, `Block`, `Unblock`, and `Op` are for sending commands or requests from the client to the server. The final three, `Info`, `Err`, and `Misc` are used to send information from the server back to the client. */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Msg { // Bi-directional messages /// Typical chunk of text to be exchanged while chatting. Text { #[serde(default)] who: String, lines: Vec<String>, }, /** Request for or acknowledgement of proof of connection. If the server hasn't received any data from the client in a while, it will send one of these. The client can then respond with one to indicate it's still connected. */ Ping, /** A private message delivered only to the recipient. When sent from the client to the server, `who` should be an identifier for the _recipient_; when sent server to client, `who` is the name of the source. */ Priv { who: String, text: String, }, /** A message from the client indicating it would like to disconnect cleanly from the server; in response, the server will send back one of these with a message and close the connection. */ Logout(String), // Client-to-server messages. /// Name-change request from client to server. Name(String), /// Client request to create/join a room. Join(String), /** A request from the client to the server for some type of information, like a list of users matching a pattern. */ Query { what: String, arg: String, }, /** A request from the client to block messages (including private messages) from the user with the matching name. */ Block(String), /** A request to unblock the given user. */ Unblock(String), /** One of the Room operator subcommands. See the `proto2::Op` enum. */ Op(Op), // Server-to-client messages. /** A non-error, miscellaneously-informative message sent form the server to the client. */ Info(String), /** A message from the server to the client indicating the client has done something wrong, like sent an invalid message. */ Err(String), /** The `Misc` variant represents information that the client may want to display in a structured manner (and not just as an unadorned line of text). For any given "type" of `Misc` message, the client is free to either implement its own form of displaying the information, or to just use the contents of the provided `.alt` field. Current Misc variants (with example field values): ``` ignore // in response to a Query { what: "roster".... } Misc { what: "roster".to_string(), data: vec!["user1".to_string(), "user2".to_string()], #... alt: "[ comma-delimited list of Users in room ]".to_string(), }; // when a user joins a channel Misc { what: "join".to_string(), data: vec!["grel user".to_string(), "room name".to_string()], alt: "grel user joins [room name]".to_string(), }; // when a user logs out or leaves a channel Misc { what: "leave".to_string(), data: vec!["grel user".to_string(), "moved to another room".to_string()], alt: "grel user moved to another room".to_string(), }; // when a user is kicked from the current channel Misc { what: "kick_other".to_string(), data: vec!["Bad User".to_string(), "This Room".to_string()], alt: "Bad User has been kicked from This Room.".to_string(), }; // When YOU are kicked from the current channel. Misc { what: "kick_you".to_string(), data: vec!["This Room".to_string()], alt: "You have been kicked from This Room.".to_string(), }; // when a user changes his or her name Misc { what: "name".to_string(), data: vec!["old name".to_string(), "new name".to_string()], alt: "\"old name\" is now known as \"new name\".".to_string(), }; // when the Room operator changes Misc { what: "new_op".to_string(), data: ["New Operator".to_string(), "This Room".to_string()], alt: "New Operator is now the operator of This Room".to_string(), }; // in response to a Query { what: "addr",... } Misc { what: "addr".to_string(), data: vec!["127.0.0.1:33333".to_string()] alt: "Your public address is 127.0.0.1:33333".to_string(), }; // in response to a Query { what: "who",... } Misc { what: "who".to_string(), data: vec!["user1".to_string(), "user2".to_string(),... ], alt: "Matching names: \"user1\", \"user2\",...".to_string(), }; // echoes a private message back to the sender Misc { what: "priv_echo".to_string(), data: vec!["recipient".to_string(), "text of message".to_string()], alt: "$ You @ Recipient: text of message".to_string() }; ``` */ Misc { what: String, data: Vec<String>, alt: String, }, } /** Some of these are convenience functions for instantiating certain variants. */ impl Msg { pub fn logout(msg: &str) -> Msg { Msg::Logout(String::from(msg)) } pub fn info(msg: &str) -> Msg { Msg::Info(String::from(msg)) } pub fn err(msg: &str) -> Msg { Msg::Err(String::from(msg)) } /// Return a JSON-encoded version of a `Msg`. pub fn bytes(&self) -> Vec<u8> { serde_json::to_vec_pretty(&self).unwrap() } /** Return whether a Msg should count against a user's "byte quota" (for rate limiting). Generally, this is anything that causes "noise". */ pub fn counts(&self) -> bool { match self { Msg::Text { who: _, lines: _ } => true, Msg::Priv { who: _, text: _ } => true, Msg::Name(_) => true, Msg::Join(_) => true, _ => false, } } } /** The `Endpoint` enum specifies sources and destinations in an `Env`. `User`s and `Room`s are stored in respective `HashMap`s with unique `u64` IDs as keys. */ #[derive(Copy, Clone, Debug)] pub enum Endpoint { User(u64), Room(u64), Server, All, } /** An `Env` (-elope) wraps the bytes of a JSON-encoded `Msg`, along with unambiguous source and destination information. This metadata is necessary because the encoded JSON is opaque to the server without decoding it. */ #[derive(Clone, Debug)] pub struct Env { pub source: Endpoint, pub dest: Endpoint, data: Vec<u8>, } impl Env { /** Wrap a `Msg`. */ pub fn new(from: Endpoint, to: Endpoint, msg: &Msg) -> Env { Env { source: from, dest: to, data: msg.bytes(), } } /** Get a reference to the encoded bytes. */ pub fn bytes(&self) -> &[u8] { &self.data } /** Consume the `Env`, returning the owned vector of bytes. */ pub fn into_bytes(self) -> Vec<u8> { self.data } } #[cfg(test)] mod test { use super::*; fn
(m: &Msg) { let stringd = serde_json::to_string_pretty(m).unwrap(); println!("{}\n", &stringd); let newm: Msg = serde_json::from_str(&stringd).unwrap(); assert_eq!(*m, newm); } #[test] fn visual_serde() { println!("Msg::Text variant"); let m = Msg::Text { who: String::from("gre luser"), lines: vec!["This is a first line of text.".to_string(), "Following the first is a second line of text.".to_string()], }; test_serde(&m); println!("Msg::Ping variant"); let m = Msg::Ping; test_serde(&m); println!("Msg::Priv variant"); let m = Msg::Priv { who: String::from("naggum"), text: String::from("XML is bascially the Hitler of protocols."), }; test_serde(&m); println!("Msg::Logout variant"); let m = Msg::logout("You have been logged out because you touch yourself at night."); test_serde(&m); println!("Msg::Name variant"); let m = Msg::Name(String::from("New Lewser")); test_serde(&m); println!("Msg::Join variant"); let m = Msg::Join(String::from("Gay Space Communism")); test_serde(&m); println!("Msg::Query variant"); let m = Msg::Query { what: String::from("who"), arg: String::from("fink"), }; test_serde(&m); println!("Msg::Block variant"); let m = Msg::Block(String::from("Dickweed User")); test_serde(&m); println!("Msg::Unblock variant"); let m = Msg::Unblock(String::from("Misunderstood User")); test_serde(&m); println!("A couple of Msg::Op variants"); let m = Msg::Op(Op::Close); test_serde(&m); let m = Msg::Op(Op::Kick("FpS DoUgG".to_string())); test_serde(&m); println!("Msg::Info variant"); let m = Msg::info("Santa isn't real."); test_serde(&m); println!("Msg::Err variant"); let m = Msg::err("Unrecognized Query \"meaning of life\"."); test_serde(&m); println!("Msg::Misc variant"); let m = Msg::Misc { what: String::from("roster"), data: vec!["you".to_string(), "me".to_string(), "a dog named foo".to_string()], alt: String::from("you, me, and a dog named foo"), }; test_serde(&m); } }
test_serde
identifier_name
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the way that you interact with each of them is very different. //! //! JavaScript's `Promise` follows a completion-based model. You register //! callbacks on a promise, and the runtime invokes each of the registered //! callbacks (there may be many!) when the promise is resolved with a //! value. You build larger asynchronous computations by chaining promises; //! registering a callback with a promise returns a new promise of that //! callback's result. Dependencies between promises are managed by the runtime. //! //! Rust's `Future` follows a readiness-based model. You define a `poll` method //! that either returns the future's value if it is ready, or a sentinel that //! says the future's value is not ready yet. You build larger asynchronous //! computations by defining (or using existing) combinators that wrap some //! inner future (or futures). These combinators delegate polling to the inner //! future, and once the inner future's value is ready, perform their //! computation on the value, and return the transformed result. Dependencies //! between futures are managed by the futures themselves, while scheduling //! polling is the runtime's responsibility. //! //! To translate between futures and promises we take two different approaches //! for each direction, by necessity. //! //! To treat a Rust `Future` as a JavaScript `Promise`, we define a `Future` //! combinator called `Future2Promise`. It takes a fresh, un-resolved `Promise` //! object, and an inner future upon construction. It's `poll` method delegates //! to the inner future's `poll`, and once the inner future's value is ready, it //! resolves the promise with the ready value, and the JavaScript runtime //! ensures that the promise's registered callbacks are invoked appropriately. //! //! To treat a JavaScript `Promise` as a Rust `Future`, we register a callback //! to the promise that sends the resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is that the runtime scheduling the polling of //! Rust `Future`s (`tokio`) still knows which futures to poll despite it only //! seeing half the picture now. I say "half the picture" because dependencies //! that would otherwise live fully within the futures ecosystem are now hidden //! in promises inside the JavaScript runtime. //! //! First, we must understand how `tokio` schedules polling. It is not busy //! spinning and calling `poll` continuously in a loop. `tokio` maintains a set //! of "root" futures. These are the futures passed to `Core::run` and //! `Handle::spawn` directly. When `tokio` polls a "root" future, that `poll` //! call will transitively reach down and call `poll` on "leaf" futures that //! wrap file descriptors and sockets and such things. It is these "leaf" //! futures' responsibilty to use OS APIs to trigger wake ups when new data is //! available on a socket or what have you, and then it is `tokio`'s //! responsibilty to map that wake up back to which "root" future it should poll //! again. If the "leaf" futures do not properly register to be woken up again, //! `tokio` will never poll that "root" future again, effectively dead locking //! it. //! //! So we must ensure that our `Promise`-backed futures will always be polled //! again by making sure that they have proper "leaf" futures. Luckily, the //! receiver half of a one-shot channel is such a "leaf" future that properly //! registers future wake ups. If instead, for example, we tried directly //! checking the promise's state in `poll` with JSAPI methods, we *wouldn't* //! register any wake ups, `tokio` would never `poll` the future again, and the //! future would dead lock. use super::{Error, ErrorKind}; use futures::{self, Async, Future, Poll, Select}; use futures::sync::oneshot; use future_ext::{ready, FutureExt}; use gc_roots::GcRoot; use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::glue::ReportError; use js::jsapi; use js::jsval; use js::rust::Runtime as JsRuntime; use state_machine_future::RentToOwn; use std::marker::PhantomData; use std::os::raw; use std::ptr; use task; use void::Void; type GenericVoid<T> = (Void, PhantomData<T>); /// A future that resolves a promise with its inner future's value when ready. #[derive(StateMachineFuture)] #[allow(dead_code)] enum Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { /// Initially, we are waiting on the inner future to be ready or error. #[state_machine_future(start, transitions(Finished, NotifyingOfError))] WaitingOnInner { future: F, promise: GcRoot<*mut jsapi::JSObject>, }, /// If we encountered an error that needs to propagate, we must send it to /// the task. #[state_machine_future(transitions(Finished))] NotifyingOfError { notify: futures::sink::Send<futures::sync::mpsc::Sender<task::TaskMessage>>, phantom: PhantomData<F>, }, /// All done. #[state_machine_future(ready)] Finished(PhantomData<F>), /// We explicitly handle all errors, so make `Future::Error` impossible to /// construct. #[state_machine_future(error)] Impossible(GenericVoid<F>), } impl<F> PollFuture2Promise<F> for Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { fn
<'a>( waiting: &'a mut RentToOwn<'a, WaitingOnInner<F>>, ) -> Poll<AfterWaitingOnInner<F>, GenericVoid<F>> { let error = match waiting.future.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } Ok(Async::Ready(t)) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); t.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::ResolvePromise( cx, promise.handle(), val.handle() )); if let Err(e) = task::drain_micro_task_queue() { e } else { return ready(Finished(PhantomData)); } } } Err(error) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); error.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::RejectPromise(cx, promise.handle(), val.handle())); if let Err(e) = task::drain_micro_task_queue() { e } else { return ready(Finished(PhantomData)); } } } }; let msg = task::TaskMessage::UnhandledRejectedPromise { error }; ready(NotifyingOfError { notify: task::this_task().send(msg), phantom: PhantomData, }) } fn poll_notifying_of_error<'a>( notification: &'a mut RentToOwn<'a, NotifyingOfError<F>>, ) -> Poll<AfterNotifyingOfError<F>, GenericVoid<F>> { match notification.notify.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } // The only way we can get an error here is if we lost a // race between notifying the task of an error and the task // finishing. Err(_) | Ok(Async::Ready(_)) => ready(Finished(PhantomData)), } } } /// Convert a Rust `Future` into a JavaScript `Promise`. /// /// The `Future` is spawned onto the current thread's `tokio` event loop. pub fn future_to_promise<F, T, E>(future: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + Future<Item = T, Error = E>, T:'static + ToJSValConvertible, E:'static + ToJSValConvertible, { let cx = JsRuntime::get(); rooted!(in(cx) let executor = ptr::null_mut()); rooted!(in(cx) let proto = ptr::null_mut()); rooted!(in(cx) let promise = unsafe { jsapi::JS::NewPromiseObject( cx, executor.handle(), proto.handle() ) }); assert!(!promise.get().is_null()); let promise = GcRoot::new(promise.get()); let future = Future2Promise::start(future, promise.clone()).ignore_results(); task::event_loop().spawn(future); promise } const CLOSURE_SLOT: usize = 0; // JSNative that forwards the call `f`. unsafe extern "C" fn trampoline<F>( cx: *mut jsapi::JSContext, argc: raw::c_uint, vp: *mut jsapi::JS::Value, ) -> bool where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let args = jsapi::JS::CallArgs::from_vp(vp, argc); rooted!(in(cx) let callee = args.callee()); let private = jsapi::js::GetFunctionNativeReserved(callee.get(), CLOSURE_SLOT); let f = (*private).to_private() as *mut F; if f.is_null() { ReportError(cx, b"May only be called once\0".as_ptr() as *const _); return false; } let private = jsval::PrivateValue(ptr::null()); jsapi::js::SetFunctionNativeReserved(callee.get(), CLOSURE_SLOT, &private); let f = Box::from_raw(f); f(cx, &args) } /// This is unsafe because the resulting function object will _not_ trace `f`'s /// closed over values. Don't close over GC things! unsafe fn make_js_fn<F>(f: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let cx = JsRuntime::get(); rooted!(in(cx) let func = jsapi::js::NewFunctionWithReserved( cx, Some(trampoline::<F>), 0, // nargs 0, // flags ptr::null_mut() // name )); assert!(!func.get().is_null()); let private = Box::new(f); let private = jsval::PrivateValue(Box::into_raw(private) as *const _); jsapi::js::SetFunctionNativeReserved(func.get() as *mut _, CLOSURE_SLOT, &private); GcRoot::new(func.get() as *mut jsapi::JSObject) } type ResultReceiver<T, E> = oneshot::Receiver<super::Result<Result<T, E>>>; /// A future of either a JavaScript promise's resolution `T` or rejection `E`. pub struct Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { inner: Select<ResultReceiver<T, E>, ResultReceiver<T, E>>, } impl<T, E> ::std::fmt::Debug for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "Promise2Future {{.. }}") } } impl<T, E> Future for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { type Item = Result<T, E>; type Error = super::Error; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { match self.inner.poll() { Err((oneshot::Canceled, _)) => { Err(ErrorKind::JavaScriptPromiseCollectedWithoutSettling.into()) } Ok(Async::NotReady) => Ok(Async::NotReady), // One of the handlers was called, but then we encountered an error // converting the value from JS into Rust or something like that. Ok(Async::Ready((Err(e), _))) => Err(e), Ok(Async::Ready((Ok(result), _))) => Ok(Async::Ready(result)), } } } /// Convert the given JavaScript `Promise` object into a future. /// /// The resulting future is of either an `Ok(T)` if the promise gets resolved, /// or an `Err(E)` if the promise is rejected. /// /// Failure to convert the resolution or rejection JavaScript value into a `T` /// or `E` will cause the resulting future's `poll` to return an error. /// /// If the promise object is reclaimed by the garbage collector without being /// resolved or rejected, then the resulting future's `poll` will return an /// error of kind `ErrorKind::JavaScriptPromiseCollectedWithoutSettling`. pub fn promise_to_future<T, E>(promise: &GcRoot<*mut jsapi::JSObject>) -> Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { unsafe { let cx = JsRuntime::get(); let (resolve_sender, resolve_receiver) = oneshot::channel(); let on_resolve = make_js_fn(move |cx, args| { match T::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = resolve_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = resolve_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = resolve_sender.send(Ok(Ok(t))); } } true }); let (reject_sender, reject_receiver) = oneshot::channel(); let on_reject = make_js_fn(move |cx, args| { match E::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = reject_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = reject_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = reject_sender.send(Ok(Err(t))); } } true }); rooted!(in(cx) let promise = promise.raw()); rooted!(in(cx) let on_resolve = on_resolve.raw()); rooted!(in(cx) let on_reject = on_reject.raw()); assert!(jsapi::JS::AddPromiseReactions( cx, promise.handle(), on_resolve.handle(), on_reject.handle() )); Promise2Future { inner: resolve_receiver.select(reject_receiver), } } }
poll_waiting_on_inner
identifier_name
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the way that you interact with each of them is very different. //! //! JavaScript's `Promise` follows a completion-based model. You register //! callbacks on a promise, and the runtime invokes each of the registered //! callbacks (there may be many!) when the promise is resolved with a //! value. You build larger asynchronous computations by chaining promises; //! registering a callback with a promise returns a new promise of that //! callback's result. Dependencies between promises are managed by the runtime. //! //! Rust's `Future` follows a readiness-based model. You define a `poll` method //! that either returns the future's value if it is ready, or a sentinel that //! says the future's value is not ready yet. You build larger asynchronous //! computations by defining (or using existing) combinators that wrap some //! inner future (or futures). These combinators delegate polling to the inner //! future, and once the inner future's value is ready, perform their //! computation on the value, and return the transformed result. Dependencies //! between futures are managed by the futures themselves, while scheduling //! polling is the runtime's responsibility. //! //! To translate between futures and promises we take two different approaches //! for each direction, by necessity. //! //! To treat a Rust `Future` as a JavaScript `Promise`, we define a `Future` //! combinator called `Future2Promise`. It takes a fresh, un-resolved `Promise` //! object, and an inner future upon construction. It's `poll` method delegates //! to the inner future's `poll`, and once the inner future's value is ready, it //! resolves the promise with the ready value, and the JavaScript runtime //! ensures that the promise's registered callbacks are invoked appropriately. //! //! To treat a JavaScript `Promise` as a Rust `Future`, we register a callback //! to the promise that sends the resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is that the runtime scheduling the polling of //! Rust `Future`s (`tokio`) still knows which futures to poll despite it only //! seeing half the picture now. I say "half the picture" because dependencies //! that would otherwise live fully within the futures ecosystem are now hidden //! in promises inside the JavaScript runtime. //! //! First, we must understand how `tokio` schedules polling. It is not busy //! spinning and calling `poll` continuously in a loop. `tokio` maintains a set //! of "root" futures. These are the futures passed to `Core::run` and //! `Handle::spawn` directly. When `tokio` polls a "root" future, that `poll` //! call will transitively reach down and call `poll` on "leaf" futures that //! wrap file descriptors and sockets and such things. It is these "leaf" //! futures' responsibilty to use OS APIs to trigger wake ups when new data is //! available on a socket or what have you, and then it is `tokio`'s //! responsibilty to map that wake up back to which "root" future it should poll //! again. If the "leaf" futures do not properly register to be woken up again, //! `tokio` will never poll that "root" future again, effectively dead locking //! it. //! //! So we must ensure that our `Promise`-backed futures will always be polled //! again by making sure that they have proper "leaf" futures. Luckily, the //! receiver half of a one-shot channel is such a "leaf" future that properly //! registers future wake ups. If instead, for example, we tried directly //! checking the promise's state in `poll` with JSAPI methods, we *wouldn't* //! register any wake ups, `tokio` would never `poll` the future again, and the //! future would dead lock. use super::{Error, ErrorKind}; use futures::{self, Async, Future, Poll, Select}; use futures::sync::oneshot; use future_ext::{ready, FutureExt}; use gc_roots::GcRoot; use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::glue::ReportError; use js::jsapi; use js::jsval; use js::rust::Runtime as JsRuntime; use state_machine_future::RentToOwn; use std::marker::PhantomData; use std::os::raw; use std::ptr; use task; use void::Void; type GenericVoid<T> = (Void, PhantomData<T>); /// A future that resolves a promise with its inner future's value when ready. #[derive(StateMachineFuture)] #[allow(dead_code)]
enum Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { /// Initially, we are waiting on the inner future to be ready or error. #[state_machine_future(start, transitions(Finished, NotifyingOfError))] WaitingOnInner { future: F, promise: GcRoot<*mut jsapi::JSObject>, }, /// If we encountered an error that needs to propagate, we must send it to /// the task. #[state_machine_future(transitions(Finished))] NotifyingOfError { notify: futures::sink::Send<futures::sync::mpsc::Sender<task::TaskMessage>>, phantom: PhantomData<F>, }, /// All done. #[state_machine_future(ready)] Finished(PhantomData<F>), /// We explicitly handle all errors, so make `Future::Error` impossible to /// construct. #[state_machine_future(error)] Impossible(GenericVoid<F>), } impl<F> PollFuture2Promise<F> for Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { fn poll_waiting_on_inner<'a>( waiting: &'a mut RentToOwn<'a, WaitingOnInner<F>>, ) -> Poll<AfterWaitingOnInner<F>, GenericVoid<F>> { let error = match waiting.future.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } Ok(Async::Ready(t)) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); t.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::ResolvePromise( cx, promise.handle(), val.handle() )); if let Err(e) = task::drain_micro_task_queue() { e } else { return ready(Finished(PhantomData)); } } } Err(error) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); error.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::RejectPromise(cx, promise.handle(), val.handle())); if let Err(e) = task::drain_micro_task_queue() { e } else { return ready(Finished(PhantomData)); } } } }; let msg = task::TaskMessage::UnhandledRejectedPromise { error }; ready(NotifyingOfError { notify: task::this_task().send(msg), phantom: PhantomData, }) } fn poll_notifying_of_error<'a>( notification: &'a mut RentToOwn<'a, NotifyingOfError<F>>, ) -> Poll<AfterNotifyingOfError<F>, GenericVoid<F>> { match notification.notify.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } // The only way we can get an error here is if we lost a // race between notifying the task of an error and the task // finishing. Err(_) | Ok(Async::Ready(_)) => ready(Finished(PhantomData)), } } } /// Convert a Rust `Future` into a JavaScript `Promise`. /// /// The `Future` is spawned onto the current thread's `tokio` event loop. pub fn future_to_promise<F, T, E>(future: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + Future<Item = T, Error = E>, T:'static + ToJSValConvertible, E:'static + ToJSValConvertible, { let cx = JsRuntime::get(); rooted!(in(cx) let executor = ptr::null_mut()); rooted!(in(cx) let proto = ptr::null_mut()); rooted!(in(cx) let promise = unsafe { jsapi::JS::NewPromiseObject( cx, executor.handle(), proto.handle() ) }); assert!(!promise.get().is_null()); let promise = GcRoot::new(promise.get()); let future = Future2Promise::start(future, promise.clone()).ignore_results(); task::event_loop().spawn(future); promise } const CLOSURE_SLOT: usize = 0; // JSNative that forwards the call `f`. unsafe extern "C" fn trampoline<F>( cx: *mut jsapi::JSContext, argc: raw::c_uint, vp: *mut jsapi::JS::Value, ) -> bool where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let args = jsapi::JS::CallArgs::from_vp(vp, argc); rooted!(in(cx) let callee = args.callee()); let private = jsapi::js::GetFunctionNativeReserved(callee.get(), CLOSURE_SLOT); let f = (*private).to_private() as *mut F; if f.is_null() { ReportError(cx, b"May only be called once\0".as_ptr() as *const _); return false; } let private = jsval::PrivateValue(ptr::null()); jsapi::js::SetFunctionNativeReserved(callee.get(), CLOSURE_SLOT, &private); let f = Box::from_raw(f); f(cx, &args) } /// This is unsafe because the resulting function object will _not_ trace `f`'s /// closed over values. Don't close over GC things! unsafe fn make_js_fn<F>(f: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let cx = JsRuntime::get(); rooted!(in(cx) let func = jsapi::js::NewFunctionWithReserved( cx, Some(trampoline::<F>), 0, // nargs 0, // flags ptr::null_mut() // name )); assert!(!func.get().is_null()); let private = Box::new(f); let private = jsval::PrivateValue(Box::into_raw(private) as *const _); jsapi::js::SetFunctionNativeReserved(func.get() as *mut _, CLOSURE_SLOT, &private); GcRoot::new(func.get() as *mut jsapi::JSObject) } type ResultReceiver<T, E> = oneshot::Receiver<super::Result<Result<T, E>>>; /// A future of either a JavaScript promise's resolution `T` or rejection `E`. pub struct Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { inner: Select<ResultReceiver<T, E>, ResultReceiver<T, E>>, } impl<T, E> ::std::fmt::Debug for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "Promise2Future {{.. }}") } } impl<T, E> Future for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { type Item = Result<T, E>; type Error = super::Error; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { match self.inner.poll() { Err((oneshot::Canceled, _)) => { Err(ErrorKind::JavaScriptPromiseCollectedWithoutSettling.into()) } Ok(Async::NotReady) => Ok(Async::NotReady), // One of the handlers was called, but then we encountered an error // converting the value from JS into Rust or something like that. Ok(Async::Ready((Err(e), _))) => Err(e), Ok(Async::Ready((Ok(result), _))) => Ok(Async::Ready(result)), } } } /// Convert the given JavaScript `Promise` object into a future. /// /// The resulting future is of either an `Ok(T)` if the promise gets resolved, /// or an `Err(E)` if the promise is rejected. /// /// Failure to convert the resolution or rejection JavaScript value into a `T` /// or `E` will cause the resulting future's `poll` to return an error. /// /// If the promise object is reclaimed by the garbage collector without being /// resolved or rejected, then the resulting future's `poll` will return an /// error of kind `ErrorKind::JavaScriptPromiseCollectedWithoutSettling`. pub fn promise_to_future<T, E>(promise: &GcRoot<*mut jsapi::JSObject>) -> Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { unsafe { let cx = JsRuntime::get(); let (resolve_sender, resolve_receiver) = oneshot::channel(); let on_resolve = make_js_fn(move |cx, args| { match T::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = resolve_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = resolve_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = resolve_sender.send(Ok(Ok(t))); } } true }); let (reject_sender, reject_receiver) = oneshot::channel(); let on_reject = make_js_fn(move |cx, args| { match E::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = reject_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = reject_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = reject_sender.send(Ok(Err(t))); } } true }); rooted!(in(cx) let promise = promise.raw()); rooted!(in(cx) let on_resolve = on_resolve.raw()); rooted!(in(cx) let on_reject = on_reject.raw()); assert!(jsapi::JS::AddPromiseReactions( cx, promise.handle(), on_resolve.handle(), on_reject.handle() )); Promise2Future { inner: resolve_receiver.select(reject_receiver), } } }
random_line_split
promise_future_glue.rs
//! Gluing Rust's `Future` and JavaScript's `Promise` together. //! //! JavaScript's `Promise` and Rust's `Future` are two abstractions with the //! same goal: asynchronous programming with eventual values. Both `Promise`s //! and `Future`s represent a value that may or may not have been computed //! yet. However, the way that you interact with each of them is very different. //! //! JavaScript's `Promise` follows a completion-based model. You register //! callbacks on a promise, and the runtime invokes each of the registered //! callbacks (there may be many!) when the promise is resolved with a //! value. You build larger asynchronous computations by chaining promises; //! registering a callback with a promise returns a new promise of that //! callback's result. Dependencies between promises are managed by the runtime. //! //! Rust's `Future` follows a readiness-based model. You define a `poll` method //! that either returns the future's value if it is ready, or a sentinel that //! says the future's value is not ready yet. You build larger asynchronous //! computations by defining (or using existing) combinators that wrap some //! inner future (or futures). These combinators delegate polling to the inner //! future, and once the inner future's value is ready, perform their //! computation on the value, and return the transformed result. Dependencies //! between futures are managed by the futures themselves, while scheduling //! polling is the runtime's responsibility. //! //! To translate between futures and promises we take two different approaches //! for each direction, by necessity. //! //! To treat a Rust `Future` as a JavaScript `Promise`, we define a `Future` //! combinator called `Future2Promise`. It takes a fresh, un-resolved `Promise` //! object, and an inner future upon construction. It's `poll` method delegates //! to the inner future's `poll`, and once the inner future's value is ready, it //! resolves the promise with the ready value, and the JavaScript runtime //! ensures that the promise's registered callbacks are invoked appropriately. //! //! To treat a JavaScript `Promise` as a Rust `Future`, we register a callback //! to the promise that sends the resolution value over a one-shot //! channel. One-shot channels are split into their two halves: sender and //! receiver. The sender half moves into the callback, but the receiver half is //! a future, and it represents the future resolution value of the original //! promise. //! //! The final concern to address is that the runtime scheduling the polling of //! Rust `Future`s (`tokio`) still knows which futures to poll despite it only //! seeing half the picture now. I say "half the picture" because dependencies //! that would otherwise live fully within the futures ecosystem are now hidden //! in promises inside the JavaScript runtime. //! //! First, we must understand how `tokio` schedules polling. It is not busy //! spinning and calling `poll` continuously in a loop. `tokio` maintains a set //! of "root" futures. These are the futures passed to `Core::run` and //! `Handle::spawn` directly. When `tokio` polls a "root" future, that `poll` //! call will transitively reach down and call `poll` on "leaf" futures that //! wrap file descriptors and sockets and such things. It is these "leaf" //! futures' responsibilty to use OS APIs to trigger wake ups when new data is //! available on a socket or what have you, and then it is `tokio`'s //! responsibilty to map that wake up back to which "root" future it should poll //! again. If the "leaf" futures do not properly register to be woken up again, //! `tokio` will never poll that "root" future again, effectively dead locking //! it. //! //! So we must ensure that our `Promise`-backed futures will always be polled //! again by making sure that they have proper "leaf" futures. Luckily, the //! receiver half of a one-shot channel is such a "leaf" future that properly //! registers future wake ups. If instead, for example, we tried directly //! checking the promise's state in `poll` with JSAPI methods, we *wouldn't* //! register any wake ups, `tokio` would never `poll` the future again, and the //! future would dead lock. use super::{Error, ErrorKind}; use futures::{self, Async, Future, Poll, Select}; use futures::sync::oneshot; use future_ext::{ready, FutureExt}; use gc_roots::GcRoot; use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::glue::ReportError; use js::jsapi; use js::jsval; use js::rust::Runtime as JsRuntime; use state_machine_future::RentToOwn; use std::marker::PhantomData; use std::os::raw; use std::ptr; use task; use void::Void; type GenericVoid<T> = (Void, PhantomData<T>); /// A future that resolves a promise with its inner future's value when ready. #[derive(StateMachineFuture)] #[allow(dead_code)] enum Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { /// Initially, we are waiting on the inner future to be ready or error. #[state_machine_future(start, transitions(Finished, NotifyingOfError))] WaitingOnInner { future: F, promise: GcRoot<*mut jsapi::JSObject>, }, /// If we encountered an error that needs to propagate, we must send it to /// the task. #[state_machine_future(transitions(Finished))] NotifyingOfError { notify: futures::sink::Send<futures::sync::mpsc::Sender<task::TaskMessage>>, phantom: PhantomData<F>, }, /// All done. #[state_machine_future(ready)] Finished(PhantomData<F>), /// We explicitly handle all errors, so make `Future::Error` impossible to /// construct. #[state_machine_future(error)] Impossible(GenericVoid<F>), } impl<F> PollFuture2Promise<F> for Future2Promise<F> where F: Future, <F as Future>::Item: ToJSValConvertible, <F as Future>::Error: ToJSValConvertible, { fn poll_waiting_on_inner<'a>( waiting: &'a mut RentToOwn<'a, WaitingOnInner<F>>, ) -> Poll<AfterWaitingOnInner<F>, GenericVoid<F>>
e } else { return ready(Finished(PhantomData)); } } } Err(error) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); error.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::RejectPromise(cx, promise.handle(), val.handle())); if let Err(e) = task::drain_micro_task_queue() { e } else { return ready(Finished(PhantomData)); } } } }; let msg = task::TaskMessage::UnhandledRejectedPromise { error }; ready(NotifyingOfError { notify: task::this_task().send(msg), phantom: PhantomData, }) } fn poll_notifying_of_error<'a>( notification: &'a mut RentToOwn<'a, NotifyingOfError<F>>, ) -> Poll<AfterNotifyingOfError<F>, GenericVoid<F>> { match notification.notify.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } // The only way we can get an error here is if we lost a // race between notifying the task of an error and the task // finishing. Err(_) | Ok(Async::Ready(_)) => ready(Finished(PhantomData)), } } } /// Convert a Rust `Future` into a JavaScript `Promise`. /// /// The `Future` is spawned onto the current thread's `tokio` event loop. pub fn future_to_promise<F, T, E>(future: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + Future<Item = T, Error = E>, T:'static + ToJSValConvertible, E:'static + ToJSValConvertible, { let cx = JsRuntime::get(); rooted!(in(cx) let executor = ptr::null_mut()); rooted!(in(cx) let proto = ptr::null_mut()); rooted!(in(cx) let promise = unsafe { jsapi::JS::NewPromiseObject( cx, executor.handle(), proto.handle() ) }); assert!(!promise.get().is_null()); let promise = GcRoot::new(promise.get()); let future = Future2Promise::start(future, promise.clone()).ignore_results(); task::event_loop().spawn(future); promise } const CLOSURE_SLOT: usize = 0; // JSNative that forwards the call `f`. unsafe extern "C" fn trampoline<F>( cx: *mut jsapi::JSContext, argc: raw::c_uint, vp: *mut jsapi::JS::Value, ) -> bool where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let args = jsapi::JS::CallArgs::from_vp(vp, argc); rooted!(in(cx) let callee = args.callee()); let private = jsapi::js::GetFunctionNativeReserved(callee.get(), CLOSURE_SLOT); let f = (*private).to_private() as *mut F; if f.is_null() { ReportError(cx, b"May only be called once\0".as_ptr() as *const _); return false; } let private = jsval::PrivateValue(ptr::null()); jsapi::js::SetFunctionNativeReserved(callee.get(), CLOSURE_SLOT, &private); let f = Box::from_raw(f); f(cx, &args) } /// This is unsafe because the resulting function object will _not_ trace `f`'s /// closed over values. Don't close over GC things! unsafe fn make_js_fn<F>(f: F) -> GcRoot<*mut jsapi::JSObject> where F:'static + FnOnce(*mut jsapi::JSContext, &jsapi::JS::CallArgs) -> bool, { let cx = JsRuntime::get(); rooted!(in(cx) let func = jsapi::js::NewFunctionWithReserved( cx, Some(trampoline::<F>), 0, // nargs 0, // flags ptr::null_mut() // name )); assert!(!func.get().is_null()); let private = Box::new(f); let private = jsval::PrivateValue(Box::into_raw(private) as *const _); jsapi::js::SetFunctionNativeReserved(func.get() as *mut _, CLOSURE_SLOT, &private); GcRoot::new(func.get() as *mut jsapi::JSObject) } type ResultReceiver<T, E> = oneshot::Receiver<super::Result<Result<T, E>>>; /// A future of either a JavaScript promise's resolution `T` or rejection `E`. pub struct Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { inner: Select<ResultReceiver<T, E>, ResultReceiver<T, E>>, } impl<T, E> ::std::fmt::Debug for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "Promise2Future {{.. }}") } } impl<T, E> Future for Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { type Item = Result<T, E>; type Error = super::Error; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { match self.inner.poll() { Err((oneshot::Canceled, _)) => { Err(ErrorKind::JavaScriptPromiseCollectedWithoutSettling.into()) } Ok(Async::NotReady) => Ok(Async::NotReady), // One of the handlers was called, but then we encountered an error // converting the value from JS into Rust or something like that. Ok(Async::Ready((Err(e), _))) => Err(e), Ok(Async::Ready((Ok(result), _))) => Ok(Async::Ready(result)), } } } /// Convert the given JavaScript `Promise` object into a future. /// /// The resulting future is of either an `Ok(T)` if the promise gets resolved, /// or an `Err(E)` if the promise is rejected. /// /// Failure to convert the resolution or rejection JavaScript value into a `T` /// or `E` will cause the resulting future's `poll` to return an error. /// /// If the promise object is reclaimed by the garbage collector without being /// resolved or rejected, then the resulting future's `poll` will return an /// error of kind `ErrorKind::JavaScriptPromiseCollectedWithoutSettling`. pub fn promise_to_future<T, E>(promise: &GcRoot<*mut jsapi::JSObject>) -> Promise2Future<T, E> where T:'static + FromJSValConvertible<Config = ()>, E:'static + FromJSValConvertible<Config = ()>, { unsafe { let cx = JsRuntime::get(); let (resolve_sender, resolve_receiver) = oneshot::channel(); let on_resolve = make_js_fn(move |cx, args| { match T::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = resolve_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = resolve_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = resolve_sender.send(Ok(Ok(t))); } } true }); let (reject_sender, reject_receiver) = oneshot::channel(); let on_reject = make_js_fn(move |cx, args| { match E::from_jsval(cx, args.get(0), ()) { Err(()) => { let err = Error::from_cx(cx); let _ = reject_sender.send(Err(err)); } Ok(ConversionResult::Failure(s)) => { let err = Err(ErrorKind::Msg(s.to_string()).into()); let _ = reject_sender.send(err); } Ok(ConversionResult::Success(t)) => { let _ = reject_sender.send(Ok(Err(t))); } } true }); rooted!(in(cx) let promise = promise.raw()); rooted!(in(cx) let on_resolve = on_resolve.raw()); rooted!(in(cx) let on_reject = on_reject.raw()); assert!(jsapi::JS::AddPromiseReactions( cx, promise.handle(), on_resolve.handle(), on_reject.handle() )); Promise2Future { inner: resolve_receiver.select(reject_receiver), } } }
{ let error = match waiting.future.poll() { Ok(Async::NotReady) => { return Ok(Async::NotReady); } Ok(Async::Ready(t)) => { let cx = JsRuntime::get(); unsafe { rooted!(in(cx) let mut val = jsval::UndefinedValue()); t.to_jsval(cx, val.handle_mut()); rooted!(in(cx) let promise = waiting.promise.raw()); assert!(jsapi::JS::ResolvePromise( cx, promise.handle(), val.handle() )); if let Err(e) = task::drain_micro_task_queue() {
identifier_body
lib.rs
//! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation. //! //! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6). //! //! There are two APIs provided: one for single-chunk hashing and one for hashing of multiple data segments. //! //! # Examples //! //! Hashing a single chunk of data with a 256-bit MD6 hash function, then verifying the result. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result = [0; 32]; //! md6::hash(256, b"The lazy fox jumps over the lazy dog", &mut result).unwrap(); //! //! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), //! vec![0xE4, 0x55, 0x51, 0xAA, 0xE2, 0x66, 0xE1, 0x48, //! 0x2A, 0xC9, 0x8E, 0x24, 0x22, 0x9B, 0x3E, 0x90, //! 0xDC, 0x06, 0x61, 0x77, 0xF8, 0xFB, 0x1A, 0x52, //! 0x6E, 0x9D, 0xA2, 0xCC, 0x95, 0x71, 0x97, 0xAA]); //! ``` //! //! Hashing multiple chunks of data with a 512-bit MD6 hash function, then verifying the result. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result = [0; 64]; //! let mut state = Md6::new(512).unwrap(); //! //! state.update("Zażółć ".as_bytes()); //! state.update("gęślą ".as_bytes()); //! state.update("jaźń".as_bytes()); //! //! state.finalise(&mut result); //! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), //! vec![0x92, 0x4E, 0x91, 0x6A, 0x01, 0x2C, 0x1A, 0x8D, //! 0x0F, 0xB7, 0x9A, 0x4A, 0xD4, 0x9C, 0x55, 0x5E, //! 0xBD, 0xCA, 0x59, 0xB8, 0x1B, 0x4C, 0x13, 0x41, //! 0x2E, 0x32, 0xA5, 0xC9, 0x3B, 0x61, 0xAD, 0xB8, //! 0x4D, 0xB3, 0xF9, 0x0C, 0x03, 0x51, 0xB2, 0x9E, //! 0x7B, 0xAE, 0x46, 0x9F, 0x8D, 0x60, 0x5D, 0xED, //! 0xFF, 0x51, 0x72, 0xDE, 0xA1, 0x6F, 0x00, 0xF7, //! 0xB4, 0x82, 0xEF, 0x87, 0xED, 0x77, 0xD9, 0x1A]); //! ``` //! //! Comparing result of single- and multi-chunk hash methods hashing the same effective message with a 64-bit MD6 hash //! function. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result_multi = [0; 8]; //! let mut result_single = [0; 8]; //! //! let mut state = Md6::new(64).unwrap(); //! state.update("Zażółć ".as_bytes()); //! state.update("gęślą ".as_bytes()); //! state.update("jaźń".as_bytes()); //! state.finalise(&mut result_multi); //! //! md6::hash(64, "Zażółć gęślą jaźń".as_bytes(), &mut result_single).unwrap(); //! //! assert_eq!(Vec::from_iter(result_multi.iter().map(|&i| i)), //! Vec::from_iter(result_single.iter().map(|&i| i))); //! ``` //! //! # Special thanks //! //! To all who support further development on [Patreon](https://patreon.com/nabijaczleweli), in particular: //! //! * ThePhD //! * Embark Studios extern crate libc; mod native; use std::error::Error; use std::fmt; use std::io; /// Helper result type containing `Md6Error`. pub type Result<T> = std::result::Result<T, Md6Error>; /// Hash all data in one fell swoop. /// /// Refer to individual functions for extended documentation. /// /// # Example /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result_256 = [0; 32]; /// let mut result_512 = [0; 64]; /// /// md6::hash(256, &[], &mut result_256).unwrap(); /// md6::hash(512, &[], &mut result_512).unwrap(); /// /// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)), /// vec![0xBC, 0xA3, 0x8B, 0x24, 0xA8, 0x04, 0xAA, 0x37, /// 0xD8, 0x21, 0xD3, 0x1A, 0xF0, 0x0F, 0x55, 0x98, /// 0x23, 0x01, 0x22, 0xC5, 0xBB, 0xFC, 0x4C, 0x4A, /// 0xD5, 0xED, 0x40, 0xE4, 0x25, 0x8F, 0x04, 0xCA]); /// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)), /// vec![0x6B, 0x7F, 0x33, 0x82, 0x1A, 0x2C, 0x06, 0x0E, /// 0xCD, 0xD8, 0x1A, 0xEF, 0xDD, 0xEA, 0x2F, 0xD3, /// 0xC4, 0x72, 0x02, 0x70, 0xE1, 0x86, 0x54, 0xF4, /// 0xCB, 0x08, 0xEC, 0xE4, 0x9C, 0xCB, 0x46, 0x9F, /// 0x8B, 0xEE, 0xEE, 0x7C, 0x83, 0x12, 0x06, 0xBD, /// 0x57, 0x7F, 0x9F, 0x26, 0x30, 0xD9, 0x17, 0x79, /// 0x79, 0x20, 0x3A, 0x94, 0x89, 0xE4, 0x7E, 0x04, /// 0xDF, 0x4E, 0x6D, 0xEA, 0xA0, 0xF8, 0xE0, 0xC0]); /// ``` pub fn hash(hashbitlen: i32, data: &[u8], hashval: &mut [u8]) -> Result<()> { match unsafe { native::MD6_Hash_Hash(hashbitlen, data.as_ptr(), data.len() as u64 * 8, hashval.as_mut_ptr()) } { 0 => Ok(()), e => Err(Md6Error::from(e)), } } /// Hashing state for multiple data sets. /// /// # Example /// /// Hashing a string split into multiple chunks. /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut state = Md6::new(256).unwrap(); /// /// state.update(b"Abolish "); /// state.update(b"the "); /// state.update(b"bourgeoisie"); /// state.update(b"!"); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0x49, 0x23, 0xE7, 0xB0, 0x53, 0x32, 0x05, 0xB0, /// 0x25, 0xC5, 0xD4, 0xDB, 0x37, 0xB8, 0x99, 0x12, /// 0x16, 0x2E, 0xFD, 0xF4, 0xDA, 0xC2, 0x2C, 0xFF, /// 0xE6, 0x27, 0xF1, 0x11, 0xEC, 0x05, 0x2F, 0xB5]); /// ``` /// /// A `Write` implementation is also provided: /// /// ``` /// # use std::iter::FromIterator; /// # use md6::Md6; /// # use std::io; /// let mut state = Md6::new(256).unwrap(); /// io::copy(&mut &b"The lazy fox jumps over the lazy dog."[..], &mut state).unwrap(); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0x06, 0x60, 0xBB, 0x89, 0x85, 0x06, 0xE4, 0xD9, /// 0x29, 0x8C, 0xD1, 0xB0, 0x40, 0x73, 0x49, 0x60, /// 0x47, 0x3E, 0x25, 0xA4, 0x9D, 0x52, 0x34, 0xBB, /// 0x2A, 0xCA, 0x31, 0x57, 0xD1, 0xAF, 0x27, 0xAA]); /// ``` pub struct Md6 { raw_state: native::FFIHashState, } /// Some functions in the library can fail, this enum represents all the possible ways they can. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Md6Error { /// Generic failure state Fail, /// `hashbitlen` passed to `Md6::new()` or `hash()` incorrect BadHashbitlen, } impl Md6 { /// Create a new hash state and initialise it with the given bit length. /// /// `hashbitlen` is the hash output length. Must be between `1` and `512`. /// /// Returns: /// /// * `Err(Md6Error::BadHashbitlen)` if `hashbitlen` is not any of the mentioned above, or /// * `Ok(Md6)` if initialisation succeeds. /// /// # Examples /// /// Incorrect `hashbitlen` /// /// ``` /// # use md6::Md6; /// assert_eq!(Md6::new(0).map(|_| ()), Err(md6::Md6Error::BadHashbitlen)); /// assert_eq!(Md6::new(1024).map(|_| ()), Err(md6::Md6Error::BadHashbitlen)); /// ``` /// /// Creating a 512-long state /// /// ``` /// # use md6::Md6; /// Md6::new(512).unwrap(); /// ``` pub fn new(hashbitlen: i32) -> Result<Md6> { let mut raw_state = native::malloc_hash_state(); match unsafe { native::MD6_Hash_Init(raw_state, hashbitlen) } { 0 => Ok(Md6 { raw_state: raw_state }), e => { native::free_hash_state(&mut raw_state); Err(Md6Error::from(e)) } } } /// Append the provided data to the hash function. /// /// # Examples /// /// Hashing a part of [a short story](http://nabijaczleweli.xyz/capitalism/writing/Świat_to_kilka_takich_pokoi/) /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result = [0; 64]; /// /// let mut state = Md6::new(512).unwrap(); /// state.update(" Serbiańcy znowu się pochlali, ale w sumie".as_bytes()); /// state.update("czegoż się po wschodnich słowianach spodziewać, swoją".as_bytes()); /// state.update("drogą. I, jak to wszystkim homo sapiensom się dzieje".as_bytes()); /// state.update("filozofować poczęli.".as_bytes()); /// state.finalise(&mut result); /// /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0xD4, 0xAC, 0x5B, 0xDA, 0x95, 0x44, 0xCC, 0x3F, /// 0xFB, 0x59, 0x4B, 0x62, 0x84, 0xEF, 0x07, 0xDD, /// 0x59, 0xE7, 0x94, 0x2D, 0xCA, 0xCA, 0x07, 0x52, /// 0x14, 0x13, 0xE8, 0x06, 0xBD, 0x84, 0xB8, 0xC7, /// 0x8F, 0xB8, 0x03, 0x24, 0x39, 0xC8, 0x2E, 0xEC, /// 0x9F, 0x7F, 0x4F, 0xDA, 0xF8, 0x8A, 0x4B, 0x5F, /// 0x9D, 0xF8, 0xFD, 0x47, 0x0C, 0x4F, 0x2F, 0x4B, /// 0xCD, 0xDF, 0xAF, 0x13, 0xE1, 0xE1, 0x4D, 0x9D]); /// ``` pub fn update(&mut self, data: &[u8]) { unsafe { native::MD6_Hash_Update(self.raw_state, data.as_ptr(), data.len() as u64 * 8); } } /// Finish hashing and store the output result in the provided space. /// /// The provided space must not be smaller than the hash function's size, /// if the provided space is smaller than the hash function's size, the behaviour is undefined.
/// /// Storing and verifying results of all possible sizes. /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result_64 = [0; 8]; /// let mut result_128 = [0; 16]; /// let mut result_256 = [0; 32]; /// let mut result_512 = [0; 64]; /// /// let mut state_64 = Md6::new(64).unwrap(); /// let mut state_128 = Md6::new(128).unwrap(); /// let mut state_256 = Md6::new(256).unwrap(); /// let mut state_512 = Md6::new(512).unwrap(); /// /// state_64.update(b"The lazy fox jumps over the lazy dog."); /// state_128.update(b"The lazy fox jumps over the lazy dog."); /// state_256.update(b"The lazy fox jumps over the lazy dog."); /// state_512.update(b"The lazy fox jumps over the lazy dog."); /// /// state_64.finalise(&mut result_64); /// state_128.finalise(&mut result_128); /// state_256.finalise(&mut result_256); /// state_512.finalise(&mut result_512); /// /// assert_eq!(Vec::from_iter(result_64.iter().map(|&i| i)), /// vec![0xF3, 0x50, 0x60, 0xAE, 0xD7, 0xF0, 0xB0, 0x96]); /// assert_eq!(Vec::from_iter(result_128.iter().map(|&i| i)), /// vec![0x08, 0x5E, 0xA5, 0xF6, 0x6D, 0x2A, 0xC1, 0xF3, /// 0xCF, 0xC5, 0x6F, 0xA3, 0x7D, 0x1B, 0xEC, 0x9C]); /// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)), /// vec![0x06, 0x60, 0xBB, 0x89, 0x85, 0x06, 0xE4, 0xD9, /// 0x29, 0x8C, 0xD1, 0xB0, 0x40, 0x73, 0x49, 0x60, /// 0x47, 0x3E, 0x25, 0xA4, 0x9D, 0x52, 0x34, 0xBB, /// 0x2A, 0xCA, 0x31, 0x57, 0xD1, 0xAF, 0x27, 0xAA]); /// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)), /// vec![0xA5, 0xFE, 0xC7, 0x36, 0x81, 0xFA, 0x64, 0xBE, /// 0xE7, 0x2D, 0xB6, 0x05, 0x35, 0x26, 0x6C, 0x00, /// 0x6B, 0x2A, 0x49, 0x54, 0x04, 0x7E, 0x39, 0x05, /// 0xD1, 0xFE, 0xB3, 0x25, 0x21, 0x01, 0x81, 0x2D, /// 0xF2, 0x20, 0xC9, 0x09, 0xD4, 0xD7, 0xB7, 0x94, /// 0x53, 0xB4, 0x2D, 0xAD, 0x6D, 0x75, 0x52, 0xC7, /// 0x82, 0xE8, 0x4E, 0xFC, 0x3C, 0x34, 0x5B, 0x0C, /// 0xFF, 0x72, 0x1B, 0x56, 0x73, 0x05, 0x6B, 0x75]); /// ``` pub fn finalise(&mut self, hashval: &mut [u8]) { unsafe { native::MD6_Hash_Final(self.raw_state, hashval.as_mut_ptr()); } } } /// The `Write` implementation updates the state with the provided data. /// /// For example, to hash a file: /// /// ``` /// # use std::iter::FromIterator; /// # use std::fs::File; /// # use md6::Md6; /// # use std::io; /// let mut state = Md6::new(256).unwrap(); /// io::copy(&mut File::open("LICENSE").unwrap(), &mut state).unwrap(); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0xB7, 0x82, 0xA1, 0xEA, 0xDE, 0xC5, 0x46, 0x3E, /// 0x1D, 0xCF, 0x56, 0xA2, 0xD7, 0x52, 0x23, 0x82, /// 0xA3, 0x02, 0xE6, 0xB6, 0x1D, 0x45, 0xA8, 0xBF, /// 0x95, 0x12, 0x92, 0x1E, 0xAD, 0x21, 0x3E, 0x47]); /// ``` impl io::Write for Md6 { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.update(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Drop for Md6 { fn drop(&mut self) { native::free_hash_state(&mut self.raw_state); } } impl Error for Md6Error { fn description(&self) -> &str { match self { &Md6Error::Fail => "Generic MD6 fail", &Md6Error::BadHashbitlen => "Incorrect hashbitlen", } } } impl From<i32> for Md6Error { /// Passing incorrect error values yields unspecified behaviour. fn from(i: i32) -> Self { match i { 0 => panic!("Not an error"), 1 => Md6Error::Fail, 2 => Md6Error::BadHashbitlen, _ => panic!("Incorrect error number"), } } } impl fmt::Display for Md6Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } }
/// /// # Examples
random_line_split
lib.rs
//! An implementation of the [MD6 hash function](http://groups.csail.mit.edu/cis/md6), via FFI to reference implementation. //! //! For more information about MD6 visit its [official homepage](http://groups.csail.mit.edu/cis/md6). //! //! There are two APIs provided: one for single-chunk hashing and one for hashing of multiple data segments. //! //! # Examples //! //! Hashing a single chunk of data with a 256-bit MD6 hash function, then verifying the result. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result = [0; 32]; //! md6::hash(256, b"The lazy fox jumps over the lazy dog", &mut result).unwrap(); //! //! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), //! vec![0xE4, 0x55, 0x51, 0xAA, 0xE2, 0x66, 0xE1, 0x48, //! 0x2A, 0xC9, 0x8E, 0x24, 0x22, 0x9B, 0x3E, 0x90, //! 0xDC, 0x06, 0x61, 0x77, 0xF8, 0xFB, 0x1A, 0x52, //! 0x6E, 0x9D, 0xA2, 0xCC, 0x95, 0x71, 0x97, 0xAA]); //! ``` //! //! Hashing multiple chunks of data with a 512-bit MD6 hash function, then verifying the result. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result = [0; 64]; //! let mut state = Md6::new(512).unwrap(); //! //! state.update("Zażółć ".as_bytes()); //! state.update("gęślą ".as_bytes()); //! state.update("jaźń".as_bytes()); //! //! state.finalise(&mut result); //! assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), //! vec![0x92, 0x4E, 0x91, 0x6A, 0x01, 0x2C, 0x1A, 0x8D, //! 0x0F, 0xB7, 0x9A, 0x4A, 0xD4, 0x9C, 0x55, 0x5E, //! 0xBD, 0xCA, 0x59, 0xB8, 0x1B, 0x4C, 0x13, 0x41, //! 0x2E, 0x32, 0xA5, 0xC9, 0x3B, 0x61, 0xAD, 0xB8, //! 0x4D, 0xB3, 0xF9, 0x0C, 0x03, 0x51, 0xB2, 0x9E, //! 0x7B, 0xAE, 0x46, 0x9F, 0x8D, 0x60, 0x5D, 0xED, //! 0xFF, 0x51, 0x72, 0xDE, 0xA1, 0x6F, 0x00, 0xF7, //! 0xB4, 0x82, 0xEF, 0x87, 0xED, 0x77, 0xD9, 0x1A]); //! ``` //! //! Comparing result of single- and multi-chunk hash methods hashing the same effective message with a 64-bit MD6 hash //! function. //! //! ``` //! # use md6::Md6; //! # use std::iter::FromIterator; //! let mut result_multi = [0; 8]; //! let mut result_single = [0; 8]; //! //! let mut state = Md6::new(64).unwrap(); //! state.update("Zażółć ".as_bytes()); //! state.update("gęślą ".as_bytes()); //! state.update("jaźń".as_bytes()); //! state.finalise(&mut result_multi); //! //! md6::hash(64, "Zażółć gęślą jaźń".as_bytes(), &mut result_single).unwrap(); //! //! assert_eq!(Vec::from_iter(result_multi.iter().map(|&i| i)), //! Vec::from_iter(result_single.iter().map(|&i| i))); //! ``` //! //! # Special thanks //! //! To all who support further development on [Patreon](https://patreon.com/nabijaczleweli), in particular: //! //! * ThePhD //! * Embark Studios extern crate libc; mod native; use std::error::Error; use std::fmt; use std::io; /// Helper result type containing `Md6Error`. pub type Result<T> = std::result::Result<T, Md6Error>; /// Hash all data in one fell swoop. /// /// Refer to individual functions for extended documentation. /// /// # Example /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result_256 = [0; 32]; /// let mut result_512 = [0; 64]; /// /// md6::hash(256, &[], &mut result_256).unwrap(); /// md6::hash(512, &[], &mut result_512).unwrap(); /// /// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)), /// vec![0xBC, 0xA3, 0x8B, 0x24, 0xA8, 0x04, 0xAA, 0x37, /// 0xD8, 0x21, 0xD3, 0x1A, 0xF0, 0x0F, 0x55, 0x98, /// 0x23, 0x01, 0x22, 0xC5, 0xBB, 0xFC, 0x4C, 0x4A, /// 0xD5, 0xED, 0x40, 0xE4, 0x25, 0x8F, 0x04, 0xCA]); /// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)), /// vec![0x6B, 0x7F, 0x33, 0x82, 0x1A, 0x2C, 0x06, 0x0E, /// 0xCD, 0xD8, 0x1A, 0xEF, 0xDD, 0xEA, 0x2F, 0xD3, /// 0xC4, 0x72, 0x02, 0x70, 0xE1, 0x86, 0x54, 0xF4, /// 0xCB, 0x08, 0xEC, 0xE4, 0x9C, 0xCB, 0x46, 0x9F, /// 0x8B, 0xEE, 0xEE, 0x7C, 0x83, 0x12, 0x06, 0xBD, /// 0x57, 0x7F, 0x9F, 0x26, 0x30, 0xD9, 0x17, 0x79, /// 0x79, 0x20, 0x3A, 0x94, 0x89, 0xE4, 0x7E, 0x04, /// 0xDF, 0x4E, 0x6D, 0xEA, 0xA0, 0xF8, 0xE0, 0xC0]); /// ``` pub fn hash(hashbitlen: i32, data: &[u8], hashval: &mut [u8]) -> Result<()> { match unsafe { native::MD6_Hash_Hash(hashbitlen, data.as_ptr(), data.len() as u64 * 8, hashval.as_mut_ptr()) } { 0 => Ok(()), e => Err(Md6Error::from(e)), } } /// Hashing state for multiple data sets. /// /// # Example /// /// Hashing a string split into multiple chunks. /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut state = Md6::new(256).unwrap(); /// /// state.update(b"Abolish "); /// state.update(b"the "); /// state.update(b"bourgeoisie"); /// state.update(b"!"); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0x49, 0x23, 0xE7, 0xB0, 0x53, 0x32, 0x05, 0xB0, /// 0x25, 0xC5, 0xD4, 0xDB, 0x37, 0xB8, 0x99, 0x12, /// 0x16, 0x2E, 0xFD, 0xF4, 0xDA, 0xC2, 0x2C, 0xFF, /// 0xE6, 0x27, 0xF1, 0x11, 0xEC, 0x05, 0x2F, 0xB5]); /// ``` /// /// A `Write` implementation is also provided: /// /// ``` /// # use std::iter::FromIterator; /// # use md6::Md6; /// # use std::io; /// let mut state = Md6::new(256).unwrap(); /// io::copy(&mut &b"The lazy fox jumps over the lazy dog."[..], &mut state).unwrap(); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0x06, 0x60, 0xBB, 0x89, 0x85, 0x06, 0xE4, 0xD9, /// 0x29, 0x8C, 0xD1, 0xB0, 0x40, 0x73, 0x49, 0x60, /// 0x47, 0x3E, 0x25, 0xA4, 0x9D, 0x52, 0x34, 0xBB, /// 0x2A, 0xCA, 0x31, 0x57, 0xD1, 0xAF, 0x27, 0xAA]); /// ``` pub struct Md6 { raw_state: native::FFIHashState, } /// Some functions in the library can fail, this enum represents all the possible ways they can. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub enum Md6Error { /// Generic failure state Fail, /// `hashbitlen` passed to `Md6::new()` or `hash()` incorrect BadHashbitlen, } impl Md6 { /// Create a new hash state and initialise it with the given bit length. /// /// `hashbitlen` is the hash output length. Must be between `1` and `512`. /// /// Returns: /// /// * `Err(Md6Error::BadHashbitlen)` if `hashbitlen` is not any of the mentioned above, or /// * `Ok(Md6)` if initialisation succeeds. /// /// # Examples /// /// Incorrect `hashbitlen` /// /// ``` /// # use md6::Md6; /// assert_eq!(Md6::new(0).map(|_| ()), Err(md6::Md6Error::BadHashbitlen)); /// assert_eq!(Md6::new(1024).map(|_| ()), Err(md6::Md6Error::BadHashbitlen)); /// ``` /// /// Creating a 512-long state /// /// ``` /// # use md6::Md6; /// Md6::new(512).unwrap(); /// ``` pub fn new(hashbitlen: i32) -> Result<Md6> { let mut raw_state = native::malloc_hash_state(); match unsafe { native::MD6_Hash_Init(raw_state, hashbitlen) } { 0 => Ok(Md6 { raw_state: raw_state }), e => { native::free_hash_state(&mut raw_state); Err(Md6Error::from(e)) } } } /// Append the provided data to the hash function. /// /// # Examples /// /// Hashing a part of [a short story](http://nabijaczleweli.xyz/capitalism/writing/Świat_to_kilka_takich_pokoi/) /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result = [0; 64]; /// /// let mut state = Md6::new(512).unwrap(); /// state.update(" Serbiańcy znowu się pochlali, ale w sumie".as_bytes()); /// state.update("czegoż się po wschodnich słowianach spodziewać, swoją".as_bytes()); /// state.update("drogą. I, jak to wszystkim homo sapiensom się dzieje".as_bytes()); /// state.update("filozofować poczęli.".as_bytes()); /// state.finalise(&mut result); /// /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0xD4, 0xAC, 0x5B, 0xDA, 0x95, 0x44, 0xCC, 0x3F, /// 0xFB, 0x59, 0x4B, 0x62, 0x84, 0xEF, 0x07, 0xDD, /// 0x59, 0xE7, 0x94, 0x2D, 0xCA, 0xCA, 0x07, 0x52, /// 0x14, 0x13, 0xE8, 0x06, 0xBD, 0x84, 0xB8, 0xC7, /// 0x8F, 0xB8, 0x03, 0x24, 0x39, 0xC8, 0x2E, 0xEC, /// 0x9F, 0x7F, 0x4F, 0xDA, 0xF8, 0x8A, 0x4B, 0x5F, /// 0x9D, 0xF8, 0xFD, 0x47, 0x0C, 0x4F, 0x2F, 0x4B, /// 0xCD, 0xDF, 0xAF, 0x13, 0xE1, 0xE1, 0x4D, 0x9D]); /// ``` pub fn update(&mut self, data: &[u8]) { unsafe { native::MD6_Hash_Update(self.raw_state, data.as_ptr(), data.len() as u64 * 8); } } /// Finish hashing and store the output result in the provided space. /// /// The provided space must not be smaller than the hash function's size, /// if the provided space is smaller than the hash function's size, the behaviour is undefined. /// /// # Examples /// /// Storing and verifying results of all possible sizes. /// /// ``` /// # use md6::Md6; /// # use std::iter::FromIterator; /// let mut result_64 = [0; 8]; /// let mut result_128 = [0; 16]; /// let mut result_256 = [0; 32]; /// let mut result_512 = [0; 64]; /// /// let mut state_64 = Md6::new(64).unwrap(); /// let mut state_128 = Md6::new(128).unwrap(); /// let mut state_256 = Md6::new(256).unwrap(); /// let mut state_512 = Md6::new(512).unwrap(); /// /// state_64.update(b"The lazy fox jumps over the lazy dog."); /// state_128.update(b"The lazy fox jumps over the lazy dog."); /// state_256.update(b"The lazy fox jumps over the lazy dog."); /// state_512.update(b"The lazy fox jumps over the lazy dog."); /// /// state_64.finalise(&mut result_64); /// state_128.finalise(&mut result_128); /// state_256.finalise(&mut result_256); /// state_512.finalise(&mut result_512); /// /// assert_eq!(Vec::from_iter(result_64.iter().map(|&i| i)), /// vec![0xF3, 0x50, 0x60, 0xAE, 0xD7, 0xF0, 0xB0, 0x96]); /// assert_eq!(Vec::from_iter(result_128.iter().map(|&i| i)), /// vec![0x08, 0x5E, 0xA5, 0xF6, 0x6D, 0x2A, 0xC1, 0xF3, /// 0xCF, 0xC5, 0x6F, 0xA3, 0x7D, 0x1B, 0xEC, 0x9C]); /// assert_eq!(Vec::from_iter(result_256.iter().map(|&i| i)), /// vec![0x06, 0x60, 0xBB, 0x89, 0x85, 0x06, 0xE4, 0xD9, /// 0x29, 0x8C, 0xD1, 0xB0, 0x40, 0x73, 0x49, 0x60, /// 0x47, 0x3E, 0x25, 0xA4, 0x9D, 0x52, 0x34, 0xBB, /// 0x2A, 0xCA, 0x31, 0x57, 0xD1, 0xAF, 0x27, 0xAA]); /// assert_eq!(Vec::from_iter(result_512.iter().map(|&i| i)), /// vec![0xA5, 0xFE, 0xC7, 0x36, 0x81, 0xFA, 0x64, 0xBE, /// 0xE7, 0x2D, 0xB6, 0x05, 0x35, 0x26, 0x6C, 0x00, /// 0x6B, 0x2A, 0x49, 0x54, 0x04, 0x7E, 0x39, 0x05, /// 0xD1, 0xFE, 0xB3, 0x25, 0x21, 0x01, 0x81, 0x2D, /// 0xF2, 0x20, 0xC9, 0x09, 0xD4, 0xD7, 0xB7, 0x94, /// 0x53, 0xB4, 0x2D, 0xAD, 0x6D, 0x75, 0x52, 0xC7, /// 0x82, 0xE8, 0x4E, 0xFC, 0x3C, 0x34, 0x5B, 0x0C, /// 0xFF, 0x72, 0x1B, 0x56, 0x73, 0x05, 0x6B, 0x75]); /// ``` pub fn finalise(&mut self, hashval: &mut [u8]) { unsafe { native::MD6_Hash_Final(self.raw_state, hashval.as_mut_ptr()); } } } /// The `Write` implementation updates the state with the provided data. /// /// For example, to hash a file: /// /// ``` /// # use std::iter::FromIterator; /// # use std::fs::File; /// # use md6::Md6; /// # use std::io; /// let mut state = Md6::new(256).unwrap(); /// io::copy(&mut File::open("LICENSE").unwrap(), &mut state).unwrap(); /// /// let mut result = [0; 32]; /// state.finalise(&mut result); /// assert_eq!(Vec::from_iter(result.iter().map(|&i| i)), /// vec![0xB7, 0x82, 0xA1, 0xEA, 0xDE, 0xC5, 0x46, 0x3E, /// 0x1D, 0xCF, 0x56, 0xA2, 0xD7, 0x52, 0x23, 0x82, /// 0xA3, 0x02, 0xE6, 0xB6, 0x1D, 0x45, 0xA8, 0xBF, /// 0x95, 0x12, 0x92, 0x1E, 0xAD, 0x21, 0x3E, 0x47]); /// ``` impl io::Write for Md6 { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.update(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Drop for Md6 { fn drop(&mut self) { native::free_
_state(&mut self.raw_state); } } impl Error for Md6Error { fn description(&self) -> &str { match self { &Md6Error::Fail => "Generic MD6 fail", &Md6Error::BadHashbitlen => "Incorrect hashbitlen", } } } impl From<i32> for Md6Error { /// Passing incorrect error values yields unspecified behaviour. fn from(i: i32) -> Self { match i { 0 => panic!("Not an error"), 1 => Md6Error::Fail, 2 => Md6Error::BadHashbitlen, _ => panic!("Incorrect error number"), } } } impl fmt::Display for Md6Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } }
hash
identifier_name
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KEY_LENGTH}; use rapido_core::{ verify_tx_signature, AccountId, AppModule, Authenticator, Context, SignedTransaction, Store, StoreView, }; #[macro_use] extern crate rapido_core; const ACCOUNT_APP_NAME: &str = "rapido.account"; const ACCOUNT_STORE_NAME: &str = "rapido.account.store"; pub type PublicKeyBytes = [u8; PUBLIC_KEY_LENGTH]; // Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, pub nonce: u64, pub pubkey: PublicKeyBytes, // flag: can this entity create accounts trustanchor: bool, } impl Account { /// Create a new account given a public key pub fn create(pk: &PublicKey, is_ta: bool) -> Self { Self { id: generate_account_id(pk), nonce: 0u64, pubkey: pk.as_bytes(), trustanchor: is_ta, } } pub fn id(&self) -> Vec<u8> { self.id.clone() } /// Return the base58 account id pub fn id_to_str(&self) -> anyhow::Result<String, anyhow::Error> { let i = String::from_utf8(self.id.clone()); ensure!(i.is_ok(), "problem decoding account id to string"); Ok(i.unwrap()) } /// Is the account a trust anchor? pub fn is_trust_anchor(&self) -> bool { self.trustanchor } pub fn update_pubkey(&self, pk: PublicKeyBytes) -> Self { Self { id: self.id.clone(), nonce: self.nonce, pubkey: pk, trustanchor: self.trustanchor, } } /// Increment the nonce for the account pub fn increment_nonce(&self) -> Self { Self { id: self.id.clone(), nonce: self.nonce + 1, pubkey: self.pubkey, trustanchor: self.trustanchor, } } } impl_store_values!(Account); /// Account Store pub(crate) struct AccountStore; impl Store for AccountStore { type Key = AccountId; type Value = Account; fn name(&self) -> String { ACCOUNT_STORE_NAME.into() } } impl AccountStore { pub fn new() -> Self { AccountStore {} } } /// Message used in Transactions #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub enum Msgs { Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), } pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self) -> String { ACCOUNT_APP_NAME.into() } // Load genesis accounts. These entries become the trust anchors fn initialize(&self, view: &mut StoreView) -> Result<(), anyhow::Error> { let store = AccountStore::new(); for pk in &self.genesis { let pubkey = PublicKey::from_slice(&pk[..]).expect("genesis: decode public key"); let account = Account::create(&pubkey, true); // <= make them a trust anchor store.put(account.id(), account, view) } Ok(()) } fn handle_tx(&self, ctx: &Context, view: &mut StoreView) -> Result<(), anyhow::Error> { let msg: Msgs = ctx.decode_msg()?; match msg { // Create an account. The origin of this call, must be a trust anchor Msgs::Create(pubkey) => { let store = AccountStore::new(); // Ensure the caller's account exists and they are a trust anchor let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); ensure!( acct.is_trust_anchor(), "only a trust anchor can create an account" ); let pk = PublicKey::from_slice(&pubkey[..]); ensure!(pk.is_some(), "problem decoding the public key"); // Create the new account let new_account = Account::create(&pk.unwrap(), false); store.put(new_account.id(), new_account, view); Ok(()) } // Change an existing publickey. The origin of this call is the owner // of the publickey Msgs::ChangePubKey(pubkey) =>
} } fn handle_query( &self, path: &str, key: Vec<u8>, view: &StoreView, ) -> Result<Vec<u8>, anyhow::Error> { ensure!(key.len() > 0, "bad account key"); // return a serialized account for the given id. match path { "/" => { let account = key; let store = AccountStore::new(); let req_acct = store.get(account, &view); ensure!(req_acct.is_some(), "account not found"); let acct: Account = req_acct.unwrap(); let bits = acct.try_to_vec()?; Ok(bits) } _ => bail!("{:} not found", path), } } } // Authenticator pub struct AccountAuthenticator; impl Authenticator for AccountAuthenticator { fn validate( &self, tx: &SignedTransaction, view: &StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let txnonce = tx.nonce(); let store = AccountStore::new(); let caller_acct = store.get(caller, &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let caller_pubkey = PublicKey::from_slice(&acct.pubkey[..]); ensure!( caller_pubkey.is_some(), "problem decoding the user's public key" ); // Validate signature ensure!( verify_tx_signature(&tx, &caller_pubkey.unwrap()), "bad signature" ); // Check nonce ensure!(acct.nonce == txnonce, "nonce don't match"); Ok(()) } fn increment_nonce( &self, tx: &SignedTransaction, view: &mut StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let store = AccountStore::new(); let caller_acct = store.get(caller.clone(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let unonce = acct.increment_nonce(); store.put(caller.clone(), unonce, view); Ok(()) } } #[cfg(test)] mod tests { use super::*; use exonum_crypto::{gen_keypair, SecretKey}; use rapido_core::{testing_keypair, AppBuilder, TestKit}; fn create_account(name: &str) -> (Vec<u8>, PublicKeyBytes, SecretKey) { let (pk, sk) = testing_keypair(name); let acct = Account::create(&pk, true); (acct.id(), acct.pubkey, sk) } fn get_genesis_accounts() -> Vec<[u8; 32]> { vec![ create_account("bob").1, create_account("alice").1, create_account("tom").1, ] } fn gen_tx(user: Vec<u8>, secret_key: &SecretKey, nonce: u64) -> SignedTransaction { let mut tx = SignedTransaction::create( user, ACCOUNT_APP_NAME, Msgs::Create([1u8; 32]), // fake data nonce, ); tx.sign(&secret_key); tx } #[test] fn test_account_authenticator() { // Check signature verification and nonce rules are enforced let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); // Check signatures and correct nonce let txs = &[ &gen_tx(bob.clone(), &bsk, 0u64), &gen_tx(bob.clone(), &bsk, 1u64), &gen_tx(bob.clone(), &bsk, 2u64), &gen_tx(bob.clone(), &bsk, 3u64), ]; assert!(tester.check_tx(txs).is_ok()); // Wrong nonce assert!(tester .check_tx(&[&gen_tx(bob.clone(), &bsk, 5u64)]) .is_err()); // Bad signature: bob's ID but signed with wrong key let (_rpk, rsk) = gen_keypair(); assert!(tester .check_tx(&[&gen_tx(bob.clone(), &rsk, 0u64)]) .is_err()); } #[test] fn test_ta_account_create() { // Bob will create an account for Carol // Carol will try to create an account for Andy...but it'll fail let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); let (carol, cpk, csk) = create_account("carol"); let (_andy, apk, _) = create_account("andy"); let mut tx = SignedTransaction::create(bob.clone(), ACCOUNT_APP_NAME, Msgs::Create(cpk), 0u64); tx.sign(&bsk); assert!(tester.check_tx(&[&tx]).is_ok()); assert!(tester.commit_tx(&[&tx]).is_ok()); assert!(tester.query("rapido.account", carol.clone()).is_ok()); let mut tx1 = SignedTransaction::create(carol.clone(), ACCOUNT_APP_NAME, Msgs::Create(apk), 0u64); tx1.sign(&csk); // Check passes...but assert!(tester.check_tx(&[&tx1]).is_ok()); // deliver fails...carol is not a TA assert!(tester.commit_tx(&[&tx1]).is_err()); } #[test] fn test_account_chng_pubkey() { // Bob will change is pubkey. Make sure he can authenticate with it assert!(true) } }
{ let store = AccountStore::new(); let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let updated = acct.update_pubkey(pubkey); store.put(updated.id(), updated, view); Ok(()) }
conditional_block
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KEY_LENGTH}; use rapido_core::{ verify_tx_signature, AccountId, AppModule, Authenticator, Context, SignedTransaction, Store, StoreView, }; #[macro_use] extern crate rapido_core; const ACCOUNT_APP_NAME: &str = "rapido.account"; const ACCOUNT_STORE_NAME: &str = "rapido.account.store"; pub type PublicKeyBytes = [u8; PUBLIC_KEY_LENGTH]; // Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, pub nonce: u64, pub pubkey: PublicKeyBytes, // flag: can this entity create accounts trustanchor: bool, } impl Account { /// Create a new account given a public key pub fn create(pk: &PublicKey, is_ta: bool) -> Self { Self { id: generate_account_id(pk), nonce: 0u64, pubkey: pk.as_bytes(), trustanchor: is_ta, } } pub fn id(&self) -> Vec<u8> { self.id.clone() } /// Return the base58 account id pub fn id_to_str(&self) -> anyhow::Result<String, anyhow::Error> { let i = String::from_utf8(self.id.clone()); ensure!(i.is_ok(), "problem decoding account id to string"); Ok(i.unwrap()) } /// Is the account a trust anchor? pub fn is_trust_anchor(&self) -> bool { self.trustanchor } pub fn update_pubkey(&self, pk: PublicKeyBytes) -> Self { Self { id: self.id.clone(), nonce: self.nonce, pubkey: pk, trustanchor: self.trustanchor, } } /// Increment the nonce for the account pub fn increment_nonce(&self) -> Self { Self { id: self.id.clone(), nonce: self.nonce + 1, pubkey: self.pubkey, trustanchor: self.trustanchor, } } } impl_store_values!(Account); /// Account Store pub(crate) struct AccountStore; impl Store for AccountStore { type Key = AccountId; type Value = Account; fn name(&self) -> String { ACCOUNT_STORE_NAME.into() } } impl AccountStore { pub fn new() -> Self { AccountStore {} } } /// Message used in Transactions
pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self) -> String { ACCOUNT_APP_NAME.into() } // Load genesis accounts. These entries become the trust anchors fn initialize(&self, view: &mut StoreView) -> Result<(), anyhow::Error> { let store = AccountStore::new(); for pk in &self.genesis { let pubkey = PublicKey::from_slice(&pk[..]).expect("genesis: decode public key"); let account = Account::create(&pubkey, true); // <= make them a trust anchor store.put(account.id(), account, view) } Ok(()) } fn handle_tx(&self, ctx: &Context, view: &mut StoreView) -> Result<(), anyhow::Error> { let msg: Msgs = ctx.decode_msg()?; match msg { // Create an account. The origin of this call, must be a trust anchor Msgs::Create(pubkey) => { let store = AccountStore::new(); // Ensure the caller's account exists and they are a trust anchor let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); ensure!( acct.is_trust_anchor(), "only a trust anchor can create an account" ); let pk = PublicKey::from_slice(&pubkey[..]); ensure!(pk.is_some(), "problem decoding the public key"); // Create the new account let new_account = Account::create(&pk.unwrap(), false); store.put(new_account.id(), new_account, view); Ok(()) } // Change an existing publickey. The origin of this call is the owner // of the publickey Msgs::ChangePubKey(pubkey) => { let store = AccountStore::new(); let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let updated = acct.update_pubkey(pubkey); store.put(updated.id(), updated, view); Ok(()) } } } fn handle_query( &self, path: &str, key: Vec<u8>, view: &StoreView, ) -> Result<Vec<u8>, anyhow::Error> { ensure!(key.len() > 0, "bad account key"); // return a serialized account for the given id. match path { "/" => { let account = key; let store = AccountStore::new(); let req_acct = store.get(account, &view); ensure!(req_acct.is_some(), "account not found"); let acct: Account = req_acct.unwrap(); let bits = acct.try_to_vec()?; Ok(bits) } _ => bail!("{:} not found", path), } } } // Authenticator pub struct AccountAuthenticator; impl Authenticator for AccountAuthenticator { fn validate( &self, tx: &SignedTransaction, view: &StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let txnonce = tx.nonce(); let store = AccountStore::new(); let caller_acct = store.get(caller, &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let caller_pubkey = PublicKey::from_slice(&acct.pubkey[..]); ensure!( caller_pubkey.is_some(), "problem decoding the user's public key" ); // Validate signature ensure!( verify_tx_signature(&tx, &caller_pubkey.unwrap()), "bad signature" ); // Check nonce ensure!(acct.nonce == txnonce, "nonce don't match"); Ok(()) } fn increment_nonce( &self, tx: &SignedTransaction, view: &mut StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let store = AccountStore::new(); let caller_acct = store.get(caller.clone(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let unonce = acct.increment_nonce(); store.put(caller.clone(), unonce, view); Ok(()) } } #[cfg(test)] mod tests { use super::*; use exonum_crypto::{gen_keypair, SecretKey}; use rapido_core::{testing_keypair, AppBuilder, TestKit}; fn create_account(name: &str) -> (Vec<u8>, PublicKeyBytes, SecretKey) { let (pk, sk) = testing_keypair(name); let acct = Account::create(&pk, true); (acct.id(), acct.pubkey, sk) } fn get_genesis_accounts() -> Vec<[u8; 32]> { vec![ create_account("bob").1, create_account("alice").1, create_account("tom").1, ] } fn gen_tx(user: Vec<u8>, secret_key: &SecretKey, nonce: u64) -> SignedTransaction { let mut tx = SignedTransaction::create( user, ACCOUNT_APP_NAME, Msgs::Create([1u8; 32]), // fake data nonce, ); tx.sign(&secret_key); tx } #[test] fn test_account_authenticator() { // Check signature verification and nonce rules are enforced let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); // Check signatures and correct nonce let txs = &[ &gen_tx(bob.clone(), &bsk, 0u64), &gen_tx(bob.clone(), &bsk, 1u64), &gen_tx(bob.clone(), &bsk, 2u64), &gen_tx(bob.clone(), &bsk, 3u64), ]; assert!(tester.check_tx(txs).is_ok()); // Wrong nonce assert!(tester .check_tx(&[&gen_tx(bob.clone(), &bsk, 5u64)]) .is_err()); // Bad signature: bob's ID but signed with wrong key let (_rpk, rsk) = gen_keypair(); assert!(tester .check_tx(&[&gen_tx(bob.clone(), &rsk, 0u64)]) .is_err()); } #[test] fn test_ta_account_create() { // Bob will create an account for Carol // Carol will try to create an account for Andy...but it'll fail let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); let (carol, cpk, csk) = create_account("carol"); let (_andy, apk, _) = create_account("andy"); let mut tx = SignedTransaction::create(bob.clone(), ACCOUNT_APP_NAME, Msgs::Create(cpk), 0u64); tx.sign(&bsk); assert!(tester.check_tx(&[&tx]).is_ok()); assert!(tester.commit_tx(&[&tx]).is_ok()); assert!(tester.query("rapido.account", carol.clone()).is_ok()); let mut tx1 = SignedTransaction::create(carol.clone(), ACCOUNT_APP_NAME, Msgs::Create(apk), 0u64); tx1.sign(&csk); // Check passes...but assert!(tester.check_tx(&[&tx1]).is_ok()); // deliver fails...carol is not a TA assert!(tester.commit_tx(&[&tx1]).is_err()); } #[test] fn test_account_chng_pubkey() { // Bob will change is pubkey. Make sure he can authenticate with it assert!(true) } }
#[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub enum Msgs { Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), }
random_line_split
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KEY_LENGTH}; use rapido_core::{ verify_tx_signature, AccountId, AppModule, Authenticator, Context, SignedTransaction, Store, StoreView, }; #[macro_use] extern crate rapido_core; const ACCOUNT_APP_NAME: &str = "rapido.account"; const ACCOUNT_STORE_NAME: &str = "rapido.account.store"; pub type PublicKeyBytes = [u8; PUBLIC_KEY_LENGTH]; // Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, pub nonce: u64, pub pubkey: PublicKeyBytes, // flag: can this entity create accounts trustanchor: bool, } impl Account { /// Create a new account given a public key pub fn create(pk: &PublicKey, is_ta: bool) -> Self { Self { id: generate_account_id(pk), nonce: 0u64, pubkey: pk.as_bytes(), trustanchor: is_ta, } } pub fn id(&self) -> Vec<u8> { self.id.clone() } /// Return the base58 account id pub fn id_to_str(&self) -> anyhow::Result<String, anyhow::Error> { let i = String::from_utf8(self.id.clone()); ensure!(i.is_ok(), "problem decoding account id to string"); Ok(i.unwrap()) } /// Is the account a trust anchor? pub fn is_trust_anchor(&self) -> bool { self.trustanchor } pub fn update_pubkey(&self, pk: PublicKeyBytes) -> Self { Self { id: self.id.clone(), nonce: self.nonce, pubkey: pk, trustanchor: self.trustanchor, } } /// Increment the nonce for the account pub fn increment_nonce(&self) -> Self { Self { id: self.id.clone(), nonce: self.nonce + 1, pubkey: self.pubkey, trustanchor: self.trustanchor, } } } impl_store_values!(Account); /// Account Store pub(crate) struct AccountStore; impl Store for AccountStore { type Key = AccountId; type Value = Account; fn name(&self) -> String { ACCOUNT_STORE_NAME.into() } } impl AccountStore { pub fn new() -> Self { AccountStore {} } } /// Message used in Transactions #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub enum
{ Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), } pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self) -> String { ACCOUNT_APP_NAME.into() } // Load genesis accounts. These entries become the trust anchors fn initialize(&self, view: &mut StoreView) -> Result<(), anyhow::Error> { let store = AccountStore::new(); for pk in &self.genesis { let pubkey = PublicKey::from_slice(&pk[..]).expect("genesis: decode public key"); let account = Account::create(&pubkey, true); // <= make them a trust anchor store.put(account.id(), account, view) } Ok(()) } fn handle_tx(&self, ctx: &Context, view: &mut StoreView) -> Result<(), anyhow::Error> { let msg: Msgs = ctx.decode_msg()?; match msg { // Create an account. The origin of this call, must be a trust anchor Msgs::Create(pubkey) => { let store = AccountStore::new(); // Ensure the caller's account exists and they are a trust anchor let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); ensure!( acct.is_trust_anchor(), "only a trust anchor can create an account" ); let pk = PublicKey::from_slice(&pubkey[..]); ensure!(pk.is_some(), "problem decoding the public key"); // Create the new account let new_account = Account::create(&pk.unwrap(), false); store.put(new_account.id(), new_account, view); Ok(()) } // Change an existing publickey. The origin of this call is the owner // of the publickey Msgs::ChangePubKey(pubkey) => { let store = AccountStore::new(); let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let updated = acct.update_pubkey(pubkey); store.put(updated.id(), updated, view); Ok(()) } } } fn handle_query( &self, path: &str, key: Vec<u8>, view: &StoreView, ) -> Result<Vec<u8>, anyhow::Error> { ensure!(key.len() > 0, "bad account key"); // return a serialized account for the given id. match path { "/" => { let account = key; let store = AccountStore::new(); let req_acct = store.get(account, &view); ensure!(req_acct.is_some(), "account not found"); let acct: Account = req_acct.unwrap(); let bits = acct.try_to_vec()?; Ok(bits) } _ => bail!("{:} not found", path), } } } // Authenticator pub struct AccountAuthenticator; impl Authenticator for AccountAuthenticator { fn validate( &self, tx: &SignedTransaction, view: &StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let txnonce = tx.nonce(); let store = AccountStore::new(); let caller_acct = store.get(caller, &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let caller_pubkey = PublicKey::from_slice(&acct.pubkey[..]); ensure!( caller_pubkey.is_some(), "problem decoding the user's public key" ); // Validate signature ensure!( verify_tx_signature(&tx, &caller_pubkey.unwrap()), "bad signature" ); // Check nonce ensure!(acct.nonce == txnonce, "nonce don't match"); Ok(()) } fn increment_nonce( &self, tx: &SignedTransaction, view: &mut StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let store = AccountStore::new(); let caller_acct = store.get(caller.clone(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let unonce = acct.increment_nonce(); store.put(caller.clone(), unonce, view); Ok(()) } } #[cfg(test)] mod tests { use super::*; use exonum_crypto::{gen_keypair, SecretKey}; use rapido_core::{testing_keypair, AppBuilder, TestKit}; fn create_account(name: &str) -> (Vec<u8>, PublicKeyBytes, SecretKey) { let (pk, sk) = testing_keypair(name); let acct = Account::create(&pk, true); (acct.id(), acct.pubkey, sk) } fn get_genesis_accounts() -> Vec<[u8; 32]> { vec![ create_account("bob").1, create_account("alice").1, create_account("tom").1, ] } fn gen_tx(user: Vec<u8>, secret_key: &SecretKey, nonce: u64) -> SignedTransaction { let mut tx = SignedTransaction::create( user, ACCOUNT_APP_NAME, Msgs::Create([1u8; 32]), // fake data nonce, ); tx.sign(&secret_key); tx } #[test] fn test_account_authenticator() { // Check signature verification and nonce rules are enforced let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); // Check signatures and correct nonce let txs = &[ &gen_tx(bob.clone(), &bsk, 0u64), &gen_tx(bob.clone(), &bsk, 1u64), &gen_tx(bob.clone(), &bsk, 2u64), &gen_tx(bob.clone(), &bsk, 3u64), ]; assert!(tester.check_tx(txs).is_ok()); // Wrong nonce assert!(tester .check_tx(&[&gen_tx(bob.clone(), &bsk, 5u64)]) .is_err()); // Bad signature: bob's ID but signed with wrong key let (_rpk, rsk) = gen_keypair(); assert!(tester .check_tx(&[&gen_tx(bob.clone(), &rsk, 0u64)]) .is_err()); } #[test] fn test_ta_account_create() { // Bob will create an account for Carol // Carol will try to create an account for Andy...but it'll fail let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); let (carol, cpk, csk) = create_account("carol"); let (_andy, apk, _) = create_account("andy"); let mut tx = SignedTransaction::create(bob.clone(), ACCOUNT_APP_NAME, Msgs::Create(cpk), 0u64); tx.sign(&bsk); assert!(tester.check_tx(&[&tx]).is_ok()); assert!(tester.commit_tx(&[&tx]).is_ok()); assert!(tester.query("rapido.account", carol.clone()).is_ok()); let mut tx1 = SignedTransaction::create(carol.clone(), ACCOUNT_APP_NAME, Msgs::Create(apk), 0u64); tx1.sign(&csk); // Check passes...but assert!(tester.check_tx(&[&tx1]).is_ok()); // deliver fails...carol is not a TA assert!(tester.commit_tx(&[&tx1]).is_err()); } #[test] fn test_account_chng_pubkey() { // Bob will change is pubkey. Make sure he can authenticate with it assert!(true) } }
Msgs
identifier_name
lib.rs
//! //! Basic account support with an authenticator. Primarly used for development/testing. //! Uses a 'Trust Anchor' approach to bootstrapping users: Genesis accounts can create other accounts. //! use anyhow::{bail, ensure}; use borsh::{BorshDeserialize, BorshSerialize}; use exonum_crypto::{hash, PublicKey, PUBLIC_KEY_LENGTH}; use rapido_core::{ verify_tx_signature, AccountId, AppModule, Authenticator, Context, SignedTransaction, Store, StoreView, }; #[macro_use] extern crate rapido_core; const ACCOUNT_APP_NAME: &str = "rapido.account"; const ACCOUNT_STORE_NAME: &str = "rapido.account.store"; pub type PublicKeyBytes = [u8; PUBLIC_KEY_LENGTH]; // Format of the account id: base58(hash(pubkey)) fn generate_account_id(pk: &PublicKey) -> Vec<u8> { let hash = hash(&pk.as_bytes()); bs58::encode(&hash.as_bytes()).into_vec() } /// Account Model #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub struct Account { pub id: AccountId, pub nonce: u64, pub pubkey: PublicKeyBytes, // flag: can this entity create accounts trustanchor: bool, } impl Account { /// Create a new account given a public key pub fn create(pk: &PublicKey, is_ta: bool) -> Self { Self { id: generate_account_id(pk), nonce: 0u64, pubkey: pk.as_bytes(), trustanchor: is_ta, } } pub fn id(&self) -> Vec<u8> { self.id.clone() } /// Return the base58 account id pub fn id_to_str(&self) -> anyhow::Result<String, anyhow::Error> { let i = String::from_utf8(self.id.clone()); ensure!(i.is_ok(), "problem decoding account id to string"); Ok(i.unwrap()) } /// Is the account a trust anchor? pub fn is_trust_anchor(&self) -> bool { self.trustanchor } pub fn update_pubkey(&self, pk: PublicKeyBytes) -> Self { Self { id: self.id.clone(), nonce: self.nonce, pubkey: pk, trustanchor: self.trustanchor, } } /// Increment the nonce for the account pub fn increment_nonce(&self) -> Self { Self { id: self.id.clone(), nonce: self.nonce + 1, pubkey: self.pubkey, trustanchor: self.trustanchor, } } } impl_store_values!(Account); /// Account Store pub(crate) struct AccountStore; impl Store for AccountStore { type Key = AccountId; type Value = Account; fn name(&self) -> String { ACCOUNT_STORE_NAME.into() } } impl AccountStore { pub fn new() -> Self { AccountStore {} } } /// Message used in Transactions #[derive(BorshDeserialize, BorshSerialize, Debug, PartialEq, Clone)] pub enum Msgs { Create(PublicKeyBytes), ChangePubKey(PublicKeyBytes), } pub struct AccountModule { // PublicKeys of genesis accounts genesis: Vec<[u8; 32]>, } impl AccountModule { pub fn new(genesis: Vec<[u8; 32]>) -> Self { Self { genesis } } } impl AppModule for AccountModule { fn name(&self) -> String { ACCOUNT_APP_NAME.into() } // Load genesis accounts. These entries become the trust anchors fn initialize(&self, view: &mut StoreView) -> Result<(), anyhow::Error> { let store = AccountStore::new(); for pk in &self.genesis { let pubkey = PublicKey::from_slice(&pk[..]).expect("genesis: decode public key"); let account = Account::create(&pubkey, true); // <= make them a trust anchor store.put(account.id(), account, view) } Ok(()) } fn handle_tx(&self, ctx: &Context, view: &mut StoreView) -> Result<(), anyhow::Error> { let msg: Msgs = ctx.decode_msg()?; match msg { // Create an account. The origin of this call, must be a trust anchor Msgs::Create(pubkey) => { let store = AccountStore::new(); // Ensure the caller's account exists and they are a trust anchor let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); ensure!( acct.is_trust_anchor(), "only a trust anchor can create an account" ); let pk = PublicKey::from_slice(&pubkey[..]); ensure!(pk.is_some(), "problem decoding the public key"); // Create the new account let new_account = Account::create(&pk.unwrap(), false); store.put(new_account.id(), new_account, view); Ok(()) } // Change an existing publickey. The origin of this call is the owner // of the publickey Msgs::ChangePubKey(pubkey) => { let store = AccountStore::new(); let caller_acct = store.get(ctx.sender(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let updated = acct.update_pubkey(pubkey); store.put(updated.id(), updated, view); Ok(()) } } } fn handle_query( &self, path: &str, key: Vec<u8>, view: &StoreView, ) -> Result<Vec<u8>, anyhow::Error> { ensure!(key.len() > 0, "bad account key"); // return a serialized account for the given id. match path { "/" => { let account = key; let store = AccountStore::new(); let req_acct = store.get(account, &view); ensure!(req_acct.is_some(), "account not found"); let acct: Account = req_acct.unwrap(); let bits = acct.try_to_vec()?; Ok(bits) } _ => bail!("{:} not found", path), } } } // Authenticator pub struct AccountAuthenticator; impl Authenticator for AccountAuthenticator { fn validate( &self, tx: &SignedTransaction, view: &StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let txnonce = tx.nonce(); let store = AccountStore::new(); let caller_acct = store.get(caller, &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let caller_pubkey = PublicKey::from_slice(&acct.pubkey[..]); ensure!( caller_pubkey.is_some(), "problem decoding the user's public key" ); // Validate signature ensure!( verify_tx_signature(&tx, &caller_pubkey.unwrap()), "bad signature" ); // Check nonce ensure!(acct.nonce == txnonce, "nonce don't match"); Ok(()) } fn increment_nonce( &self, tx: &SignedTransaction, view: &mut StoreView, ) -> anyhow::Result<(), anyhow::Error> { let caller = tx.sender(); let store = AccountStore::new(); let caller_acct = store.get(caller.clone(), &view); ensure!(caller_acct.is_some(), "user not found"); let acct = caller_acct.unwrap(); let unonce = acct.increment_nonce(); store.put(caller.clone(), unonce, view); Ok(()) } } #[cfg(test)] mod tests { use super::*; use exonum_crypto::{gen_keypair, SecretKey}; use rapido_core::{testing_keypair, AppBuilder, TestKit}; fn create_account(name: &str) -> (Vec<u8>, PublicKeyBytes, SecretKey) { let (pk, sk) = testing_keypair(name); let acct = Account::create(&pk, true); (acct.id(), acct.pubkey, sk) } fn get_genesis_accounts() -> Vec<[u8; 32]> { vec![ create_account("bob").1, create_account("alice").1, create_account("tom").1, ] } fn gen_tx(user: Vec<u8>, secret_key: &SecretKey, nonce: u64) -> SignedTransaction
#[test] fn test_account_authenticator() { // Check signature verification and nonce rules are enforced let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); // Check signatures and correct nonce let txs = &[ &gen_tx(bob.clone(), &bsk, 0u64), &gen_tx(bob.clone(), &bsk, 1u64), &gen_tx(bob.clone(), &bsk, 2u64), &gen_tx(bob.clone(), &bsk, 3u64), ]; assert!(tester.check_tx(txs).is_ok()); // Wrong nonce assert!(tester .check_tx(&[&gen_tx(bob.clone(), &bsk, 5u64)]) .is_err()); // Bad signature: bob's ID but signed with wrong key let (_rpk, rsk) = gen_keypair(); assert!(tester .check_tx(&[&gen_tx(bob.clone(), &rsk, 0u64)]) .is_err()); } #[test] fn test_ta_account_create() { // Bob will create an account for Carol // Carol will try to create an account for Andy...but it'll fail let app = AppBuilder::new() .set_authenticator(AccountAuthenticator {}) .with_app(AccountModule::new(get_genesis_accounts())); let mut tester = TestKit::create(app); tester.start(); let (bob, _bpk, bsk) = create_account("bob"); let (carol, cpk, csk) = create_account("carol"); let (_andy, apk, _) = create_account("andy"); let mut tx = SignedTransaction::create(bob.clone(), ACCOUNT_APP_NAME, Msgs::Create(cpk), 0u64); tx.sign(&bsk); assert!(tester.check_tx(&[&tx]).is_ok()); assert!(tester.commit_tx(&[&tx]).is_ok()); assert!(tester.query("rapido.account", carol.clone()).is_ok()); let mut tx1 = SignedTransaction::create(carol.clone(), ACCOUNT_APP_NAME, Msgs::Create(apk), 0u64); tx1.sign(&csk); // Check passes...but assert!(tester.check_tx(&[&tx1]).is_ok()); // deliver fails...carol is not a TA assert!(tester.commit_tx(&[&tx1]).is_err()); } #[test] fn test_account_chng_pubkey() { // Bob will change is pubkey. Make sure he can authenticate with it assert!(true) } }
{ let mut tx = SignedTransaction::create( user, ACCOUNT_APP_NAME, Msgs::Create([1u8; 32]), // fake data nonce, ); tx.sign(&secret_key); tx }
identifier_body
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket, HEADER_SIZE}; type EventRecv = UnboundedReceiverStream<Vec<u8>>; type ShutdownRecv = future::Fuse<oneshot::Receiver<()>>; /// The read state of the packet handler. /// /// This type is used by `PacketHandler` to decide what should be read next when handling an /// event. enum ReadState { /// `PacketHandler` should read a header. Header, /// `PacketHandler` should read a payload based on a header. Payload(HeaderPacket), } /// A packet handler. /// /// It takes care of processing events into packets that can be processed by the workers. pub(super) struct PacketHandler { events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHandler { /// Create a new packet handler from an event receiver, a shutdown receiver and the peer's /// address. pub(super) fn new(receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self { Self { events: EventHandler::new(receiver), shutdown, // The handler should read a header first. state: ReadState::Header, address, } } /// Fetch the header and payload of a packet. /// /// This method only returns `None` if a shutdown signal is received. pub(super) async fn fetch_packet(&mut self) -> Option<(HeaderPacket, &[u8])> { // loop until we can return the header and payload loop { match &self.state { // Read a header. ReadState::Header => { // We need `HEADER_SIZE` bytes to read a header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, HEADER_SIZE) .await?; trace!("[{}] Reading Header...", self.address); // This never panics because we fetch exactly `HEADER_SIZE` bytes. let header = HeaderPacket::from_bytes(bytes.try_into().unwrap()); // Now we are ready to read a payload. self.state = ReadState::Payload(header); } // Read a payload. ReadState::Payload(header) => { // We read the quantity of bytes stated by the header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, header.packet_length.into()) .await?; // FIXME: Avoid this clone let header = header.clone(); // Now we are ready to read the next packet's header. self.state = ReadState::Header; // We return the current packet's header and payload. return Some((header, bytes)); } } } } } // An event handler. // // This type takes care of actually receiving the events and appending them to an inner buffer so // they can be used seamlessly by the `PacketHandler`. struct EventHandler { receiver: EventRecv, buffer: Vec<u8>, offset: usize, } impl EventHandler { /// Create a new event handler from an event receiver. fn new(receiver: EventRecv) -> Self { Self { receiver, buffer: vec![], offset: 0, } } /// Push a new event into the buffer. /// /// This method also removes the `..self.offset` range from the buffer and sets the offset back /// to zero. Which means that this should only be called when the buffer is empty or when there /// are not enough bytes to read a new header or payload. fn push_event(&mut self, mut bytes: Vec<u8>) { // Remove the already read bytes from the buffer. self.buffer = self.buffer.split_off(self.offset); // Reset the offset. self.offset = 0; // Append the bytes of the new event self.buffer.append(&mut bytes); } /// Fetch a slice of bytes of a determined length. /// /// The future returned by this method will be ready until there are enough bytes to fulfill /// the request. async fn fetch_bytes(&mut self, len: usize) -> &[u8] { // We need to be sure that we have enough bytes in the buffer. while self.offset + len > self.buffer.len() { // If there are not enough bytes in the buffer, we must receive new events if let Some(event) = self.receiver.next().await
} // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte slice. self.offset += len; bytes } /// Helper method to be able to shutdown when fetching bytes for a packet. /// /// This method returns `None` if a shutdown signal is received, otherwise it returns the /// requested bytes. async fn fetch_bytes_or_shutdown(&mut self, shutdown: &mut ShutdownRecv, len: usize) -> Option<&'_ [u8]> { select! { // Always select `shutdown` first, otherwise you can end with an infinite loop. _ = shutdown => None, bytes = self.fetch_bytes(len).fuse() => Some(bytes), } } } #[cfg(test)] mod tests { use std::time::Duration; use futures::{channel::oneshot, future::FutureExt}; use tokio::{spawn, sync::mpsc, time::sleep}; use tokio_stream::wrappers::UnboundedReceiverStream; use super::*; /// Generate a vector of events filled with packets of a desired length. fn gen_events(event_len: usize, msg_size: usize, n_msg: usize) -> Vec<Vec<u8>> { // Bytes of all the packets. let mut msgs = vec![0u8; msg_size * n_msg]; // We need 3 bytes for the header. Thus the packet length stored in the header should be 3 // bytes shorter. let msg_len = ((msg_size - 3) as u16).to_le_bytes(); // We write the bytes that correspond to the packet length in the header. for i in (0..n_msg).map(|i| i * msg_size + 1) { msgs[i] = msg_len[0]; msgs[i + 1] = msg_len[1]; } // Finally, we split all the bytes into events. msgs.chunks(event_len).map(Vec::from).collect() } /// Test if the `PacketHandler` can produce an exact number of packets of a desired length, /// divided in events of an specified length. This test checks that: /// - The header and payload of all the packets have the right content. /// - The number of produced packets is the desired one. async fn test(event_size: usize, msg_size: usize, msg_count: usize) { let msg_len = msg_size - 3; // Produce the events let events = gen_events(event_size, msg_size, msg_count); // Create a new packet handler let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); // Create the task that does the checks of the test. let handle = spawn(async move { // The packets are expected to be filled with zeroes except for the packet length // field of the header. let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); // Count how many packets can be fetched. let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { // Assert that the packets' content is correct. assert_eq!(msg, expected_msg); counter += 1; } // Assert that the number of packets is correct. assert_eq!(msg_count, counter); // Return back the packet handler to avoid dropping the channels. msg_handler }); // Send all the events to the packet handler. for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } // Sleep to be sure the handler had time to produce all the packets. sleep(Duration::from_millis(1)).await; // Send a shutdown signal. sender_shutdown.send(()).unwrap(); // Await for the task with the checks to be completed. assert!(handle.await.is_ok()); } /// Test that packets are produced correctly when they are divided into one byte events. #[tokio::test] async fn one_byte_events() { test(1, 5, 10).await; } /// Test that packets are produced correctly when each mes// let peer_id: PeerId = /// Url::from_url_str("tcp://[::1]:16000").await.unwrap().into();sage fits exactly into an event. #[tokio::test] async fn one_packet_per_event() { test(5, 5, 10).await; } /// Test that packets are produced correctly when two packets fit exactly into an event. #[tokio::test] async fn two_packets_per_event() { test(10, 5, 10).await; } /// Test that packets are produced correctly when a packet fits exactly into two events. #[tokio::test] async fn two_events_per_packet() { test(5, 10, 10).await; } /// Test that packets are produced correctly when a packet does not fit in a single event and /// it is not aligned either. #[tokio::test] async fn misaligned_packets() { test(3, 5, 10).await; } /// Test that the handler stops producing packets after receiving the shutdown signal. /// /// This test is basically the same as the `one_packet_per_event` test. But the last event is /// sent after the shutdown signal. As a consequence, the last packet is not produced by the /// packet handler. #[tokio::test] async fn shutdown() { let event_size = 5; let msg_size = event_size; let msg_count = 10; let msg_len = msg_size - 3; let mut events = gen_events(event_size, msg_size, msg_count); // Put the last event into its own variable. let last_event = events.pop().unwrap(); let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); let handle = spawn(async move { let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { assert_eq!(msg, expected_msg); counter += 1; } // Assert that we are missing one packet. assert_eq!(msg_count - 1, counter); msg_handler }); for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } sender_shutdown.send(()).unwrap(); sleep(Duration::from_millis(1)).await; // Send the last event after the shutdown signal sender.send(last_event).unwrap(); assert!(handle.await.is_ok()); } }
{ // If we received an event, we push it to the buffer. self.push_event(event); }
conditional_block
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket, HEADER_SIZE}; type EventRecv = UnboundedReceiverStream<Vec<u8>>; type ShutdownRecv = future::Fuse<oneshot::Receiver<()>>; /// The read state of the packet handler. /// /// This type is used by `PacketHandler` to decide what should be read next when handling an /// event. enum ReadState { /// `PacketHandler` should read a header. Header, /// `PacketHandler` should read a payload based on a header. Payload(HeaderPacket), } /// A packet handler. /// /// It takes care of processing events into packets that can be processed by the workers. pub(super) struct PacketHandler { events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHandler { /// Create a new packet handler from an event receiver, a shutdown receiver and the peer's /// address. pub(super) fn
(receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self { Self { events: EventHandler::new(receiver), shutdown, // The handler should read a header first. state: ReadState::Header, address, } } /// Fetch the header and payload of a packet. /// /// This method only returns `None` if a shutdown signal is received. pub(super) async fn fetch_packet(&mut self) -> Option<(HeaderPacket, &[u8])> { // loop until we can return the header and payload loop { match &self.state { // Read a header. ReadState::Header => { // We need `HEADER_SIZE` bytes to read a header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, HEADER_SIZE) .await?; trace!("[{}] Reading Header...", self.address); // This never panics because we fetch exactly `HEADER_SIZE` bytes. let header = HeaderPacket::from_bytes(bytes.try_into().unwrap()); // Now we are ready to read a payload. self.state = ReadState::Payload(header); } // Read a payload. ReadState::Payload(header) => { // We read the quantity of bytes stated by the header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, header.packet_length.into()) .await?; // FIXME: Avoid this clone let header = header.clone(); // Now we are ready to read the next packet's header. self.state = ReadState::Header; // We return the current packet's header and payload. return Some((header, bytes)); } } } } } // An event handler. // // This type takes care of actually receiving the events and appending them to an inner buffer so // they can be used seamlessly by the `PacketHandler`. struct EventHandler { receiver: EventRecv, buffer: Vec<u8>, offset: usize, } impl EventHandler { /// Create a new event handler from an event receiver. fn new(receiver: EventRecv) -> Self { Self { receiver, buffer: vec![], offset: 0, } } /// Push a new event into the buffer. /// /// This method also removes the `..self.offset` range from the buffer and sets the offset back /// to zero. Which means that this should only be called when the buffer is empty or when there /// are not enough bytes to read a new header or payload. fn push_event(&mut self, mut bytes: Vec<u8>) { // Remove the already read bytes from the buffer. self.buffer = self.buffer.split_off(self.offset); // Reset the offset. self.offset = 0; // Append the bytes of the new event self.buffer.append(&mut bytes); } /// Fetch a slice of bytes of a determined length. /// /// The future returned by this method will be ready until there are enough bytes to fulfill /// the request. async fn fetch_bytes(&mut self, len: usize) -> &[u8] { // We need to be sure that we have enough bytes in the buffer. while self.offset + len > self.buffer.len() { // If there are not enough bytes in the buffer, we must receive new events if let Some(event) = self.receiver.next().await { // If we received an event, we push it to the buffer. self.push_event(event); } } // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte slice. self.offset += len; bytes } /// Helper method to be able to shutdown when fetching bytes for a packet. /// /// This method returns `None` if a shutdown signal is received, otherwise it returns the /// requested bytes. async fn fetch_bytes_or_shutdown(&mut self, shutdown: &mut ShutdownRecv, len: usize) -> Option<&'_ [u8]> { select! { // Always select `shutdown` first, otherwise you can end with an infinite loop. _ = shutdown => None, bytes = self.fetch_bytes(len).fuse() => Some(bytes), } } } #[cfg(test)] mod tests { use std::time::Duration; use futures::{channel::oneshot, future::FutureExt}; use tokio::{spawn, sync::mpsc, time::sleep}; use tokio_stream::wrappers::UnboundedReceiverStream; use super::*; /// Generate a vector of events filled with packets of a desired length. fn gen_events(event_len: usize, msg_size: usize, n_msg: usize) -> Vec<Vec<u8>> { // Bytes of all the packets. let mut msgs = vec![0u8; msg_size * n_msg]; // We need 3 bytes for the header. Thus the packet length stored in the header should be 3 // bytes shorter. let msg_len = ((msg_size - 3) as u16).to_le_bytes(); // We write the bytes that correspond to the packet length in the header. for i in (0..n_msg).map(|i| i * msg_size + 1) { msgs[i] = msg_len[0]; msgs[i + 1] = msg_len[1]; } // Finally, we split all the bytes into events. msgs.chunks(event_len).map(Vec::from).collect() } /// Test if the `PacketHandler` can produce an exact number of packets of a desired length, /// divided in events of an specified length. This test checks that: /// - The header and payload of all the packets have the right content. /// - The number of produced packets is the desired one. async fn test(event_size: usize, msg_size: usize, msg_count: usize) { let msg_len = msg_size - 3; // Produce the events let events = gen_events(event_size, msg_size, msg_count); // Create a new packet handler let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); // Create the task that does the checks of the test. let handle = spawn(async move { // The packets are expected to be filled with zeroes except for the packet length // field of the header. let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); // Count how many packets can be fetched. let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { // Assert that the packets' content is correct. assert_eq!(msg, expected_msg); counter += 1; } // Assert that the number of packets is correct. assert_eq!(msg_count, counter); // Return back the packet handler to avoid dropping the channels. msg_handler }); // Send all the events to the packet handler. for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } // Sleep to be sure the handler had time to produce all the packets. sleep(Duration::from_millis(1)).await; // Send a shutdown signal. sender_shutdown.send(()).unwrap(); // Await for the task with the checks to be completed. assert!(handle.await.is_ok()); } /// Test that packets are produced correctly when they are divided into one byte events. #[tokio::test] async fn one_byte_events() { test(1, 5, 10).await; } /// Test that packets are produced correctly when each mes// let peer_id: PeerId = /// Url::from_url_str("tcp://[::1]:16000").await.unwrap().into();sage fits exactly into an event. #[tokio::test] async fn one_packet_per_event() { test(5, 5, 10).await; } /// Test that packets are produced correctly when two packets fit exactly into an event. #[tokio::test] async fn two_packets_per_event() { test(10, 5, 10).await; } /// Test that packets are produced correctly when a packet fits exactly into two events. #[tokio::test] async fn two_events_per_packet() { test(5, 10, 10).await; } /// Test that packets are produced correctly when a packet does not fit in a single event and /// it is not aligned either. #[tokio::test] async fn misaligned_packets() { test(3, 5, 10).await; } /// Test that the handler stops producing packets after receiving the shutdown signal. /// /// This test is basically the same as the `one_packet_per_event` test. But the last event is /// sent after the shutdown signal. As a consequence, the last packet is not produced by the /// packet handler. #[tokio::test] async fn shutdown() { let event_size = 5; let msg_size = event_size; let msg_count = 10; let msg_len = msg_size - 3; let mut events = gen_events(event_size, msg_size, msg_count); // Put the last event into its own variable. let last_event = events.pop().unwrap(); let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); let handle = spawn(async move { let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { assert_eq!(msg, expected_msg); counter += 1; } // Assert that we are missing one packet. assert_eq!(msg_count - 1, counter); msg_handler }); for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } sender_shutdown.send(()).unwrap(); sleep(Duration::from_millis(1)).await; // Send the last event after the shutdown signal sender.send(last_event).unwrap(); assert!(handle.await.is_ok()); } }
new
identifier_name
packet_handler.rs
// Copyright 2020-2022 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use bee_gossip::Multiaddr; use futures::{ channel::oneshot, future::{self, FutureExt}, stream::StreamExt, }; use log::trace; use tokio::select; use tokio_stream::wrappers::UnboundedReceiverStream; use crate::packets::{HeaderPacket, HEADER_SIZE}; type EventRecv = UnboundedReceiverStream<Vec<u8>>; type ShutdownRecv = future::Fuse<oneshot::Receiver<()>>; /// The read state of the packet handler. /// /// This type is used by `PacketHandler` to decide what should be read next when handling an /// event. enum ReadState { /// `PacketHandler` should read a header. Header, /// `PacketHandler` should read a payload based on a header. Payload(HeaderPacket), } /// A packet handler. /// /// It takes care of processing events into packets that can be processed by the workers. pub(super) struct PacketHandler { events: EventHandler, // FIXME: see if we can implement `Stream` for the `PacketHandler` and use the // `ShutdownStream` type instead. shutdown: ShutdownRecv, state: ReadState, /// The address of the peer. This field is only here for logging purposes. address: Multiaddr, } impl PacketHandler { /// Create a new packet handler from an event receiver, a shutdown receiver and the peer's /// address. pub(super) fn new(receiver: EventRecv, shutdown: ShutdownRecv, address: Multiaddr) -> Self { Self { events: EventHandler::new(receiver), shutdown, // The handler should read a header first. state: ReadState::Header, address, } } /// Fetch the header and payload of a packet. /// /// This method only returns `None` if a shutdown signal is received. pub(super) async fn fetch_packet(&mut self) -> Option<(HeaderPacket, &[u8])> { // loop until we can return the header and payload loop { match &self.state { // Read a header. ReadState::Header => { // We need `HEADER_SIZE` bytes to read a header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, HEADER_SIZE) .await?; trace!("[{}] Reading Header...", self.address); // This never panics because we fetch exactly `HEADER_SIZE` bytes. let header = HeaderPacket::from_bytes(bytes.try_into().unwrap()); // Now we are ready to read a payload. self.state = ReadState::Payload(header); } // Read a payload. ReadState::Payload(header) => { // We read the quantity of bytes stated by the header. let bytes = self .events .fetch_bytes_or_shutdown(&mut self.shutdown, header.packet_length.into()) .await?; // FIXME: Avoid this clone let header = header.clone(); // Now we are ready to read the next packet's header. self.state = ReadState::Header; // We return the current packet's header and payload. return Some((header, bytes)); } } } } } // An event handler. // // This type takes care of actually receiving the events and appending them to an inner buffer so // they can be used seamlessly by the `PacketHandler`. struct EventHandler { receiver: EventRecv, buffer: Vec<u8>, offset: usize, } impl EventHandler { /// Create a new event handler from an event receiver. fn new(receiver: EventRecv) -> Self { Self { receiver, buffer: vec![], offset: 0, } } /// Push a new event into the buffer. /// /// This method also removes the `..self.offset` range from the buffer and sets the offset back /// to zero. Which means that this should only be called when the buffer is empty or when there /// are not enough bytes to read a new header or payload. fn push_event(&mut self, mut bytes: Vec<u8>) { // Remove the already read bytes from the buffer. self.buffer = self.buffer.split_off(self.offset); // Reset the offset. self.offset = 0; // Append the bytes of the new event self.buffer.append(&mut bytes); } /// Fetch a slice of bytes of a determined length. /// /// The future returned by this method will be ready until there are enough bytes to fulfill /// the request. async fn fetch_bytes(&mut self, len: usize) -> &[u8] { // We need to be sure that we have enough bytes in the buffer. while self.offset + len > self.buffer.len() { // If there are not enough bytes in the buffer, we must receive new events if let Some(event) = self.receiver.next().await { // If we received an event, we push it to the buffer.
self.push_event(event); } } // Get the requested bytes. This will not panic because the loop above only exists if we // have enough bytes to do this step. let bytes = &self.buffer[self.offset..][..len]; // Increase the offset by the length of the byte slice. self.offset += len; bytes } /// Helper method to be able to shutdown when fetching bytes for a packet. /// /// This method returns `None` if a shutdown signal is received, otherwise it returns the /// requested bytes. async fn fetch_bytes_or_shutdown(&mut self, shutdown: &mut ShutdownRecv, len: usize) -> Option<&'_ [u8]> { select! { // Always select `shutdown` first, otherwise you can end with an infinite loop. _ = shutdown => None, bytes = self.fetch_bytes(len).fuse() => Some(bytes), } } } #[cfg(test)] mod tests { use std::time::Duration; use futures::{channel::oneshot, future::FutureExt}; use tokio::{spawn, sync::mpsc, time::sleep}; use tokio_stream::wrappers::UnboundedReceiverStream; use super::*; /// Generate a vector of events filled with packets of a desired length. fn gen_events(event_len: usize, msg_size: usize, n_msg: usize) -> Vec<Vec<u8>> { // Bytes of all the packets. let mut msgs = vec![0u8; msg_size * n_msg]; // We need 3 bytes for the header. Thus the packet length stored in the header should be 3 // bytes shorter. let msg_len = ((msg_size - 3) as u16).to_le_bytes(); // We write the bytes that correspond to the packet length in the header. for i in (0..n_msg).map(|i| i * msg_size + 1) { msgs[i] = msg_len[0]; msgs[i + 1] = msg_len[1]; } // Finally, we split all the bytes into events. msgs.chunks(event_len).map(Vec::from).collect() } /// Test if the `PacketHandler` can produce an exact number of packets of a desired length, /// divided in events of an specified length. This test checks that: /// - The header and payload of all the packets have the right content. /// - The number of produced packets is the desired one. async fn test(event_size: usize, msg_size: usize, msg_count: usize) { let msg_len = msg_size - 3; // Produce the events let events = gen_events(event_size, msg_size, msg_count); // Create a new packet handler let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); // Create the task that does the checks of the test. let handle = spawn(async move { // The packets are expected to be filled with zeroes except for the packet length // field of the header. let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); // Count how many packets can be fetched. let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { // Assert that the packets' content is correct. assert_eq!(msg, expected_msg); counter += 1; } // Assert that the number of packets is correct. assert_eq!(msg_count, counter); // Return back the packet handler to avoid dropping the channels. msg_handler }); // Send all the events to the packet handler. for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } // Sleep to be sure the handler had time to produce all the packets. sleep(Duration::from_millis(1)).await; // Send a shutdown signal. sender_shutdown.send(()).unwrap(); // Await for the task with the checks to be completed. assert!(handle.await.is_ok()); } /// Test that packets are produced correctly when they are divided into one byte events. #[tokio::test] async fn one_byte_events() { test(1, 5, 10).await; } /// Test that packets are produced correctly when each mes// let peer_id: PeerId = /// Url::from_url_str("tcp://[::1]:16000").await.unwrap().into();sage fits exactly into an event. #[tokio::test] async fn one_packet_per_event() { test(5, 5, 10).await; } /// Test that packets are produced correctly when two packets fit exactly into an event. #[tokio::test] async fn two_packets_per_event() { test(10, 5, 10).await; } /// Test that packets are produced correctly when a packet fits exactly into two events. #[tokio::test] async fn two_events_per_packet() { test(5, 10, 10).await; } /// Test that packets are produced correctly when a packet does not fit in a single event and /// it is not aligned either. #[tokio::test] async fn misaligned_packets() { test(3, 5, 10).await; } /// Test that the handler stops producing packets after receiving the shutdown signal. /// /// This test is basically the same as the `one_packet_per_event` test. But the last event is /// sent after the shutdown signal. As a consequence, the last packet is not produced by the /// packet handler. #[tokio::test] async fn shutdown() { let event_size = 5; let msg_size = event_size; let msg_count = 10; let msg_len = msg_size - 3; let mut events = gen_events(event_size, msg_size, msg_count); // Put the last event into its own variable. let last_event = events.pop().unwrap(); let (sender_shutdown, receiver_shutdown) = oneshot::channel::<()>(); let (sender, receiver) = mpsc::unbounded_channel::<Vec<u8>>(); let mut msg_handler = PacketHandler::new( UnboundedReceiverStream::new(receiver), receiver_shutdown.fuse(), "/ip4/0.0.0.0/tcp/8080".parse().unwrap(), ); let handle = spawn(async move { let expected_bytes = vec![0u8; msg_len]; let expected_msg = ( HeaderPacket { packet_type: 0, packet_length: msg_len as u16, }, expected_bytes.as_slice(), ); let mut counter = 0; while let Some(msg) = msg_handler.fetch_packet().await { assert_eq!(msg, expected_msg); counter += 1; } // Assert that we are missing one packet. assert_eq!(msg_count - 1, counter); msg_handler }); for event in events { sender.send(event).unwrap(); sleep(Duration::from_millis(1)).await; } sender_shutdown.send(()).unwrap(); sleep(Duration::from_millis(1)).await; // Send the last event after the shutdown signal sender.send(last_event).unwrap(); assert!(handle.await.is_ok()); } }
random_line_split
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, time::Instant, }; create_idx_struct!(pub NodeIdx); create_idx_struct!(pub EdgeIdx); create_idx_struct!(pub EntryIdx); #[derive(Debug)] struct CompressedIlpName<T>(T); impl<T: SmallIdx> Display for CompressedIlpName<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let mut val = self.0.idx(); while val!= 0 { f.write_char(char::from(CHARS[val % CHARS.len()]))?; val /= CHARS.len(); } Ok(()) } } #[derive(Debug)] struct ParsedEdgeHandler { edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, node_degrees: Vec<usize>, } impl ParsedEdgeHandler { fn handle_edge(&mut self, node_indices: impl IntoIterator<Item = Result<usize>>) -> Result<()> { let incidences = SkipVec::try_sorted_from(node_indices.into_iter().map(|idx_result| { idx_result.and_then(|node_idx| { ensure!( node_idx < self.node_degrees.len(), "invalid node idx in edge: {}", node_idx ); Ok((NodeIdx::from(node_idx), EntryIdx::INVALID)) }) }))?; ensure!(incidences.len() > 0, "edges may not be empty"); for (_, (node, _)) in &incidences { self.node_degrees[node.idx()] += 1; } self.edge_incidences.push(incidences); Ok(()) } } #[derive(Debug, Deserialize)] struct JsonInstance { num_nodes: usize, edges: Vec<Vec<usize>>, } #[derive(Clone, Debug)] pub struct Instance { nodes: ContiguousIdxVec<NodeIdx>, edges: ContiguousIdxVec<EdgeIdx>, node_incidences: Vec<SkipVec<(EdgeIdx, EntryIdx)>>, edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, } impl Instance { fn load( num_nodes: usize, num_edges: usize, read_edges: impl FnOnce(&mut ParsedEdgeHandler) -> Result<()>, ) -> Result<Self> { let mut handler = ParsedEdgeHandler { edge_incidences: Vec::with_capacity(num_edges), node_degrees: vec![0; num_nodes], }; read_edges(&mut handler)?; let ParsedEdgeHandler { mut edge_incidences, node_degrees, } = handler; let mut node_incidences: Vec<_> = node_degrees .iter() .map(|&len| SkipVec::with_len(len)) .collect(); let mut rem_node_degrees = node_degrees; for (edge, incidences) in edge_incidences.iter_mut().enumerate() { let edge = EdgeIdx::from(edge); for (edge_entry_idx, edge_entry) in incidences.iter_mut() { let node = edge_entry.0.idx(); let node_entry_idx = node_incidences[node].len() - rem_node_degrees[node]; rem_node_degrees[node] -= 1; edge_entry.1 = EntryIdx::from(node_entry_idx); node_incidences[node][node_entry_idx] = (edge, EntryIdx::from(edge_entry_idx)); } } Ok(Self { nodes: (0..num_nodes).map(NodeIdx::from).collect(), edges: (0..num_edges).map(EdgeIdx::from).collect(), node_incidences, edge_incidences, }) } pub fn load_from_text(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); let mut line = String::new(); reader.read_line(&mut line)?; let mut numbers = line.split_ascii_whitespace().map(str::parse); let num_nodes = numbers .next() .ok_or_else(|| anyhow!("Missing node count"))??; let num_edges = numbers .next() .ok_or_else(|| anyhow!("Missing edge count"))??; ensure!( numbers.next().is_none(), "Too many numbers in first input line" ); let instance = Self::load(num_nodes, num_edges, |handler| { for _ in 0..num_edges { line.clear(); reader.read_line(&mut line)?; let mut numbers = line .split_ascii_whitespace() .map(|s| s.parse::<usize>().map_err(Error::from)); // Skip degree numbers .next() .ok_or_else(|| anyhow!("empty edge line in input, expected degree"))??; handler.handle_edge(numbers)?; } Ok(()) })?; info!( "Loaded text instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn load_from_json(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); // Usually faster for large inputs, see https://github.com/serde-rs/json/issues/160 let mut text = String::new(); reader.read_to_string(&mut text)?; let JsonInstance { num_nodes, edges } = serde_json::from_str(&text)?; let num_edges = edges.len(); let instance = Self::load(num_nodes, num_edges, |handler| { for edge in edges { handler.handle_edge(edge.into_iter().map(Ok))?; } Ok(()) })?; info!( "Loaded json instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn num_edges(&self) -> usize { self.edges.len() } pub fn num_nodes_total(&self) -> usize { self.node_incidences.len() } pub fn num_edges_total(&self) -> usize {
} /// Edges incident to a node, sorted by increasing indices. pub fn node( &self, node: NodeIdx, ) -> impl Iterator<Item = EdgeIdx> + ExactSizeIterator + Clone + '_ { self.node_incidences[node.idx()] .iter() .map(|(_, (edge, _))| *edge) } /// Nodes incident to an edge, sorted by increasing indices. pub fn edge( &self, edge: EdgeIdx, ) -> impl Iterator<Item = NodeIdx> + ExactSizeIterator + Clone + '_ { self.edge_incidences[edge.idx()] .iter() .map(|(_, (node, _))| *node) } /// Alive nodes in the instance, in arbitrary order. pub fn nodes(&self) -> &[NodeIdx] { &self.nodes } /// Alive edges in the instance, in arbitrary order. pub fn edges(&self) -> &[EdgeIdx] { &self.edges } pub fn node_degree(&self, node: NodeIdx) -> usize { self.node_incidences[node.idx()].len() } pub fn edge_size(&self, edge: EdgeIdx) -> usize { self.edge_incidences[edge.idx()].len() } /// Deletes a node from the instance. pub fn delete_node(&mut self, node: NodeIdx) { trace!("Deleting node {}", node); for (_idx, (edge, entry_idx)) in &self.node_incidences[node.idx()] { self.edge_incidences[edge.idx()].delete(entry_idx.idx()); } self.nodes.delete(node.idx()); } /// Deletes an edge from the instance. pub fn delete_edge(&mut self, edge: EdgeIdx) { trace!("Deleting edge {}", edge); for (_idx, (node, entry_idx)) in &self.edge_incidences[edge.idx()] { self.node_incidences[node.idx()].delete(entry_idx.idx()); } self.edges.delete(edge.idx()); } /// Restores a previously deleted node. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn restore_node(&mut self, node: NodeIdx) { trace!("Restoring node {}", node); for (_idx, (edge, entry_idx)) in self.node_incidences[node.idx()].iter().rev() { self.edge_incidences[edge.idx()].restore(entry_idx.idx()); } self.nodes.restore(node.idx()); } /// Restores a previously deleted edge. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn restore_edge(&mut self, edge: EdgeIdx) { trace!("Restoring edge {}", edge); for (_idx, (node, entry_idx)) in self.edge_incidences[edge.idx()].iter().rev() { self.node_incidences[node.idx()].restore(entry_idx.idx()); } self.edges.restore(edge.idx()); } /// Deletes all edges incident to a node. /// /// The node itself must have already been deleted. pub fn delete_incident_edges(&mut self, node: NodeIdx) { // We want to iterate over the incidence of `node` while deleting // edges, which in turn changes node incidences. This is safe, since // `node` itself was already deleted. To make the borrow checker // accept this, we temporarily move `node` incidence to a local // variable, replacing it with an empty list. This should not be much // slower than unsafe alternatives, since an incidence list is only // 28 bytes large. trace!("Deleting all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to delete_incident_edges must be deleted" ); let incidence = mem::take(&mut self.node_incidences[node.idx()]); for (_, (edge, _)) in &incidence { self.delete_edge(*edge); } self.node_incidences[node.idx()] = incidence; } /// Restores all incident edges to a node. /// /// This reverses the effect of `delete_incident_edges`. As with all other /// `restore_*` methods, this must be done in reverse order of deletions. /// In particular, the node itself must still be deleted. pub fn restore_incident_edges(&mut self, node: NodeIdx) { trace!("Restoring all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to restore_incident_edges must be deleted" ); // See `delete_incident_edges` for an explanation of this swapping around let incidence = mem::take(&mut self.node_incidences[node.idx()]); // It is important that we restore the edges in reverse order for (_, (edge, _)) in incidence.iter().rev() { self.restore_edge(*edge); } self.node_incidences[node.idx()] = incidence; } pub fn export_as_ilp(&self, mut writer: impl Write) -> Result<()> { writeln!(writer, "Minimize")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " + v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "Subject To")?; for &edge in self.edges() { write!(writer, " e{}: ", CompressedIlpName(edge))?; for (idx, node) in self.edge(edge).enumerate() { if idx > 0 { write!(writer, " + ")?; } write!(writer, "v{}", CompressedIlpName(node))?; } writeln!(writer, " >= 1")?; } writeln!(writer, "Binaries")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "End")?; Ok(()) } }
self.edge_incidences.len()
random_line_split
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, time::Instant, }; create_idx_struct!(pub NodeIdx); create_idx_struct!(pub EdgeIdx); create_idx_struct!(pub EntryIdx); #[derive(Debug)] struct CompressedIlpName<T>(T); impl<T: SmallIdx> Display for CompressedIlpName<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let mut val = self.0.idx(); while val!= 0 { f.write_char(char::from(CHARS[val % CHARS.len()]))?; val /= CHARS.len(); } Ok(()) } } #[derive(Debug)] struct ParsedEdgeHandler { edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, node_degrees: Vec<usize>, } impl ParsedEdgeHandler { fn handle_edge(&mut self, node_indices: impl IntoIterator<Item = Result<usize>>) -> Result<()> { let incidences = SkipVec::try_sorted_from(node_indices.into_iter().map(|idx_result| { idx_result.and_then(|node_idx| { ensure!( node_idx < self.node_degrees.len(), "invalid node idx in edge: {}", node_idx ); Ok((NodeIdx::from(node_idx), EntryIdx::INVALID)) }) }))?; ensure!(incidences.len() > 0, "edges may not be empty"); for (_, (node, _)) in &incidences { self.node_degrees[node.idx()] += 1; } self.edge_incidences.push(incidences); Ok(()) } } #[derive(Debug, Deserialize)] struct JsonInstance { num_nodes: usize, edges: Vec<Vec<usize>>, } #[derive(Clone, Debug)] pub struct Instance { nodes: ContiguousIdxVec<NodeIdx>, edges: ContiguousIdxVec<EdgeIdx>, node_incidences: Vec<SkipVec<(EdgeIdx, EntryIdx)>>, edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, } impl Instance { fn load( num_nodes: usize, num_edges: usize, read_edges: impl FnOnce(&mut ParsedEdgeHandler) -> Result<()>, ) -> Result<Self> { let mut handler = ParsedEdgeHandler { edge_incidences: Vec::with_capacity(num_edges), node_degrees: vec![0; num_nodes], }; read_edges(&mut handler)?; let ParsedEdgeHandler { mut edge_incidences, node_degrees, } = handler; let mut node_incidences: Vec<_> = node_degrees .iter() .map(|&len| SkipVec::with_len(len)) .collect(); let mut rem_node_degrees = node_degrees; for (edge, incidences) in edge_incidences.iter_mut().enumerate() { let edge = EdgeIdx::from(edge); for (edge_entry_idx, edge_entry) in incidences.iter_mut() { let node = edge_entry.0.idx(); let node_entry_idx = node_incidences[node].len() - rem_node_degrees[node]; rem_node_degrees[node] -= 1; edge_entry.1 = EntryIdx::from(node_entry_idx); node_incidences[node][node_entry_idx] = (edge, EntryIdx::from(edge_entry_idx)); } } Ok(Self { nodes: (0..num_nodes).map(NodeIdx::from).collect(), edges: (0..num_edges).map(EdgeIdx::from).collect(), node_incidences, edge_incidences, }) } pub fn load_from_text(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); let mut line = String::new(); reader.read_line(&mut line)?; let mut numbers = line.split_ascii_whitespace().map(str::parse); let num_nodes = numbers .next() .ok_or_else(|| anyhow!("Missing node count"))??; let num_edges = numbers .next() .ok_or_else(|| anyhow!("Missing edge count"))??; ensure!( numbers.next().is_none(), "Too many numbers in first input line" ); let instance = Self::load(num_nodes, num_edges, |handler| { for _ in 0..num_edges { line.clear(); reader.read_line(&mut line)?; let mut numbers = line .split_ascii_whitespace() .map(|s| s.parse::<usize>().map_err(Error::from)); // Skip degree numbers .next() .ok_or_else(|| anyhow!("empty edge line in input, expected degree"))??; handler.handle_edge(numbers)?; } Ok(()) })?; info!( "Loaded text instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn load_from_json(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); // Usually faster for large inputs, see https://github.com/serde-rs/json/issues/160 let mut text = String::new(); reader.read_to_string(&mut text)?; let JsonInstance { num_nodes, edges } = serde_json::from_str(&text)?; let num_edges = edges.len(); let instance = Self::load(num_nodes, num_edges, |handler| { for edge in edges { handler.handle_edge(edge.into_iter().map(Ok))?; } Ok(()) })?; info!( "Loaded json instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn num_edges(&self) -> usize { self.edges.len() } pub fn num_nodes_total(&self) -> usize { self.node_incidences.len() } pub fn num_edges_total(&self) -> usize { self.edge_incidences.len() } /// Edges incident to a node, sorted by increasing indices. pub fn node( &self, node: NodeIdx, ) -> impl Iterator<Item = EdgeIdx> + ExactSizeIterator + Clone + '_ { self.node_incidences[node.idx()] .iter() .map(|(_, (edge, _))| *edge) } /// Nodes incident to an edge, sorted by increasing indices. pub fn edge( &self, edge: EdgeIdx, ) -> impl Iterator<Item = NodeIdx> + ExactSizeIterator + Clone + '_ { self.edge_incidences[edge.idx()] .iter() .map(|(_, (node, _))| *node) } /// Alive nodes in the instance, in arbitrary order. pub fn nodes(&self) -> &[NodeIdx] { &self.nodes } /// Alive edges in the instance, in arbitrary order. pub fn edges(&self) -> &[EdgeIdx] { &self.edges } pub fn node_degree(&self, node: NodeIdx) -> usize { self.node_incidences[node.idx()].len() } pub fn edge_size(&self, edge: EdgeIdx) -> usize { self.edge_incidences[edge.idx()].len() } /// Deletes a node from the instance. pub fn delete_node(&mut self, node: NodeIdx) { trace!("Deleting node {}", node); for (_idx, (edge, entry_idx)) in &self.node_incidences[node.idx()] { self.edge_incidences[edge.idx()].delete(entry_idx.idx()); } self.nodes.delete(node.idx()); } /// Deletes an edge from the instance. pub fn delete_edge(&mut self, edge: EdgeIdx) { trace!("Deleting edge {}", edge); for (_idx, (node, entry_idx)) in &self.edge_incidences[edge.idx()] { self.node_incidences[node.idx()].delete(entry_idx.idx()); } self.edges.delete(edge.idx()); } /// Restores a previously deleted node. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn restore_node(&mut self, node: NodeIdx) { trace!("Restoring node {}", node); for (_idx, (edge, entry_idx)) in self.node_incidences[node.idx()].iter().rev() { self.edge_incidences[edge.idx()].restore(entry_idx.idx()); } self.nodes.restore(node.idx()); } /// Restores a previously deleted edge. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn restore_edge(&mut self, edge: EdgeIdx) { trace!("Restoring edge {}", edge); for (_idx, (node, entry_idx)) in self.edge_incidences[edge.idx()].iter().rev() { self.node_incidences[node.idx()].restore(entry_idx.idx()); } self.edges.restore(edge.idx()); } /// Deletes all edges incident to a node. /// /// The node itself must have already been deleted. pub fn delete_incident_edges(&mut self, node: NodeIdx) { // We want to iterate over the incidence of `node` while deleting // edges, which in turn changes node incidences. This is safe, since // `node` itself was already deleted. To make the borrow checker // accept this, we temporarily move `node` incidence to a local // variable, replacing it with an empty list. This should not be much // slower than unsafe alternatives, since an incidence list is only // 28 bytes large. trace!("Deleting all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to delete_incident_edges must be deleted" ); let incidence = mem::take(&mut self.node_incidences[node.idx()]); for (_, (edge, _)) in &incidence { self.delete_edge(*edge); } self.node_incidences[node.idx()] = incidence; } /// Restores all incident edges to a node. /// /// This reverses the effect of `delete_incident_edges`. As with all other /// `restore_*` methods, this must be done in reverse order of deletions. /// In particular, the node itself must still be deleted. pub fn restore_incident_edges(&mut self, node: NodeIdx) { trace!("Restoring all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to restore_incident_edges must be deleted" ); // See `delete_incident_edges` for an explanation of this swapping around let incidence = mem::take(&mut self.node_incidences[node.idx()]); // It is important that we restore the edges in reverse order for (_, (edge, _)) in incidence.iter().rev() { self.restore_edge(*edge); } self.node_incidences[node.idx()] = incidence; } pub fn export_as_ilp(&self, mut writer: impl Write) -> Result<()> { writeln!(writer, "Minimize")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " + v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "Subject To")?; for &edge in self.edges() { write!(writer, " e{}: ", CompressedIlpName(edge))?; for (idx, node) in self.edge(edge).enumerate() { if idx > 0
write!(writer, "v{}", CompressedIlpName(node))?; } writeln!(writer, " >= 1")?; } writeln!(writer, "Binaries")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "End")?; Ok(()) } }
{ write!(writer, " + ")?; }
conditional_block
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, time::Instant, }; create_idx_struct!(pub NodeIdx); create_idx_struct!(pub EdgeIdx); create_idx_struct!(pub EntryIdx); #[derive(Debug)] struct CompressedIlpName<T>(T); impl<T: SmallIdx> Display for CompressedIlpName<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; let mut val = self.0.idx(); while val!= 0 { f.write_char(char::from(CHARS[val % CHARS.len()]))?; val /= CHARS.len(); } Ok(()) } } #[derive(Debug)] struct ParsedEdgeHandler { edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, node_degrees: Vec<usize>, } impl ParsedEdgeHandler { fn handle_edge(&mut self, node_indices: impl IntoIterator<Item = Result<usize>>) -> Result<()> { let incidences = SkipVec::try_sorted_from(node_indices.into_iter().map(|idx_result| { idx_result.and_then(|node_idx| { ensure!( node_idx < self.node_degrees.len(), "invalid node idx in edge: {}", node_idx ); Ok((NodeIdx::from(node_idx), EntryIdx::INVALID)) }) }))?; ensure!(incidences.len() > 0, "edges may not be empty"); for (_, (node, _)) in &incidences { self.node_degrees[node.idx()] += 1; } self.edge_incidences.push(incidences); Ok(()) } } #[derive(Debug, Deserialize)] struct JsonInstance { num_nodes: usize, edges: Vec<Vec<usize>>, } #[derive(Clone, Debug)] pub struct Instance { nodes: ContiguousIdxVec<NodeIdx>, edges: ContiguousIdxVec<EdgeIdx>, node_incidences: Vec<SkipVec<(EdgeIdx, EntryIdx)>>, edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>, } impl Instance { fn load( num_nodes: usize, num_edges: usize, read_edges: impl FnOnce(&mut ParsedEdgeHandler) -> Result<()>, ) -> Result<Self> { let mut handler = ParsedEdgeHandler { edge_incidences: Vec::with_capacity(num_edges), node_degrees: vec![0; num_nodes], }; read_edges(&mut handler)?; let ParsedEdgeHandler { mut edge_incidences, node_degrees, } = handler; let mut node_incidences: Vec<_> = node_degrees .iter() .map(|&len| SkipVec::with_len(len)) .collect(); let mut rem_node_degrees = node_degrees; for (edge, incidences) in edge_incidences.iter_mut().enumerate() { let edge = EdgeIdx::from(edge); for (edge_entry_idx, edge_entry) in incidences.iter_mut() { let node = edge_entry.0.idx(); let node_entry_idx = node_incidences[node].len() - rem_node_degrees[node]; rem_node_degrees[node] -= 1; edge_entry.1 = EntryIdx::from(node_entry_idx); node_incidences[node][node_entry_idx] = (edge, EntryIdx::from(edge_entry_idx)); } } Ok(Self { nodes: (0..num_nodes).map(NodeIdx::from).collect(), edges: (0..num_edges).map(EdgeIdx::from).collect(), node_incidences, edge_incidences, }) } pub fn load_from_text(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); let mut line = String::new(); reader.read_line(&mut line)?; let mut numbers = line.split_ascii_whitespace().map(str::parse); let num_nodes = numbers .next() .ok_or_else(|| anyhow!("Missing node count"))??; let num_edges = numbers .next() .ok_or_else(|| anyhow!("Missing edge count"))??; ensure!( numbers.next().is_none(), "Too many numbers in first input line" ); let instance = Self::load(num_nodes, num_edges, |handler| { for _ in 0..num_edges { line.clear(); reader.read_line(&mut line)?; let mut numbers = line .split_ascii_whitespace() .map(|s| s.parse::<usize>().map_err(Error::from)); // Skip degree numbers .next() .ok_or_else(|| anyhow!("empty edge line in input, expected degree"))??; handler.handle_edge(numbers)?; } Ok(()) })?; info!( "Loaded text instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn load_from_json(mut reader: impl BufRead) -> Result<Self> { let time_before = Instant::now(); // Usually faster for large inputs, see https://github.com/serde-rs/json/issues/160 let mut text = String::new(); reader.read_to_string(&mut text)?; let JsonInstance { num_nodes, edges } = serde_json::from_str(&text)?; let num_edges = edges.len(); let instance = Self::load(num_nodes, num_edges, |handler| { for edge in edges { handler.handle_edge(edge.into_iter().map(Ok))?; } Ok(()) })?; info!( "Loaded json instance with {} nodes, {} edges in {:.2?}", num_nodes, num_edges, time_before.elapsed(), ); Ok(instance) } pub fn num_edges(&self) -> usize { self.edges.len() } pub fn num_nodes_total(&self) -> usize { self.node_incidences.len() } pub fn num_edges_total(&self) -> usize { self.edge_incidences.len() } /// Edges incident to a node, sorted by increasing indices. pub fn node( &self, node: NodeIdx, ) -> impl Iterator<Item = EdgeIdx> + ExactSizeIterator + Clone + '_ { self.node_incidences[node.idx()] .iter() .map(|(_, (edge, _))| *edge) } /// Nodes incident to an edge, sorted by increasing indices. pub fn edge( &self, edge: EdgeIdx, ) -> impl Iterator<Item = NodeIdx> + ExactSizeIterator + Clone + '_ { self.edge_incidences[edge.idx()] .iter() .map(|(_, (node, _))| *node) } /// Alive nodes in the instance, in arbitrary order. pub fn nodes(&self) -> &[NodeIdx] { &self.nodes } /// Alive edges in the instance, in arbitrary order. pub fn edges(&self) -> &[EdgeIdx] { &self.edges } pub fn node_degree(&self, node: NodeIdx) -> usize { self.node_incidences[node.idx()].len() } pub fn edge_size(&self, edge: EdgeIdx) -> usize { self.edge_incidences[edge.idx()].len() } /// Deletes a node from the instance. pub fn delete_node(&mut self, node: NodeIdx) { trace!("Deleting node {}", node); for (_idx, (edge, entry_idx)) in &self.node_incidences[node.idx()] { self.edge_incidences[edge.idx()].delete(entry_idx.idx()); } self.nodes.delete(node.idx()); } /// Deletes an edge from the instance. pub fn delete_edge(&mut self, edge: EdgeIdx) { trace!("Deleting edge {}", edge); for (_idx, (node, entry_idx)) in &self.edge_incidences[edge.idx()] { self.node_incidences[node.idx()].delete(entry_idx.idx()); } self.edges.delete(edge.idx()); } /// Restores a previously deleted node. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn restore_node(&mut self, node: NodeIdx) { trace!("Restoring node {}", node); for (_idx, (edge, entry_idx)) in self.node_incidences[node.idx()].iter().rev() { self.edge_incidences[edge.idx()].restore(entry_idx.idx()); } self.nodes.restore(node.idx()); } /// Restores a previously deleted edge. /// /// All restore operations (node or edge) must be done in reverse order of /// the corresponding deletions to produce sensible results. pub fn
(&mut self, edge: EdgeIdx) { trace!("Restoring edge {}", edge); for (_idx, (node, entry_idx)) in self.edge_incidences[edge.idx()].iter().rev() { self.node_incidences[node.idx()].restore(entry_idx.idx()); } self.edges.restore(edge.idx()); } /// Deletes all edges incident to a node. /// /// The node itself must have already been deleted. pub fn delete_incident_edges(&mut self, node: NodeIdx) { // We want to iterate over the incidence of `node` while deleting // edges, which in turn changes node incidences. This is safe, since // `node` itself was already deleted. To make the borrow checker // accept this, we temporarily move `node` incidence to a local // variable, replacing it with an empty list. This should not be much // slower than unsafe alternatives, since an incidence list is only // 28 bytes large. trace!("Deleting all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to delete_incident_edges must be deleted" ); let incidence = mem::take(&mut self.node_incidences[node.idx()]); for (_, (edge, _)) in &incidence { self.delete_edge(*edge); } self.node_incidences[node.idx()] = incidence; } /// Restores all incident edges to a node. /// /// This reverses the effect of `delete_incident_edges`. As with all other /// `restore_*` methods, this must be done in reverse order of deletions. /// In particular, the node itself must still be deleted. pub fn restore_incident_edges(&mut self, node: NodeIdx) { trace!("Restoring all edges incident to {}", node); debug_assert!( self.nodes.is_deleted(node.idx()), "Node passed to restore_incident_edges must be deleted" ); // See `delete_incident_edges` for an explanation of this swapping around let incidence = mem::take(&mut self.node_incidences[node.idx()]); // It is important that we restore the edges in reverse order for (_, (edge, _)) in incidence.iter().rev() { self.restore_edge(*edge); } self.node_incidences[node.idx()] = incidence; } pub fn export_as_ilp(&self, mut writer: impl Write) -> Result<()> { writeln!(writer, "Minimize")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " + v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "Subject To")?; for &edge in self.edges() { write!(writer, " e{}: ", CompressedIlpName(edge))?; for (idx, node) in self.edge(edge).enumerate() { if idx > 0 { write!(writer, " + ")?; } write!(writer, "v{}", CompressedIlpName(node))?; } writeln!(writer, " >= 1")?; } writeln!(writer, "Binaries")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " v{}", CompressedIlpName(node))?; } writeln!(writer)?; writeln!(writer, "End")?; Ok(()) } }
restore_edge
identifier_name
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, info}; use std::{collections::HashMap, fmt::Debug}; use std::{sync::Arc, time::Instant}; use threads::AsyncRunner; use tokio::runtime::Builder; use lazy_static::*; use tokio::runtime::Runtime; use work::{Workload, WorkloadHandle, WorkloadStatus}; use async_trait::async_trait; pub mod cfg; pub mod comm; pub mod plugins; pub mod prom; pub mod threads; pub mod work; pub mod channels { pub const AGENT_CHANNEL: &'static str = "Agent"; } // Configuration lazy_static! { static ref SETTINGS: RwLock<Config> = RwLock::new(Config::default()); } impl<'a> Default for Agent { fn default() -> Agent { let agt = Agent { name: "Unnamed Agent".to_string(), features: Vec::default(), runtime: Runtime::new().unwrap(), state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), }; agt } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum AgentState { Ok, Stopped, Error, } #[derive(Clone, Copy, Debug)] pub struct Schedule {} #[derive(Clone, Debug)] pub enum AgentCommand { Start, Schedule(Schedule, Workload), Stop, } #[derive(Debug, Clone)] pub struct FeatureConfig { pub bind_address: [u8; 4], pub bind_port: u16, pub settings: HashMap<String, String>, } #[derive(Clone)] pub struct AgentController { pub agent: Arc<RwLock<Agent>>, pub signal: Option<Sender<()>>, } impl Debug for AgentController { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("Handle for Agent")) } } impl AgentController { pub fn new(name: &str) -> AgentController { let runtime = Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn with_read<F>(&self, closure: F) where F: FnOnce(&RwLockReadGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let agent = handle.read().await; closure(&agent); } pub async fn with_write<F>(&self, closure: F) where F: FnOnce(&mut RwLockWriteGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let mut agent = handle.write().await; closure(&mut agent); drop(agent); } pub async fn send(&self, event: AgentEvent) -> Result<()> { let agent = self.agent.read().await; let mut hub = agent.hub.write().await; let channel = hub.get_or_create(AGENT_CHANNEL); channel .sender .send(event) .map_err(|err| anyhow!("{}", err))?; Ok(()) } pub async fn get_channel(&self, name: &str) -> (Receiver<AgentEvent>, Sender<AgentEvent>) { let agent = self.agent.read().await; let chan = agent.hub.clone().write().await.get_or_create(name); drop(agent); (chan.receiver, chan.sender) } pub fn with_runtime(name: &str, runtime: Runtime) -> AgentController { let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn add_feature(&mut self, handle: FeatureHandle) -> &mut AgentController { let mut agent = self.agent.write().await; agent.features.push(handle); drop(agent); self } pub async fn start(&mut self) -> Receiver<()> { let agent = self.agent.read().await; info!("Feature count: {}", agent.features.len()); for f in &agent.features { let feature_name = f.read().await.name(); let (rx, tx) = self.get_channel(AGENT_CHANNEL).await; f.write().await.init(self.clone()).await; let feature_handle = f.clone(); agent.runtime.spawn(async move { debug!("Spawning feature communication channel."); loop { let fh = feature_handle.clone(); let message = rx .recv() .map_err(|err| anyhow!("Error receiving message: {}", err)); if let Ok(message) = message { info!("Got AgentEvent {}", message); let mut feature = fh.write().await; feature.on_event(message.clone()).await; debug!("Done writing event to feature"); } } }); let _ = tx .send(AgentEvent::Started) .map_err(|err| { anyhow!( "Error sending Agent Start event to {}: {}", feature_name, err ) }) .unwrap(); } drop(agent); self.agent.write().await.state = AgentState::Ok; let (rx, tx) = crossbeam_channel::bounded::<()>(1); self.signal = Some(rx); tx } pub async fn schedule<T>(&self, interval : Duration, func : T) where T : Fn() -> () + Clone + Send +'static { let handle = { let agent = self.agent.read().await; agent.runtime.handle().clone() }; let f = func.clone(); handle.spawn(async move { info!("Starting scheduled function"); loop { f.clone()(); delay_for(interval).await; } }); } } /* impl FeatureHandle { pub fn new<T>(feature: T) -> FeatureHandle where T: Feature +'static, { FeatureHandle { handle: Arc::new(tokio::sync::RwLock::new(feature)), } } } impl<'a> FeatureHandle { pub async fn with_write<F>(&self, callback: F) where F: FnOnce(&mut RwLockWriteGuard<dyn Feature>) + Sync + Send +'static, { callback(&mut self.handle.write().await); } pub async fn with_read<F>(&self, callback: F) where F: FnOnce(&RwLockReadGuard<dyn Feature>) + Sync + Send +'static, { callback(&self.handle.read().await); } }*/ type HubHandle = Arc<RwLock<Hub<AgentEvent>>>; pub struct Agent { pub name: String, pub features: Vec<FeatureHandle>, pub state: AgentState, pub runtime: Runtime, pub hub: HubHandle, pub work_handles: Vec<Arc<tokio::sync::RwLock<WorkloadHandle>>>, } impl Agent { pub fn new(name: &str) -> Agent { Agent { name: name.to_string(), ..Default::default() } } pub fn with_runtime(name: &str, runtime: Runtime) -> Agent { Agent { name: name.to_string(), features: Vec::default(), runtime: runtime, state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), } } pub fn status(&self) -> AgentState { self.state } /// Run a command on the agent. pub async fn command(&mut self, cmd: AgentCommand) { let channel = self.hub.write().await.get_or_create(AGENT_CHANNEL); match cmd { AgentCommand::Start => { self.state = AgentState::Ok; let work_handles = self.work_handles.clone(); println!("Workload handles: {}", work_handles.len()); // rerun defered workload handles for wl in work_handles { let wl2 = wl.clone(); let (status, workload) = AsyncRunner::block_on(async move { let wl = wl.read().await; (wl.status.clone(), wl.workload.as_ref().unwrap().clone()) }); if status == WorkloadStatus::None { self.run(workload); } AsyncRunner::block_on(async move { let mut handle = wl2.write().await; handle.status = WorkloadStatus::Complete; }); } channel.sender.send(AgentEvent::Started).unwrap(); } AgentCommand::Schedule(_, _) => {} AgentCommand::Stop => { self.state = AgentState::Stopped; channel.sender.send(AgentEvent::Stopped).unwrap(); } } } /// Run a workload in the agent /// This will capture the statistics of the workload run and store it in /// the agent. pub fn run(&mut self, workload: Workload) -> Arc<tokio::sync::RwLock<WorkloadHandle>>
let jh = self.runtime.spawn(async move { info!("[Workload {}] Running.", id); let start = Instant::now(); let result = workload.run().await; let mills = start.elapsed().as_millis(); info!("[Workload {}] Duration: {}ms", id, mills as f64); prom::WORKLOAD_TOTAL_TIME.inc_by(mills as i64); crate::prom::WORKLOAD_TIME_COLLECTOR .with_label_values(&["processing_time"]) .observe(mills as f64 / 1000.); match result { Ok(wl) => { prom::WORKLOAD_COMPLETE.inc(); Ok(wl) } Err(_) => { prom::WORKLOAD_ERROR.inc(); Err(anyhow!("Workload run failed.")) } } }); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: id, join_handle: Some(jh), status: work::WorkloadStatus::Running, ..Default::default() })); self.work_handles.push(work_handle.clone()); work_handle } } pub type FeatureHandle = Arc<tokio::sync::RwLock<dyn Feature>>; #[async_trait] pub trait Feature: Send + Sync { async fn init(&mut self, agent: AgentController); async fn on_event(&mut self, event: AgentEvent); fn name(&self) -> String; }
{ if self.state == AgentState::Stopped { info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: workload.id, join_handle: None, status: WorkloadStatus::None, workload: Some(workload), ..Default::default() })); self.work_handles.push(work_handle.clone()); return work_handle; } let id = workload.id; prom::WORKLOAD_START.inc();
identifier_body
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, info}; use std::{collections::HashMap, fmt::Debug}; use std::{sync::Arc, time::Instant}; use threads::AsyncRunner; use tokio::runtime::Builder; use lazy_static::*; use tokio::runtime::Runtime; use work::{Workload, WorkloadHandle, WorkloadStatus}; use async_trait::async_trait; pub mod cfg; pub mod comm; pub mod plugins; pub mod prom; pub mod threads; pub mod work; pub mod channels { pub const AGENT_CHANNEL: &'static str = "Agent"; } // Configuration lazy_static! { static ref SETTINGS: RwLock<Config> = RwLock::new(Config::default()); } impl<'a> Default for Agent { fn default() -> Agent { let agt = Agent { name: "Unnamed Agent".to_string(), features: Vec::default(), runtime: Runtime::new().unwrap(), state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), }; agt } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum AgentState { Ok, Stopped, Error, } #[derive(Clone, Copy, Debug)] pub struct Schedule {} #[derive(Clone, Debug)] pub enum AgentCommand { Start, Schedule(Schedule, Workload), Stop, } #[derive(Debug, Clone)] pub struct FeatureConfig { pub bind_address: [u8; 4], pub bind_port: u16, pub settings: HashMap<String, String>, } #[derive(Clone)] pub struct AgentController { pub agent: Arc<RwLock<Agent>>, pub signal: Option<Sender<()>>, } impl Debug for AgentController { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("Handle for Agent")) } } impl AgentController { pub fn new(name: &str) -> AgentController { let runtime = Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn with_read<F>(&self, closure: F) where F: FnOnce(&RwLockReadGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let agent = handle.read().await; closure(&agent); } pub async fn with_write<F>(&self, closure: F) where F: FnOnce(&mut RwLockWriteGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let mut agent = handle.write().await; closure(&mut agent); drop(agent); } pub async fn send(&self, event: AgentEvent) -> Result<()> { let agent = self.agent.read().await; let mut hub = agent.hub.write().await; let channel = hub.get_or_create(AGENT_CHANNEL); channel .sender .send(event) .map_err(|err| anyhow!("{}", err))?; Ok(()) } pub async fn get_channel(&self, name: &str) -> (Receiver<AgentEvent>, Sender<AgentEvent>) { let agent = self.agent.read().await; let chan = agent.hub.clone().write().await.get_or_create(name); drop(agent); (chan.receiver, chan.sender) } pub fn with_runtime(name: &str, runtime: Runtime) -> AgentController { let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn add_feature(&mut self, handle: FeatureHandle) -> &mut AgentController { let mut agent = self.agent.write().await; agent.features.push(handle); drop(agent); self } pub async fn start(&mut self) -> Receiver<()> { let agent = self.agent.read().await; info!("Feature count: {}", agent.features.len()); for f in &agent.features { let feature_name = f.read().await.name(); let (rx, tx) = self.get_channel(AGENT_CHANNEL).await; f.write().await.init(self.clone()).await; let feature_handle = f.clone(); agent.runtime.spawn(async move { debug!("Spawning feature communication channel."); loop { let fh = feature_handle.clone(); let message = rx .recv() .map_err(|err| anyhow!("Error receiving message: {}", err)); if let Ok(message) = message { info!("Got AgentEvent {}", message); let mut feature = fh.write().await; feature.on_event(message.clone()).await; debug!("Done writing event to feature"); } } }); let _ = tx .send(AgentEvent::Started) .map_err(|err| { anyhow!( "Error sending Agent Start event to {}: {}", feature_name, err ) }) .unwrap(); } drop(agent); self.agent.write().await.state = AgentState::Ok; let (rx, tx) = crossbeam_channel::bounded::<()>(1); self.signal = Some(rx); tx } pub async fn schedule<T>(&self, interval : Duration, func : T) where T : Fn() -> () + Clone + Send +'static { let handle = { let agent = self.agent.read().await; agent.runtime.handle().clone() }; let f = func.clone(); handle.spawn(async move { info!("Starting scheduled function"); loop { f.clone()(); delay_for(interval).await; } }); } } /* impl FeatureHandle { pub fn new<T>(feature: T) -> FeatureHandle where T: Feature +'static, { FeatureHandle { handle: Arc::new(tokio::sync::RwLock::new(feature)), } } } impl<'a> FeatureHandle { pub async fn with_write<F>(&self, callback: F) where F: FnOnce(&mut RwLockWriteGuard<dyn Feature>) + Sync + Send +'static, { callback(&mut self.handle.write().await); } pub async fn with_read<F>(&self, callback: F) where F: FnOnce(&RwLockReadGuard<dyn Feature>) + Sync + Send +'static, { callback(&self.handle.read().await); } }*/ type HubHandle = Arc<RwLock<Hub<AgentEvent>>>; pub struct Agent { pub name: String, pub features: Vec<FeatureHandle>, pub state: AgentState, pub runtime: Runtime, pub hub: HubHandle, pub work_handles: Vec<Arc<tokio::sync::RwLock<WorkloadHandle>>>, } impl Agent { pub fn new(name: &str) -> Agent { Agent { name: name.to_string(), ..Default::default() } } pub fn with_runtime(name: &str, runtime: Runtime) -> Agent { Agent { name: name.to_string(), features: Vec::default(), runtime: runtime, state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), } } pub fn status(&self) -> AgentState { self.state } /// Run a command on the agent. pub async fn command(&mut self, cmd: AgentCommand) { let channel = self.hub.write().await.get_or_create(AGENT_CHANNEL); match cmd { AgentCommand::Start => { self.state = AgentState::Ok; let work_handles = self.work_handles.clone(); println!("Workload handles: {}", work_handles.len()); // rerun defered workload handles for wl in work_handles { let wl2 = wl.clone(); let (status, workload) = AsyncRunner::block_on(async move { let wl = wl.read().await; (wl.status.clone(), wl.workload.as_ref().unwrap().clone()) }); if status == WorkloadStatus::None { self.run(workload); } AsyncRunner::block_on(async move { let mut handle = wl2.write().await; handle.status = WorkloadStatus::Complete; }); } channel.sender.send(AgentEvent::Started).unwrap(); } AgentCommand::Schedule(_, _) =>
AgentCommand::Stop => { self.state = AgentState::Stopped; channel.sender.send(AgentEvent::Stopped).unwrap(); } } } /// Run a workload in the agent /// This will capture the statistics of the workload run and store it in /// the agent. pub fn run(&mut self, workload: Workload) -> Arc<tokio::sync::RwLock<WorkloadHandle>> { if self.state == AgentState::Stopped { info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: workload.id, join_handle: None, status: WorkloadStatus::None, workload: Some(workload), ..Default::default() })); self.work_handles.push(work_handle.clone()); return work_handle; } let id = workload.id; prom::WORKLOAD_START.inc(); let jh = self.runtime.spawn(async move { info!("[Workload {}] Running.", id); let start = Instant::now(); let result = workload.run().await; let mills = start.elapsed().as_millis(); info!("[Workload {}] Duration: {}ms", id, mills as f64); prom::WORKLOAD_TOTAL_TIME.inc_by(mills as i64); crate::prom::WORKLOAD_TIME_COLLECTOR .with_label_values(&["processing_time"]) .observe(mills as f64 / 1000.); match result { Ok(wl) => { prom::WORKLOAD_COMPLETE.inc(); Ok(wl) } Err(_) => { prom::WORKLOAD_ERROR.inc(); Err(anyhow!("Workload run failed.")) } } }); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: id, join_handle: Some(jh), status: work::WorkloadStatus::Running, ..Default::default() })); self.work_handles.push(work_handle.clone()); work_handle } } pub type FeatureHandle = Arc<tokio::sync::RwLock<dyn Feature>>; #[async_trait] pub trait Feature: Send + Sync { async fn init(&mut self, agent: AgentController); async fn on_event(&mut self, event: AgentEvent); fn name(&self) -> String; }
{}
conditional_block
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, info}; use std::{collections::HashMap, fmt::Debug}; use std::{sync::Arc, time::Instant}; use threads::AsyncRunner; use tokio::runtime::Builder; use lazy_static::*;
use work::{Workload, WorkloadHandle, WorkloadStatus}; use async_trait::async_trait; pub mod cfg; pub mod comm; pub mod plugins; pub mod prom; pub mod threads; pub mod work; pub mod channels { pub const AGENT_CHANNEL: &'static str = "Agent"; } // Configuration lazy_static! { static ref SETTINGS: RwLock<Config> = RwLock::new(Config::default()); } impl<'a> Default for Agent { fn default() -> Agent { let agt = Agent { name: "Unnamed Agent".to_string(), features: Vec::default(), runtime: Runtime::new().unwrap(), state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), }; agt } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum AgentState { Ok, Stopped, Error, } #[derive(Clone, Copy, Debug)] pub struct Schedule {} #[derive(Clone, Debug)] pub enum AgentCommand { Start, Schedule(Schedule, Workload), Stop, } #[derive(Debug, Clone)] pub struct FeatureConfig { pub bind_address: [u8; 4], pub bind_port: u16, pub settings: HashMap<String, String>, } #[derive(Clone)] pub struct AgentController { pub agent: Arc<RwLock<Agent>>, pub signal: Option<Sender<()>>, } impl Debug for AgentController { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("Handle for Agent")) } } impl AgentController { pub fn new(name: &str) -> AgentController { let runtime = Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn with_read<F>(&self, closure: F) where F: FnOnce(&RwLockReadGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let agent = handle.read().await; closure(&agent); } pub async fn with_write<F>(&self, closure: F) where F: FnOnce(&mut RwLockWriteGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let mut agent = handle.write().await; closure(&mut agent); drop(agent); } pub async fn send(&self, event: AgentEvent) -> Result<()> { let agent = self.agent.read().await; let mut hub = agent.hub.write().await; let channel = hub.get_or_create(AGENT_CHANNEL); channel .sender .send(event) .map_err(|err| anyhow!("{}", err))?; Ok(()) } pub async fn get_channel(&self, name: &str) -> (Receiver<AgentEvent>, Sender<AgentEvent>) { let agent = self.agent.read().await; let chan = agent.hub.clone().write().await.get_or_create(name); drop(agent); (chan.receiver, chan.sender) } pub fn with_runtime(name: &str, runtime: Runtime) -> AgentController { let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn add_feature(&mut self, handle: FeatureHandle) -> &mut AgentController { let mut agent = self.agent.write().await; agent.features.push(handle); drop(agent); self } pub async fn start(&mut self) -> Receiver<()> { let agent = self.agent.read().await; info!("Feature count: {}", agent.features.len()); for f in &agent.features { let feature_name = f.read().await.name(); let (rx, tx) = self.get_channel(AGENT_CHANNEL).await; f.write().await.init(self.clone()).await; let feature_handle = f.clone(); agent.runtime.spawn(async move { debug!("Spawning feature communication channel."); loop { let fh = feature_handle.clone(); let message = rx .recv() .map_err(|err| anyhow!("Error receiving message: {}", err)); if let Ok(message) = message { info!("Got AgentEvent {}", message); let mut feature = fh.write().await; feature.on_event(message.clone()).await; debug!("Done writing event to feature"); } } }); let _ = tx .send(AgentEvent::Started) .map_err(|err| { anyhow!( "Error sending Agent Start event to {}: {}", feature_name, err ) }) .unwrap(); } drop(agent); self.agent.write().await.state = AgentState::Ok; let (rx, tx) = crossbeam_channel::bounded::<()>(1); self.signal = Some(rx); tx } pub async fn schedule<T>(&self, interval : Duration, func : T) where T : Fn() -> () + Clone + Send +'static { let handle = { let agent = self.agent.read().await; agent.runtime.handle().clone() }; let f = func.clone(); handle.spawn(async move { info!("Starting scheduled function"); loop { f.clone()(); delay_for(interval).await; } }); } } /* impl FeatureHandle { pub fn new<T>(feature: T) -> FeatureHandle where T: Feature +'static, { FeatureHandle { handle: Arc::new(tokio::sync::RwLock::new(feature)), } } } impl<'a> FeatureHandle { pub async fn with_write<F>(&self, callback: F) where F: FnOnce(&mut RwLockWriteGuard<dyn Feature>) + Sync + Send +'static, { callback(&mut self.handle.write().await); } pub async fn with_read<F>(&self, callback: F) where F: FnOnce(&RwLockReadGuard<dyn Feature>) + Sync + Send +'static, { callback(&self.handle.read().await); } }*/ type HubHandle = Arc<RwLock<Hub<AgentEvent>>>; pub struct Agent { pub name: String, pub features: Vec<FeatureHandle>, pub state: AgentState, pub runtime: Runtime, pub hub: HubHandle, pub work_handles: Vec<Arc<tokio::sync::RwLock<WorkloadHandle>>>, } impl Agent { pub fn new(name: &str) -> Agent { Agent { name: name.to_string(), ..Default::default() } } pub fn with_runtime(name: &str, runtime: Runtime) -> Agent { Agent { name: name.to_string(), features: Vec::default(), runtime: runtime, state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), } } pub fn status(&self) -> AgentState { self.state } /// Run a command on the agent. pub async fn command(&mut self, cmd: AgentCommand) { let channel = self.hub.write().await.get_or_create(AGENT_CHANNEL); match cmd { AgentCommand::Start => { self.state = AgentState::Ok; let work_handles = self.work_handles.clone(); println!("Workload handles: {}", work_handles.len()); // rerun defered workload handles for wl in work_handles { let wl2 = wl.clone(); let (status, workload) = AsyncRunner::block_on(async move { let wl = wl.read().await; (wl.status.clone(), wl.workload.as_ref().unwrap().clone()) }); if status == WorkloadStatus::None { self.run(workload); } AsyncRunner::block_on(async move { let mut handle = wl2.write().await; handle.status = WorkloadStatus::Complete; }); } channel.sender.send(AgentEvent::Started).unwrap(); } AgentCommand::Schedule(_, _) => {} AgentCommand::Stop => { self.state = AgentState::Stopped; channel.sender.send(AgentEvent::Stopped).unwrap(); } } } /// Run a workload in the agent /// This will capture the statistics of the workload run and store it in /// the agent. pub fn run(&mut self, workload: Workload) -> Arc<tokio::sync::RwLock<WorkloadHandle>> { if self.state == AgentState::Stopped { info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: workload.id, join_handle: None, status: WorkloadStatus::None, workload: Some(workload), ..Default::default() })); self.work_handles.push(work_handle.clone()); return work_handle; } let id = workload.id; prom::WORKLOAD_START.inc(); let jh = self.runtime.spawn(async move { info!("[Workload {}] Running.", id); let start = Instant::now(); let result = workload.run().await; let mills = start.elapsed().as_millis(); info!("[Workload {}] Duration: {}ms", id, mills as f64); prom::WORKLOAD_TOTAL_TIME.inc_by(mills as i64); crate::prom::WORKLOAD_TIME_COLLECTOR .with_label_values(&["processing_time"]) .observe(mills as f64 / 1000.); match result { Ok(wl) => { prom::WORKLOAD_COMPLETE.inc(); Ok(wl) } Err(_) => { prom::WORKLOAD_ERROR.inc(); Err(anyhow!("Workload run failed.")) } } }); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: id, join_handle: Some(jh), status: work::WorkloadStatus::Running, ..Default::default() })); self.work_handles.push(work_handle.clone()); work_handle } } pub type FeatureHandle = Arc<tokio::sync::RwLock<dyn Feature>>; #[async_trait] pub trait Feature: Send + Sync { async fn init(&mut self, agent: AgentController); async fn on_event(&mut self, event: AgentEvent); fn name(&self) -> String; }
use tokio::runtime::Runtime;
random_line_split
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, info}; use std::{collections::HashMap, fmt::Debug}; use std::{sync::Arc, time::Instant}; use threads::AsyncRunner; use tokio::runtime::Builder; use lazy_static::*; use tokio::runtime::Runtime; use work::{Workload, WorkloadHandle, WorkloadStatus}; use async_trait::async_trait; pub mod cfg; pub mod comm; pub mod plugins; pub mod prom; pub mod threads; pub mod work; pub mod channels { pub const AGENT_CHANNEL: &'static str = "Agent"; } // Configuration lazy_static! { static ref SETTINGS: RwLock<Config> = RwLock::new(Config::default()); } impl<'a> Default for Agent { fn default() -> Agent { let agt = Agent { name: "Unnamed Agent".to_string(), features: Vec::default(), runtime: Runtime::new().unwrap(), state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), }; agt } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum AgentState { Ok, Stopped, Error, } #[derive(Clone, Copy, Debug)] pub struct Schedule {} #[derive(Clone, Debug)] pub enum
{ Start, Schedule(Schedule, Workload), Stop, } #[derive(Debug, Clone)] pub struct FeatureConfig { pub bind_address: [u8; 4], pub bind_port: u16, pub settings: HashMap<String, String>, } #[derive(Clone)] pub struct AgentController { pub agent: Arc<RwLock<Agent>>, pub signal: Option<Sender<()>>, } impl Debug for AgentController { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_fmt(format_args!("Handle for Agent")) } } impl AgentController { pub fn new(name: &str) -> AgentController { let runtime = Builder::new() .threaded_scheduler() .enable_all() .build() .unwrap(); let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn with_read<F>(&self, closure: F) where F: FnOnce(&RwLockReadGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let agent = handle.read().await; closure(&agent); } pub async fn with_write<F>(&self, closure: F) where F: FnOnce(&mut RwLockWriteGuard<Agent>) + Sync + Send +'static, { let handle = self.agent.clone(); let mut agent = handle.write().await; closure(&mut agent); drop(agent); } pub async fn send(&self, event: AgentEvent) -> Result<()> { let agent = self.agent.read().await; let mut hub = agent.hub.write().await; let channel = hub.get_or_create(AGENT_CHANNEL); channel .sender .send(event) .map_err(|err| anyhow!("{}", err))?; Ok(()) } pub async fn get_channel(&self, name: &str) -> (Receiver<AgentEvent>, Sender<AgentEvent>) { let agent = self.agent.read().await; let chan = agent.hub.clone().write().await.get_or_create(name); drop(agent); (chan.receiver, chan.sender) } pub fn with_runtime(name: &str, runtime: Runtime) -> AgentController { let agent = Agent::with_runtime(name, runtime); AgentController { agent: Arc::new(RwLock::new(agent)), signal: None, } } pub async fn add_feature(&mut self, handle: FeatureHandle) -> &mut AgentController { let mut agent = self.agent.write().await; agent.features.push(handle); drop(agent); self } pub async fn start(&mut self) -> Receiver<()> { let agent = self.agent.read().await; info!("Feature count: {}", agent.features.len()); for f in &agent.features { let feature_name = f.read().await.name(); let (rx, tx) = self.get_channel(AGENT_CHANNEL).await; f.write().await.init(self.clone()).await; let feature_handle = f.clone(); agent.runtime.spawn(async move { debug!("Spawning feature communication channel."); loop { let fh = feature_handle.clone(); let message = rx .recv() .map_err(|err| anyhow!("Error receiving message: {}", err)); if let Ok(message) = message { info!("Got AgentEvent {}", message); let mut feature = fh.write().await; feature.on_event(message.clone()).await; debug!("Done writing event to feature"); } } }); let _ = tx .send(AgentEvent::Started) .map_err(|err| { anyhow!( "Error sending Agent Start event to {}: {}", feature_name, err ) }) .unwrap(); } drop(agent); self.agent.write().await.state = AgentState::Ok; let (rx, tx) = crossbeam_channel::bounded::<()>(1); self.signal = Some(rx); tx } pub async fn schedule<T>(&self, interval : Duration, func : T) where T : Fn() -> () + Clone + Send +'static { let handle = { let agent = self.agent.read().await; agent.runtime.handle().clone() }; let f = func.clone(); handle.spawn(async move { info!("Starting scheduled function"); loop { f.clone()(); delay_for(interval).await; } }); } } /* impl FeatureHandle { pub fn new<T>(feature: T) -> FeatureHandle where T: Feature +'static, { FeatureHandle { handle: Arc::new(tokio::sync::RwLock::new(feature)), } } } impl<'a> FeatureHandle { pub async fn with_write<F>(&self, callback: F) where F: FnOnce(&mut RwLockWriteGuard<dyn Feature>) + Sync + Send +'static, { callback(&mut self.handle.write().await); } pub async fn with_read<F>(&self, callback: F) where F: FnOnce(&RwLockReadGuard<dyn Feature>) + Sync + Send +'static, { callback(&self.handle.read().await); } }*/ type HubHandle = Arc<RwLock<Hub<AgentEvent>>>; pub struct Agent { pub name: String, pub features: Vec<FeatureHandle>, pub state: AgentState, pub runtime: Runtime, pub hub: HubHandle, pub work_handles: Vec<Arc<tokio::sync::RwLock<WorkloadHandle>>>, } impl Agent { pub fn new(name: &str) -> Agent { Agent { name: name.to_string(), ..Default::default() } } pub fn with_runtime(name: &str, runtime: Runtime) -> Agent { Agent { name: name.to_string(), features: Vec::default(), runtime: runtime, state: AgentState::Stopped, work_handles: Vec::default(), hub: Hub::new(), } } pub fn status(&self) -> AgentState { self.state } /// Run a command on the agent. pub async fn command(&mut self, cmd: AgentCommand) { let channel = self.hub.write().await.get_or_create(AGENT_CHANNEL); match cmd { AgentCommand::Start => { self.state = AgentState::Ok; let work_handles = self.work_handles.clone(); println!("Workload handles: {}", work_handles.len()); // rerun defered workload handles for wl in work_handles { let wl2 = wl.clone(); let (status, workload) = AsyncRunner::block_on(async move { let wl = wl.read().await; (wl.status.clone(), wl.workload.as_ref().unwrap().clone()) }); if status == WorkloadStatus::None { self.run(workload); } AsyncRunner::block_on(async move { let mut handle = wl2.write().await; handle.status = WorkloadStatus::Complete; }); } channel.sender.send(AgentEvent::Started).unwrap(); } AgentCommand::Schedule(_, _) => {} AgentCommand::Stop => { self.state = AgentState::Stopped; channel.sender.send(AgentEvent::Stopped).unwrap(); } } } /// Run a workload in the agent /// This will capture the statistics of the workload run and store it in /// the agent. pub fn run(&mut self, workload: Workload) -> Arc<tokio::sync::RwLock<WorkloadHandle>> { if self.state == AgentState::Stopped { info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: workload.id, join_handle: None, status: WorkloadStatus::None, workload: Some(workload), ..Default::default() })); self.work_handles.push(work_handle.clone()); return work_handle; } let id = workload.id; prom::WORKLOAD_START.inc(); let jh = self.runtime.spawn(async move { info!("[Workload {}] Running.", id); let start = Instant::now(); let result = workload.run().await; let mills = start.elapsed().as_millis(); info!("[Workload {}] Duration: {}ms", id, mills as f64); prom::WORKLOAD_TOTAL_TIME.inc_by(mills as i64); crate::prom::WORKLOAD_TIME_COLLECTOR .with_label_values(&["processing_time"]) .observe(mills as f64 / 1000.); match result { Ok(wl) => { prom::WORKLOAD_COMPLETE.inc(); Ok(wl) } Err(_) => { prom::WORKLOAD_ERROR.inc(); Err(anyhow!("Workload run failed.")) } } }); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: id, join_handle: Some(jh), status: work::WorkloadStatus::Running, ..Default::default() })); self.work_handles.push(work_handle.clone()); work_handle } } pub type FeatureHandle = Arc<tokio::sync::RwLock<dyn Feature>>; #[async_trait] pub trait Feature: Send + Sync { async fn init(&mut self, agent: AgentController); async fn on_event(&mut self, event: AgentEvent); fn name(&self) -> String; }
AgentCommand
identifier_name
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created does live in here. //! //! These below examples have nothing to do with this library as all should be //! done through the [`Tilemap`]. These are just more specific examples which //! use the private API of this library. //! //! [`Tilemap`]: crate::tilemap::Tilemap //! //! # Simple chunk creation //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! // There are two ways to create a new chunk. Either directly... //! //! tilemap.insert_chunk((0, 0)); //! //! // Or indirectly... //! //! let point = (0, 0); //! let sprite_index = 0; //! let tile = Tile { point, sprite_index,..Default::default() }; //! tilemap.insert_tile(tile); //! //! ``` //! //! # Specifying what kind of chunk //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! tilemap.insert_chunk((0, 0)); //! //! let z_order = 0; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! //! let z_order = 1; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! ``` /// Chunk entity. pub(crate) mod entity; /// Sparse and dense chunk layers. mod layer; /// Meshes for rendering to vertices. pub(crate) mod mesh; /// Raw tile that is stored in the chunks. pub mod raw_tile; /// Files and helpers for rendering. pub(crate) mod render; /// Systems for chunks. pub(crate) mod system; use crate::{lib::*, tile::Tile}; pub use layer::LayerKind; use layer::{DenseLayer, LayerKindInner, SparseLayer, SpriteLayer}; pub use raw_tile::RawTile; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, PartialEq, Debug)] #[doc(hidden)] pub(crate) struct Chunk { /// The point coordinate of the chunk. point: Point2, /// The sprite layers of the chunk. sprite_layers: Vec<Option<SpriteLayer>>, /// Ephemeral user data that can be used for flags or other purposes. user_data: u128, /// Contains a map of all collision entities. #[cfg(feature = "bevy_rapier2d")] pub collision_entities: HashMap<usize, Entity>, } impl Chunk { /// A newly constructed chunk from a point and the maximum number of layers. pub(crate) fn new( point: Point2, layers: &[Option<LayerKind>], dimensions: Dimension2, ) -> Chunk { let mut chunk = Chunk { point, sprite_layers: vec![None; layers.len()], user_data: 0, #[cfg(feature = "bevy_rapier2d")] collision_entities: HashMap::default(), }; for (z_order, kind) in layers.iter().enumerate() { if let Some(kind) = kind { chunk.add_layer(kind, z_order, dimensions) } } chunk } /// Adds a layer from a layer kind, the z layer, and dimensions of the /// chunk. pub(crate) fn add_layer(&mut self, kind: &LayerKind, z_order: usize, dimensions: Dimension2) { match kind { LayerKind::Dense => { let tiles = vec![ RawTile { index: 0, color: Color::rgba(0.0, 0.0, 0.0, 0.0) }; dimensions.area() as usize ]; if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Dense(DenseLayer::new(tiles)), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } LayerKind::Sparse => { if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Sparse(SparseLayer::new(HashMap::default())), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } } } /// Returns the point of the location of the chunk. pub(crate) fn point(&self) -> Point2 { self.point } // /// Returns a copy of the user data. // pub(crate) fn user_data(&self) -> u128 { // self.user_data // } // // /// Returns a mutable reference to the user data. // pub(crate) fn user_data_mut(&mut self) -> &mut u128 { // &mut self.user_data // } /// Moves a layer from a z layer to another. pub(crate) fn move_layer(&mut self, from_z: usize, to_z: usize) { // TODO: rename to swap and include it in the greater api if self.sprite_layers.get(to_z).is_some() { error!( "sprite layer {} unexpectedly exists and can not be moved", to_z ); return; } self.sprite_layers.swap(from_z, to_z); } /// Removes a layer from the specified layer. pub(crate) fn remove_layer(&mut self, z_order: usize) { self.sprite_layers.get_mut(z_order).take(); } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().set_mesh(mesh) } else { error!("can not set mesh to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Sets a single raw tile to be added to a z layer and index. pub(crate) fn set_tile<P: Into<Point2>>(&mut self, index: usize, tile: Tile<P>) { if let Some(layer) = self.sprite_layers.get_mut(tile.z_order) { if let Some(layer) = layer.as_mut()
else { error!("can not set tile to sprite layer {}", tile.z_order); } } else { error!("sprite layer {} does not exist", tile.z_order); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, index: usize, z_order: usize) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().remove_tile(index); } else { error!("can not remove tile on sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a z layer, always when it is spawned. pub(crate) fn add_entity(&mut self, z_order: usize, entity: Entity) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.entity = Some(entity); } else { error!("can not add entity to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a tile index in a layer. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn insert_collision_entity( &mut self, index: usize, entity: Entity, ) -> Option<Entity> { self.collision_entities.insert(index, entity) } /// Gets the layers entity, if any. Useful for despawning. pub(crate) fn get_entity(&self, z_order: usize) -> Option<Entity> { self.sprite_layers .get(z_order) .and_then(|o| o.as_ref().and_then(|layer| layer.entity)) } /// Gets the collision entity if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_collision_entity(&self, index: usize) -> Option<Entity> { self.collision_entities.get(&index).cloned() } /// Remove all the layers and collision entities and return them for use with bulk despawning. pub(crate) fn remove_entities(&mut self) -> Vec<Entity> { let mut entities = Vec::new(); for sprite_layer in &mut self.sprite_layers { if let Some(layer) = sprite_layer { if let Some(entity) = layer.entity.take() { entities.push(entity); } } } #[cfg(feature = "bevy_rapier2d")] for (_, entity) in self.collision_entities.drain() { entities.push(entity) } entities } /// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_tile(index)) }) } /// Gets a mutable reference to a tile from a provided z order and index. pub(crate) fn get_tile_mut(&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> { self.sprite_layers.get_mut(z_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) } /// Gets a vec of all the tiles in the layer, if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_tile_indices(&self, z_order: usize) -> Option<Vec<usize>> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .map(|layer| layer.inner.as_ref().get_tile_indices()) }) } /// At the given z layer, changes the tiles into attributes for use with /// the renderer using the given dimensions. /// /// Easier to pass in the dimensions opposed to storing it everywhere. pub(crate) fn tiles_to_renderer_parts( &self, z: usize, dimensions: Dimension2, ) -> Option<(Vec<f32>, Vec<[f32; 4]>)> { let area = dimensions.area() as usize; self.sprite_layers.get(z).and_then(|o| { o.as_ref() .map(|layer| layer.inner.as_ref().tiles_to_attributes(area)) }) } }
{ let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; layer.inner.as_mut().set_tile(index, raw_tile); }
conditional_block
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created does live in here. //! //! These below examples have nothing to do with this library as all should be //! done through the [`Tilemap`]. These are just more specific examples which //! use the private API of this library. //! //! [`Tilemap`]: crate::tilemap::Tilemap //! //! # Simple chunk creation //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! // There are two ways to create a new chunk. Either directly... //! //! tilemap.insert_chunk((0, 0)); //! //! // Or indirectly... //! //! let point = (0, 0); //! let sprite_index = 0; //! let tile = Tile { point, sprite_index,..Default::default() }; //! tilemap.insert_tile(tile); //! //! ``` //! //! # Specifying what kind of chunk //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! tilemap.insert_chunk((0, 0)); //! //! let z_order = 0; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! //! let z_order = 1; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! ``` /// Chunk entity. pub(crate) mod entity; /// Sparse and dense chunk layers. mod layer; /// Meshes for rendering to vertices. pub(crate) mod mesh; /// Raw tile that is stored in the chunks. pub mod raw_tile; /// Files and helpers for rendering. pub(crate) mod render; /// Systems for chunks. pub(crate) mod system; use crate::{lib::*, tile::Tile}; pub use layer::LayerKind; use layer::{DenseLayer, LayerKindInner, SparseLayer, SpriteLayer}; pub use raw_tile::RawTile; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, PartialEq, Debug)] #[doc(hidden)] pub(crate) struct Chunk { /// The point coordinate of the chunk. point: Point2, /// The sprite layers of the chunk. sprite_layers: Vec<Option<SpriteLayer>>, /// Ephemeral user data that can be used for flags or other purposes. user_data: u128, /// Contains a map of all collision entities. #[cfg(feature = "bevy_rapier2d")] pub collision_entities: HashMap<usize, Entity>, } impl Chunk { /// A newly constructed chunk from a point and the maximum number of layers. pub(crate) fn new( point: Point2, layers: &[Option<LayerKind>], dimensions: Dimension2, ) -> Chunk { let mut chunk = Chunk { point, sprite_layers: vec![None; layers.len()], user_data: 0, #[cfg(feature = "bevy_rapier2d")] collision_entities: HashMap::default(), }; for (z_order, kind) in layers.iter().enumerate() { if let Some(kind) = kind { chunk.add_layer(kind, z_order, dimensions) } } chunk } /// Adds a layer from a layer kind, the z layer, and dimensions of the /// chunk. pub(crate) fn add_layer(&mut self, kind: &LayerKind, z_order: usize, dimensions: Dimension2) { match kind { LayerKind::Dense => { let tiles = vec![ RawTile { index: 0, color: Color::rgba(0.0, 0.0, 0.0, 0.0) }; dimensions.area() as usize ]; if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Dense(DenseLayer::new(tiles)), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } LayerKind::Sparse => { if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Sparse(SparseLayer::new(HashMap::default())), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } } } /// Returns the point of the location of the chunk. pub(crate) fn point(&self) -> Point2 { self.point } // /// Returns a copy of the user data. // pub(crate) fn user_data(&self) -> u128 { // self.user_data // } // // /// Returns a mutable reference to the user data. // pub(crate) fn user_data_mut(&mut self) -> &mut u128 { // &mut self.user_data // } /// Moves a layer from a z layer to another. pub(crate) fn move_layer(&mut self, from_z: usize, to_z: usize)
/// Removes a layer from the specified layer. pub(crate) fn remove_layer(&mut self, z_order: usize) { self.sprite_layers.get_mut(z_order).take(); } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().set_mesh(mesh) } else { error!("can not set mesh to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Sets a single raw tile to be added to a z layer and index. pub(crate) fn set_tile<P: Into<Point2>>(&mut self, index: usize, tile: Tile<P>) { if let Some(layer) = self.sprite_layers.get_mut(tile.z_order) { if let Some(layer) = layer.as_mut() { let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; layer.inner.as_mut().set_tile(index, raw_tile); } else { error!("can not set tile to sprite layer {}", tile.z_order); } } else { error!("sprite layer {} does not exist", tile.z_order); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, index: usize, z_order: usize) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().remove_tile(index); } else { error!("can not remove tile on sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a z layer, always when it is spawned. pub(crate) fn add_entity(&mut self, z_order: usize, entity: Entity) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.entity = Some(entity); } else { error!("can not add entity to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a tile index in a layer. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn insert_collision_entity( &mut self, index: usize, entity: Entity, ) -> Option<Entity> { self.collision_entities.insert(index, entity) } /// Gets the layers entity, if any. Useful for despawning. pub(crate) fn get_entity(&self, z_order: usize) -> Option<Entity> { self.sprite_layers .get(z_order) .and_then(|o| o.as_ref().and_then(|layer| layer.entity)) } /// Gets the collision entity if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_collision_entity(&self, index: usize) -> Option<Entity> { self.collision_entities.get(&index).cloned() } /// Remove all the layers and collision entities and return them for use with bulk despawning. pub(crate) fn remove_entities(&mut self) -> Vec<Entity> { let mut entities = Vec::new(); for sprite_layer in &mut self.sprite_layers { if let Some(layer) = sprite_layer { if let Some(entity) = layer.entity.take() { entities.push(entity); } } } #[cfg(feature = "bevy_rapier2d")] for (_, entity) in self.collision_entities.drain() { entities.push(entity) } entities } /// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_tile(index)) }) } /// Gets a mutable reference to a tile from a provided z order and index. pub(crate) fn get_tile_mut(&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> { self.sprite_layers.get_mut(z_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) } /// Gets a vec of all the tiles in the layer, if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_tile_indices(&self, z_order: usize) -> Option<Vec<usize>> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .map(|layer| layer.inner.as_ref().get_tile_indices()) }) } /// At the given z layer, changes the tiles into attributes for use with /// the renderer using the given dimensions. /// /// Easier to pass in the dimensions opposed to storing it everywhere. pub(crate) fn tiles_to_renderer_parts( &self, z: usize, dimensions: Dimension2, ) -> Option<(Vec<f32>, Vec<[f32; 4]>)> { let area = dimensions.area() as usize; self.sprite_layers.get(z).and_then(|o| { o.as_ref() .map(|layer| layer.inner.as_ref().tiles_to_attributes(area)) }) } }
{ // TODO: rename to swap and include it in the greater api if self.sprite_layers.get(to_z).is_some() { error!( "sprite layer {} unexpectedly exists and can not be moved", to_z ); return; } self.sprite_layers.swap(from_z, to_z); }
identifier_body
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created does live in here. //! //! These below examples have nothing to do with this library as all should be //! done through the [`Tilemap`]. These are just more specific examples which //! use the private API of this library. //! //! [`Tilemap`]: crate::tilemap::Tilemap //! //! # Simple chunk creation //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! // There are two ways to create a new chunk. Either directly... //! //! tilemap.insert_chunk((0, 0)); //! //! // Or indirectly... //! //! let point = (0, 0); //! let sprite_index = 0; //! let tile = Tile { point, sprite_index,..Default::default() }; //! tilemap.insert_tile(tile); //! //! ``` //! //! # Specifying what kind of chunk //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! tilemap.insert_chunk((0, 0)); //! //! let z_order = 0; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! //! let z_order = 1; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! ``` /// Chunk entity. pub(crate) mod entity; /// Sparse and dense chunk layers. mod layer; /// Meshes for rendering to vertices. pub(crate) mod mesh; /// Raw tile that is stored in the chunks. pub mod raw_tile; /// Files and helpers for rendering. pub(crate) mod render; /// Systems for chunks. pub(crate) mod system; use crate::{lib::*, tile::Tile}; pub use layer::LayerKind; use layer::{DenseLayer, LayerKindInner, SparseLayer, SpriteLayer}; pub use raw_tile::RawTile; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, PartialEq, Debug)] #[doc(hidden)] pub(crate) struct Chunk { /// The point coordinate of the chunk. point: Point2, /// The sprite layers of the chunk. sprite_layers: Vec<Option<SpriteLayer>>, /// Ephemeral user data that can be used for flags or other purposes. user_data: u128, /// Contains a map of all collision entities. #[cfg(feature = "bevy_rapier2d")] pub collision_entities: HashMap<usize, Entity>, } impl Chunk { /// A newly constructed chunk from a point and the maximum number of layers. pub(crate) fn new( point: Point2, layers: &[Option<LayerKind>], dimensions: Dimension2, ) -> Chunk { let mut chunk = Chunk { point, sprite_layers: vec![None; layers.len()], user_data: 0, #[cfg(feature = "bevy_rapier2d")] collision_entities: HashMap::default(), }; for (z_order, kind) in layers.iter().enumerate() { if let Some(kind) = kind { chunk.add_layer(kind, z_order, dimensions) } } chunk } /// Adds a layer from a layer kind, the z layer, and dimensions of the /// chunk. pub(crate) fn add_layer(&mut self, kind: &LayerKind, z_order: usize, dimensions: Dimension2) { match kind { LayerKind::Dense => { let tiles = vec![ RawTile { index: 0, color: Color::rgba(0.0, 0.0, 0.0, 0.0) }; dimensions.area() as usize ]; if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Dense(DenseLayer::new(tiles)), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } LayerKind::Sparse => { if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Sparse(SparseLayer::new(HashMap::default())), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } } } /// Returns the point of the location of the chunk. pub(crate) fn point(&self) -> Point2 { self.point } // /// Returns a copy of the user data. // pub(crate) fn user_data(&self) -> u128 { // self.user_data // } // // /// Returns a mutable reference to the user data. // pub(crate) fn user_data_mut(&mut self) -> &mut u128 { // &mut self.user_data // } /// Moves a layer from a z layer to another. pub(crate) fn move_layer(&mut self, from_z: usize, to_z: usize) { // TODO: rename to swap and include it in the greater api if self.sprite_layers.get(to_z).is_some() { error!( "sprite layer {} unexpectedly exists and can not be moved", to_z ); return; } self.sprite_layers.swap(from_z, to_z); } /// Removes a layer from the specified layer. pub(crate) fn remove_layer(&mut self, z_order: usize) { self.sprite_layers.get_mut(z_order).take(); } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().set_mesh(mesh) } else { error!("can not set mesh to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Sets a single raw tile to be added to a z layer and index. pub(crate) fn set_tile<P: Into<Point2>>(&mut self, index: usize, tile: Tile<P>) { if let Some(layer) = self.sprite_layers.get_mut(tile.z_order) { if let Some(layer) = layer.as_mut() { let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; layer.inner.as_mut().set_tile(index, raw_tile); } else { error!("can not set tile to sprite layer {}", tile.z_order); } } else { error!("sprite layer {} does not exist", tile.z_order); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, index: usize, z_order: usize) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().remove_tile(index); } else { error!("can not remove tile on sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a z layer, always when it is spawned. pub(crate) fn add_entity(&mut self, z_order: usize, entity: Entity) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.entity = Some(entity); } else { error!("can not add entity to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a tile index in a layer. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn insert_collision_entity( &mut self, index: usize, entity: Entity, ) -> Option<Entity> { self.collision_entities.insert(index, entity) } /// Gets the layers entity, if any. Useful for despawning. pub(crate) fn get_entity(&self, z_order: usize) -> Option<Entity> { self.sprite_layers .get(z_order) .and_then(|o| o.as_ref().and_then(|layer| layer.entity)) } /// Gets the collision entity if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_collision_entity(&self, index: usize) -> Option<Entity> { self.collision_entities.get(&index).cloned() } /// Remove all the layers and collision entities and return them for use with bulk despawning. pub(crate) fn remove_entities(&mut self) -> Vec<Entity> { let mut entities = Vec::new(); for sprite_layer in &mut self.sprite_layers { if let Some(layer) = sprite_layer { if let Some(entity) = layer.entity.take() { entities.push(entity); } } } #[cfg(feature = "bevy_rapier2d")] for (_, entity) in self.collision_entities.drain() { entities.push(entity) } entities } /// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_tile(index)) }) } /// Gets a mutable reference to a tile from a provided z order and index. pub(crate) fn
(&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> { self.sprite_layers.get_mut(z_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) } /// Gets a vec of all the tiles in the layer, if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_tile_indices(&self, z_order: usize) -> Option<Vec<usize>> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .map(|layer| layer.inner.as_ref().get_tile_indices()) }) } /// At the given z layer, changes the tiles into attributes for use with /// the renderer using the given dimensions. /// /// Easier to pass in the dimensions opposed to storing it everywhere. pub(crate) fn tiles_to_renderer_parts( &self, z: usize, dimensions: Dimension2, ) -> Option<(Vec<f32>, Vec<[f32; 4]>)> { let area = dimensions.area() as usize; self.sprite_layers.get(z).and_then(|o| { o.as_ref() .map(|layer| layer.inner.as_ref().tiles_to_attributes(area)) }) } }
get_tile_mut
identifier_name
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created does live in here. //! //! These below examples have nothing to do with this library as all should be //! done through the [`Tilemap`]. These are just more specific examples which //! use the private API of this library. //! //! [`Tilemap`]: crate::tilemap::Tilemap //! //! # Simple chunk creation //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! // There are two ways to create a new chunk. Either directly... //! //! tilemap.insert_chunk((0, 0)); //! //! // Or indirectly... //! //! let point = (0, 0); //! let sprite_index = 0; //! let tile = Tile { point, sprite_index,..Default::default() }; //! tilemap.insert_tile(tile); //! //! ``` //! //! # Specifying what kind of chunk //! ``` //! use bevy_asset::{prelude::*, HandleId}; //! use bevy_sprite::prelude::*; //! use bevy_tilemap::prelude::*; //! //! // This must be set in Asset<TextureAtlas>. //! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>()); //! //! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32); //! //! tilemap.insert_chunk((0, 0)); //! //! let z_order = 0; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! //! let z_order = 1; //! tilemap.add_layer(TilemapLayer { kind: LayerKind::Dense,..Default::default() }, 1); //! ``` /// Chunk entity. pub(crate) mod entity; /// Sparse and dense chunk layers. mod layer; /// Meshes for rendering to vertices. pub(crate) mod mesh; /// Raw tile that is stored in the chunks. pub mod raw_tile; /// Files and helpers for rendering. pub(crate) mod render; /// Systems for chunks. pub(crate) mod system; use crate::{lib::*, tile::Tile}; pub use layer::LayerKind; use layer::{DenseLayer, LayerKindInner, SparseLayer, SpriteLayer}; pub use raw_tile::RawTile; #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Clone, PartialEq, Debug)] #[doc(hidden)] pub(crate) struct Chunk { /// The point coordinate of the chunk. point: Point2, /// The sprite layers of the chunk. sprite_layers: Vec<Option<SpriteLayer>>, /// Ephemeral user data that can be used for flags or other purposes. user_data: u128, /// Contains a map of all collision entities. #[cfg(feature = "bevy_rapier2d")] pub collision_entities: HashMap<usize, Entity>, } impl Chunk { /// A newly constructed chunk from a point and the maximum number of layers. pub(crate) fn new( point: Point2, layers: &[Option<LayerKind>], dimensions: Dimension2, ) -> Chunk { let mut chunk = Chunk { point, sprite_layers: vec![None; layers.len()], user_data: 0, #[cfg(feature = "bevy_rapier2d")] collision_entities: HashMap::default(), }; for (z_order, kind) in layers.iter().enumerate() { if let Some(kind) = kind { chunk.add_layer(kind, z_order, dimensions) } } chunk } /// Adds a layer from a layer kind, the z layer, and dimensions of the /// chunk. pub(crate) fn add_layer(&mut self, kind: &LayerKind, z_order: usize, dimensions: Dimension2) { match kind { LayerKind::Dense => { let tiles = vec![ RawTile { index: 0, color: Color::rgba(0.0, 0.0, 0.0, 0.0) }; dimensions.area() as usize ]; if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Dense(DenseLayer::new(tiles)), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } LayerKind::Sparse => { if let Some(layer) = self.sprite_layers.get_mut(z_order) { *layer = Some(SpriteLayer { inner: LayerKindInner::Sparse(SparseLayer::new(HashMap::default())), entity: None, }); } else { error!("sprite layer {} is out of bounds", z_order); } } } } /// Returns the point of the location of the chunk. pub(crate) fn point(&self) -> Point2 { self.point } // /// Returns a copy of the user data. // pub(crate) fn user_data(&self) -> u128 { // self.user_data // } // // /// Returns a mutable reference to the user data. // pub(crate) fn user_data_mut(&mut self) -> &mut u128 { // &mut self.user_data // } /// Moves a layer from a z layer to another. pub(crate) fn move_layer(&mut self, from_z: usize, to_z: usize) { // TODO: rename to swap and include it in the greater api if self.sprite_layers.get(to_z).is_some() { error!( "sprite layer {} unexpectedly exists and can not be moved", to_z ); return; } self.sprite_layers.swap(from_z, to_z); } /// Removes a layer from the specified layer. pub(crate) fn remove_layer(&mut self, z_order: usize) { self.sprite_layers.get_mut(z_order).take(); } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().set_mesh(mesh) } else { error!("can not set mesh to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Sets a single raw tile to be added to a z layer and index. pub(crate) fn set_tile<P: Into<Point2>>(&mut self, index: usize, tile: Tile<P>) { if let Some(layer) = self.sprite_layers.get_mut(tile.z_order) { if let Some(layer) = layer.as_mut() { let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; layer.inner.as_mut().set_tile(index, raw_tile); } else { error!("can not set tile to sprite layer {}", tile.z_order); } } else { error!("sprite layer {} does not exist", tile.z_order); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, index: usize, z_order: usize) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.inner.as_mut().remove_tile(index); } else { error!("can not remove tile on sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a z layer, always when it is spawned. pub(crate) fn add_entity(&mut self, z_order: usize, entity: Entity) { if let Some(layer) = self.sprite_layers.get_mut(z_order) { if let Some(layer) = layer.as_mut() { layer.entity = Some(entity); } else { error!("can not add entity to sprite layer {}", z_order); } } else { error!("sprite layer {} does not exist", z_order); } } /// Adds an entity to a tile index in a layer. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn insert_collision_entity( &mut self, index: usize, entity: Entity, ) -> Option<Entity> { self.collision_entities.insert(index, entity) } /// Gets the layers entity, if any. Useful for despawning. pub(crate) fn get_entity(&self, z_order: usize) -> Option<Entity> { self.sprite_layers .get(z_order) .and_then(|o| o.as_ref().and_then(|layer| layer.entity)) } /// Gets the collision entity if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_collision_entity(&self, index: usize) -> Option<Entity> { self.collision_entities.get(&index).cloned() } /// Remove all the layers and collision entities and return them for use with bulk despawning. pub(crate) fn remove_entities(&mut self) -> Vec<Entity> { let mut entities = Vec::new(); for sprite_layer in &mut self.sprite_layers { if let Some(layer) = sprite_layer { if let Some(entity) = layer.entity.take() { entities.push(entity); } } } #[cfg(feature = "bevy_rapier2d")] for (_, entity) in self.collision_entities.drain() { entities.push(entity) } entities
/// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_tile(index)) }) } /// Gets a mutable reference to a tile from a provided z order and index. pub(crate) fn get_tile_mut(&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> { self.sprite_layers.get_mut(z_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) } /// Gets a vec of all the tiles in the layer, if any. #[cfg(feature = "bevy_rapier2d")] pub(crate) fn get_tile_indices(&self, z_order: usize) -> Option<Vec<usize>> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .map(|layer| layer.inner.as_ref().get_tile_indices()) }) } /// At the given z layer, changes the tiles into attributes for use with /// the renderer using the given dimensions. /// /// Easier to pass in the dimensions opposed to storing it everywhere. pub(crate) fn tiles_to_renderer_parts( &self, z: usize, dimensions: Dimension2, ) -> Option<(Vec<f32>, Vec<[f32; 4]>)> { let area = dimensions.area() as usize; self.sprite_layers.get(z).and_then(|o| { o.as_ref() .map(|layer| layer.inner.as_ref().tiles_to_attributes(area)) }) } }
}
random_line_split
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_stdio_container_t, }; callbacks! { pub ExitCB(handle: ProcessHandle, exit_status: i64, term_signal: i32); } /// Additional data stored on the handle #[derive(Default)] pub(crate) struct ProcessDataFields<'a> { exit_cb: ExitCB<'a>, } /// Callback for uv_process_options_t.exit_cb extern "C" fn uv_exit_cb( handle: *mut uv_process_t, exit_status: i64, term_signal: std::os::raw::c_int, ) { let dataptr = crate::Handle::get_data(uv_handle!(handle)); if!dataptr.is_null() { unsafe { if let super::ProcessData(d) = &mut (*dataptr).addl { d.exit_cb .call(handle.into_inner(), exit_status, term_signal as _); } } } } bitflags! { /// Flags specifying how a stdio should be transmitted to the child process. pub struct StdioFlags: u32 { /// No file descriptor will be provided (or redirected to `/dev/null` if it is fd 0, 1 or /// 2). const IGNORE = uv::uv_stdio_flags_UV_IGNORE as _; /// Open a new pipe into `data.stream`, per the flags below. The `data.stream` field must /// point to a PipeHandle object that has been initialized with `new`, but not yet opened /// or connected. const CREATE_PIPE = uv::uv_stdio_flags_UV_CREATE_PIPE as _; /// The child process will be given a duplicate of the parent's file descriptor given by /// `data.fd`. const INHERIT_FD = uv::uv_stdio_flags_UV_INHERIT_FD as _; /// The child process will be given a duplicate of the parent's file descriptor being used /// by the stream handle given by `data.stream`. const INHERIT_STREAM = uv::uv_stdio_flags_UV_INHERIT_STREAM as _; /// When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE determine the /// direction of flow, from the child process' perspective. Both flags may be specified to /// create a duplex data stream. const READABLE_PIPE = uv::uv_stdio_flags_UV_READABLE_PIPE as _; const WRITABLE_PIPE = uv::uv_stdio_flags_UV_WRITABLE_PIPE as _; /// Open the child pipe handle in overlapped mode on Windows. On Unix it is silently /// ignored. const OVERLAPPED_PIPE = uv::uv_stdio_flags_UV_OVERLAPPED_PIPE as _; } } impl Default for StdioFlags { fn default() -> Self { StdioFlags::IGNORE } } bitflags! { /// Flags to be set on the flags field of ProcessOptions. pub struct ProcessFlags: u32 { /// Set the child process' user id. const SETUID = uv::uv_process_flags_UV_PROCESS_SETUID as _; /// Set the child process' group id. const SETGID = uv::uv_process_flags_UV_PROCESS_SETGID as _; /// Do not wrap any arguments in quotes, or perform any other escaping, when converting the /// argument list into a command line string. This option is only meaningful on Windows /// systems. On Unix it is silently ignored. const WINDOWS_VERBATIM_ARGUMENTS = uv::uv_process_flags_UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS as _; /// Spawn the child process in a detached state - this will make it a process group leader, /// and will effectively enable the child to keep running after the parent exits. Note that /// the child process will still keep the parent's event loop alive unless the parent /// process calls uv_unref() on the child's process handle. const DETACHED = uv::uv_process_flags_UV_PROCESS_DETACHED as _; /// Hide the subprocess window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE as _; /// Hide the subprocess console window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_CONSOLE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_CONSOLE as _; /// Hide the subprocess GUI window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_GUI = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_GUI as _; } } pub enum StdioType { Stream(crate::StreamHandle), Fd(i32), } impl Default for StdioType { fn default() -> Self { StdioType::Fd(0) } } impl Inner<uv_stdio_container_data> for StdioType { fn inner(&self) -> uv_stdio_container_data { match self { StdioType::Stream(s) => uv_stdio_container_data { stream: s.inner() }, StdioType::Fd(fd) => uv_stdio_container_data { fd: *fd }, } } } /// Container for each stdio handle or fd passed to a child process. #[derive(Default)] pub struct StdioContainer { pub flags: StdioFlags, pub data: StdioType, } /// Options for spawning the process (passed to spawn()). pub struct ProcessOptions<'a> { /// Called after the process exits. pub exit_cb: ExitCB<'static>, /// Path to program to execute. pub file: &'a str, /// Command line arguments. args[0] should be the path to the program. On Windows this uses /// CreateProcess which concatenates the arguments into a string this can cause some strange /// errors. See the note at windows_verbatim_arguments. pub args: &'a [&'a str], /// This will be set as the environ variable in the subprocess. If this is None then the /// parents environ will be used. pub env: Option<&'a [&'a str]>, /// If Some() this represents a directory the subprocess should execute in. Stands for current /// working directory. pub cwd: Option<&'a str>, /// Various flags that control how spawn() behaves. See the definition of `ProcessFlags`. pub flags: ProcessFlags, /// The `stdio` field points to an array of StdioContainer structs that describe the file /// descriptors that will be made available to the child process. The convention is that /// stdio[0] points to stdin, fd 1 is used for stdout, and fd 2 is stderr. /// /// Note that on windows file descriptors greater than 2 are available to the child process /// only if the child processes uses the MSVCRT runtime. pub stdio: &'a [StdioContainer], /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub uid: crate::Uid, /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub gid: crate::Gid, } impl<'a> ProcessOptions<'a> { /// Constructs a new ProcessOptions object. The args slice must have at least one member: the /// path to the program to execute. Any additional members of the slice will be passed as /// command line arguments. pub fn new(args: &'a [&'a str]) -> ProcessOptions { assert!( args.len() > 0, "ProcessOptions args slice must contain at least one str" ); ProcessOptions { exit_cb: ().into(), file: args[0], args: args, env: None, cwd: None, flags: ProcessFlags::empty(), stdio: &[], uid: 0, gid: 0, } } } /// Process handles will spawn a new process and allow the user to control it and establish /// communication channels with it using streams. #[derive(Clone, Copy)] pub struct
{ handle: *mut uv_process_t, } impl ProcessHandle { /// Create a new process handle pub fn new() -> crate::Result<ProcessHandle> { let layout = std::alloc::Layout::new::<uv_process_t>(); let handle = unsafe { std::alloc::alloc(layout) as *mut uv_process_t }; if handle.is_null() { return Err(crate::Error::ENOMEM); } crate::Handle::initialize_data(uv_handle!(handle), super::ProcessData(Default::default())); Ok(ProcessHandle { handle }) } /// Disables inheritance for file descriptors / handles that this process inherited from its /// parent. The effect is that child processes spawned by this process don’t accidentally /// inherit these handles. /// /// It is recommended to call this function as early in your program as possible, before the /// inherited file descriptors can be closed or duplicated. /// /// Note: This function works on a best-effort basis: there is no guarantee that libuv can /// discover all file descriptors that were inherited. In general it does a better job on /// Windows than it does on Unix. pub fn disable_stdio_inheritance() { unsafe { uv_disable_stdio_inheritance() }; } /// Initializes the process handle and starts the process. /// /// Possible reasons for failing to spawn would include (but not be limited to) the file to /// execute not existing, not having permissions to use the setuid or setgid specified, or not /// having enough memory to allocate for the new process. pub fn spawn( &mut self, r#loop: &crate::Loop, options: ProcessOptions, ) -> Result<(), Box<dyn std::error::Error>> { let exit_cb_uv = use_c_callback!(uv_exit_cb, options.exit_cb); let dataptr = crate::Handle::get_data(uv_handle!(self.handle)); if!dataptr.is_null() { if let super::ProcessData(d) = unsafe { &mut (*dataptr).addl } { d.exit_cb = options.exit_cb; } } // CString will ensure we have a terminating null let file = CString::new(options.file)?; // For args, libuv-sys is expecting a "*mut *mut c_char". The only way to get a "*mut // c_char" from a CString is via CString::into_raw() which will "leak" the memory from // rust. We'll need to make sure to reclaim that memory later so it'll be GC'd. So, first // we need to convert all of the arguments to CStrings for the null-termination. Then we // need to grab a *mut pointer to the data using CString::into_raw() which will "leak" the // CStrings out of rust. Then we need to add a final null pointer to the end (the C code // requires it so it can find the end of the array) and collect it all into a Vec. let mut args = options .args .iter() .map(|a| CString::new(*a).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>()?; // env is similar to args except that it is Option'al. let mut env = options .env .map(|env| { env.iter() .map(|e| CString::new(*e).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>() }) .transpose()?; // cwd is like file except it's Option'al let cwd = options.cwd.map(|cwd| CString::new(cwd)).transpose()?; // stdio is an array of uv_stdio_container_t objects let mut stdio = options .stdio .iter() .map(|stdio| uv_stdio_container_t { flags: stdio.flags.bits() as _, data: stdio.data.inner(), }) .collect::<Vec<uv_stdio_container_t>>(); let options = uv_process_options_t { exit_cb: exit_cb_uv, file: file.as_ptr(), args: args.as_mut_ptr(), env: env .as_mut() .map_or(std::ptr::null_mut(), |e| e.as_mut_ptr()), cwd: cwd.map_or(std::ptr::null(), |s| s.as_ptr()), flags: options.flags.bits(), stdio_count: options.stdio.len() as _, stdio: stdio.as_mut_ptr(), uid: options.uid, gid: options.gid, }; let result = crate::uvret(unsafe { uv_spawn(r#loop.into_inner(), self.handle, &options as *const _) }) .map_err(|e| Box::new(e) as _); // reclaim data so it'll be freed - I'm pretty sure it's safe to free options here. Under // the hood, libuv is calling fork and execvp. The fork should copy the address space into // the new process, so freeing it here shouldn't affect that. Then execvp is going to // replace the address space, so we don't need to worry about leaking the copy. // For args, we don't need the last element because it's a null pointer. let args: Vec<CString> = args .iter() .take(args.len() - 1) .map(|a| unsafe { CString::from_raw(*a) }) .collect(); std::mem::drop(args); // env is the same as args except it's Option'al let env: Option<Vec<CString>> = env.map(|env| { env.iter() .take(env.len() - 1) .map(|e| unsafe { CString::from_raw(*e) }) .collect() }); std::mem::drop(env); result } /// The PID of the spawned process. It’s set after calling spawn(). pub fn pid(&self) -> i32 { unsafe { uv_process_get_pid(self.handle) as _ } } /// Sends the specified signal to the given process handle. Check the documentation on /// SignalHandle for signal support, specially on Windows. pub fn kill(&mut self, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_process_kill(self.handle, signum) }) } /// Sends the specified signal to the given PID. Check the documentation on SignalHandle for /// signal support, specially on Windows. pub fn kill_pid(pid: i32, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_kill(pid, signum) }) } } impl FromInner<*mut uv_process_t> for ProcessHandle { fn from_inner(handle: *mut uv_process_t) -> ProcessHandle { ProcessHandle { handle } } } impl Inner<*mut uv::uv_handle_t> for ProcessHandle { fn inner(&self) -> *mut uv::uv_handle_t { uv_handle!(self.handle) } } impl From<ProcessHandle> for crate::Handle { fn from(process: ProcessHandle) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(&process)) } } impl crate::ToHandle for ProcessHandle { fn to_handle(&self) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(self)) } } impl TryFrom<crate::Handle> for ProcessHandle { type Error = crate::ConversionError; fn try_from(handle: crate::Handle) -> Result<Self, Self::Error> { let t = handle.get_type(); if t!= crate::HandleType::PROCESS { Err(crate::ConversionError::new(t, crate::HandleType::PROCESS)) } else { Ok((handle.inner() as *mut uv_process_t).into_inner()) } } } impl HandleTrait for ProcessHandle {} impl crate::Loop { /// Create a new process handle and spawn the process pub fn spawn_process( &self, options: ProcessOptions, ) -> Result<ProcessHandle, Box<dyn std::error::Error>> { let mut process = ProcessHandle::new()?; process.spawn(self, options)?; Ok(process) } }
ProcessHandle
identifier_name
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_stdio_container_t, }; callbacks! { pub ExitCB(handle: ProcessHandle, exit_status: i64, term_signal: i32); } /// Additional data stored on the handle #[derive(Default)] pub(crate) struct ProcessDataFields<'a> { exit_cb: ExitCB<'a>, } /// Callback for uv_process_options_t.exit_cb extern "C" fn uv_exit_cb( handle: *mut uv_process_t, exit_status: i64, term_signal: std::os::raw::c_int, ) { let dataptr = crate::Handle::get_data(uv_handle!(handle)); if!dataptr.is_null() { unsafe { if let super::ProcessData(d) = &mut (*dataptr).addl { d.exit_cb .call(handle.into_inner(), exit_status, term_signal as _); } } } } bitflags! { /// Flags specifying how a stdio should be transmitted to the child process.
/// 2). const IGNORE = uv::uv_stdio_flags_UV_IGNORE as _; /// Open a new pipe into `data.stream`, per the flags below. The `data.stream` field must /// point to a PipeHandle object that has been initialized with `new`, but not yet opened /// or connected. const CREATE_PIPE = uv::uv_stdio_flags_UV_CREATE_PIPE as _; /// The child process will be given a duplicate of the parent's file descriptor given by /// `data.fd`. const INHERIT_FD = uv::uv_stdio_flags_UV_INHERIT_FD as _; /// The child process will be given a duplicate of the parent's file descriptor being used /// by the stream handle given by `data.stream`. const INHERIT_STREAM = uv::uv_stdio_flags_UV_INHERIT_STREAM as _; /// When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE determine the /// direction of flow, from the child process' perspective. Both flags may be specified to /// create a duplex data stream. const READABLE_PIPE = uv::uv_stdio_flags_UV_READABLE_PIPE as _; const WRITABLE_PIPE = uv::uv_stdio_flags_UV_WRITABLE_PIPE as _; /// Open the child pipe handle in overlapped mode on Windows. On Unix it is silently /// ignored. const OVERLAPPED_PIPE = uv::uv_stdio_flags_UV_OVERLAPPED_PIPE as _; } } impl Default for StdioFlags { fn default() -> Self { StdioFlags::IGNORE } } bitflags! { /// Flags to be set on the flags field of ProcessOptions. pub struct ProcessFlags: u32 { /// Set the child process' user id. const SETUID = uv::uv_process_flags_UV_PROCESS_SETUID as _; /// Set the child process' group id. const SETGID = uv::uv_process_flags_UV_PROCESS_SETGID as _; /// Do not wrap any arguments in quotes, or perform any other escaping, when converting the /// argument list into a command line string. This option is only meaningful on Windows /// systems. On Unix it is silently ignored. const WINDOWS_VERBATIM_ARGUMENTS = uv::uv_process_flags_UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS as _; /// Spawn the child process in a detached state - this will make it a process group leader, /// and will effectively enable the child to keep running after the parent exits. Note that /// the child process will still keep the parent's event loop alive unless the parent /// process calls uv_unref() on the child's process handle. const DETACHED = uv::uv_process_flags_UV_PROCESS_DETACHED as _; /// Hide the subprocess window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE as _; /// Hide the subprocess console window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_CONSOLE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_CONSOLE as _; /// Hide the subprocess GUI window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_GUI = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_GUI as _; } } pub enum StdioType { Stream(crate::StreamHandle), Fd(i32), } impl Default for StdioType { fn default() -> Self { StdioType::Fd(0) } } impl Inner<uv_stdio_container_data> for StdioType { fn inner(&self) -> uv_stdio_container_data { match self { StdioType::Stream(s) => uv_stdio_container_data { stream: s.inner() }, StdioType::Fd(fd) => uv_stdio_container_data { fd: *fd }, } } } /// Container for each stdio handle or fd passed to a child process. #[derive(Default)] pub struct StdioContainer { pub flags: StdioFlags, pub data: StdioType, } /// Options for spawning the process (passed to spawn()). pub struct ProcessOptions<'a> { /// Called after the process exits. pub exit_cb: ExitCB<'static>, /// Path to program to execute. pub file: &'a str, /// Command line arguments. args[0] should be the path to the program. On Windows this uses /// CreateProcess which concatenates the arguments into a string this can cause some strange /// errors. See the note at windows_verbatim_arguments. pub args: &'a [&'a str], /// This will be set as the environ variable in the subprocess. If this is None then the /// parents environ will be used. pub env: Option<&'a [&'a str]>, /// If Some() this represents a directory the subprocess should execute in. Stands for current /// working directory. pub cwd: Option<&'a str>, /// Various flags that control how spawn() behaves. See the definition of `ProcessFlags`. pub flags: ProcessFlags, /// The `stdio` field points to an array of StdioContainer structs that describe the file /// descriptors that will be made available to the child process. The convention is that /// stdio[0] points to stdin, fd 1 is used for stdout, and fd 2 is stderr. /// /// Note that on windows file descriptors greater than 2 are available to the child process /// only if the child processes uses the MSVCRT runtime. pub stdio: &'a [StdioContainer], /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub uid: crate::Uid, /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub gid: crate::Gid, } impl<'a> ProcessOptions<'a> { /// Constructs a new ProcessOptions object. The args slice must have at least one member: the /// path to the program to execute. Any additional members of the slice will be passed as /// command line arguments. pub fn new(args: &'a [&'a str]) -> ProcessOptions { assert!( args.len() > 0, "ProcessOptions args slice must contain at least one str" ); ProcessOptions { exit_cb: ().into(), file: args[0], args: args, env: None, cwd: None, flags: ProcessFlags::empty(), stdio: &[], uid: 0, gid: 0, } } } /// Process handles will spawn a new process and allow the user to control it and establish /// communication channels with it using streams. #[derive(Clone, Copy)] pub struct ProcessHandle { handle: *mut uv_process_t, } impl ProcessHandle { /// Create a new process handle pub fn new() -> crate::Result<ProcessHandle> { let layout = std::alloc::Layout::new::<uv_process_t>(); let handle = unsafe { std::alloc::alloc(layout) as *mut uv_process_t }; if handle.is_null() { return Err(crate::Error::ENOMEM); } crate::Handle::initialize_data(uv_handle!(handle), super::ProcessData(Default::default())); Ok(ProcessHandle { handle }) } /// Disables inheritance for file descriptors / handles that this process inherited from its /// parent. The effect is that child processes spawned by this process don’t accidentally /// inherit these handles. /// /// It is recommended to call this function as early in your program as possible, before the /// inherited file descriptors can be closed or duplicated. /// /// Note: This function works on a best-effort basis: there is no guarantee that libuv can /// discover all file descriptors that were inherited. In general it does a better job on /// Windows than it does on Unix. pub fn disable_stdio_inheritance() { unsafe { uv_disable_stdio_inheritance() }; } /// Initializes the process handle and starts the process. /// /// Possible reasons for failing to spawn would include (but not be limited to) the file to /// execute not existing, not having permissions to use the setuid or setgid specified, or not /// having enough memory to allocate for the new process. pub fn spawn( &mut self, r#loop: &crate::Loop, options: ProcessOptions, ) -> Result<(), Box<dyn std::error::Error>> { let exit_cb_uv = use_c_callback!(uv_exit_cb, options.exit_cb); let dataptr = crate::Handle::get_data(uv_handle!(self.handle)); if!dataptr.is_null() { if let super::ProcessData(d) = unsafe { &mut (*dataptr).addl } { d.exit_cb = options.exit_cb; } } // CString will ensure we have a terminating null let file = CString::new(options.file)?; // For args, libuv-sys is expecting a "*mut *mut c_char". The only way to get a "*mut // c_char" from a CString is via CString::into_raw() which will "leak" the memory from // rust. We'll need to make sure to reclaim that memory later so it'll be GC'd. So, first // we need to convert all of the arguments to CStrings for the null-termination. Then we // need to grab a *mut pointer to the data using CString::into_raw() which will "leak" the // CStrings out of rust. Then we need to add a final null pointer to the end (the C code // requires it so it can find the end of the array) and collect it all into a Vec. let mut args = options .args .iter() .map(|a| CString::new(*a).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>()?; // env is similar to args except that it is Option'al. let mut env = options .env .map(|env| { env.iter() .map(|e| CString::new(*e).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>() }) .transpose()?; // cwd is like file except it's Option'al let cwd = options.cwd.map(|cwd| CString::new(cwd)).transpose()?; // stdio is an array of uv_stdio_container_t objects let mut stdio = options .stdio .iter() .map(|stdio| uv_stdio_container_t { flags: stdio.flags.bits() as _, data: stdio.data.inner(), }) .collect::<Vec<uv_stdio_container_t>>(); let options = uv_process_options_t { exit_cb: exit_cb_uv, file: file.as_ptr(), args: args.as_mut_ptr(), env: env .as_mut() .map_or(std::ptr::null_mut(), |e| e.as_mut_ptr()), cwd: cwd.map_or(std::ptr::null(), |s| s.as_ptr()), flags: options.flags.bits(), stdio_count: options.stdio.len() as _, stdio: stdio.as_mut_ptr(), uid: options.uid, gid: options.gid, }; let result = crate::uvret(unsafe { uv_spawn(r#loop.into_inner(), self.handle, &options as *const _) }) .map_err(|e| Box::new(e) as _); // reclaim data so it'll be freed - I'm pretty sure it's safe to free options here. Under // the hood, libuv is calling fork and execvp. The fork should copy the address space into // the new process, so freeing it here shouldn't affect that. Then execvp is going to // replace the address space, so we don't need to worry about leaking the copy. // For args, we don't need the last element because it's a null pointer. let args: Vec<CString> = args .iter() .take(args.len() - 1) .map(|a| unsafe { CString::from_raw(*a) }) .collect(); std::mem::drop(args); // env is the same as args except it's Option'al let env: Option<Vec<CString>> = env.map(|env| { env.iter() .take(env.len() - 1) .map(|e| unsafe { CString::from_raw(*e) }) .collect() }); std::mem::drop(env); result } /// The PID of the spawned process. It’s set after calling spawn(). pub fn pid(&self) -> i32 { unsafe { uv_process_get_pid(self.handle) as _ } } /// Sends the specified signal to the given process handle. Check the documentation on /// SignalHandle for signal support, specially on Windows. pub fn kill(&mut self, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_process_kill(self.handle, signum) }) } /// Sends the specified signal to the given PID. Check the documentation on SignalHandle for /// signal support, specially on Windows. pub fn kill_pid(pid: i32, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_kill(pid, signum) }) } } impl FromInner<*mut uv_process_t> for ProcessHandle { fn from_inner(handle: *mut uv_process_t) -> ProcessHandle { ProcessHandle { handle } } } impl Inner<*mut uv::uv_handle_t> for ProcessHandle { fn inner(&self) -> *mut uv::uv_handle_t { uv_handle!(self.handle) } } impl From<ProcessHandle> for crate::Handle { fn from(process: ProcessHandle) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(&process)) } } impl crate::ToHandle for ProcessHandle { fn to_handle(&self) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(self)) } } impl TryFrom<crate::Handle> for ProcessHandle { type Error = crate::ConversionError; fn try_from(handle: crate::Handle) -> Result<Self, Self::Error> { let t = handle.get_type(); if t!= crate::HandleType::PROCESS { Err(crate::ConversionError::new(t, crate::HandleType::PROCESS)) } else { Ok((handle.inner() as *mut uv_process_t).into_inner()) } } } impl HandleTrait for ProcessHandle {} impl crate::Loop { /// Create a new process handle and spawn the process pub fn spawn_process( &self, options: ProcessOptions, ) -> Result<ProcessHandle, Box<dyn std::error::Error>> { let mut process = ProcessHandle::new()?; process.spawn(self, options)?; Ok(process) } }
pub struct StdioFlags: u32 { /// No file descriptor will be provided (or redirected to `/dev/null` if it is fd 0, 1 or
random_line_split
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_stdio_container_t, }; callbacks! { pub ExitCB(handle: ProcessHandle, exit_status: i64, term_signal: i32); } /// Additional data stored on the handle #[derive(Default)] pub(crate) struct ProcessDataFields<'a> { exit_cb: ExitCB<'a>, } /// Callback for uv_process_options_t.exit_cb extern "C" fn uv_exit_cb( handle: *mut uv_process_t, exit_status: i64, term_signal: std::os::raw::c_int, ) { let dataptr = crate::Handle::get_data(uv_handle!(handle)); if!dataptr.is_null() { unsafe { if let super::ProcessData(d) = &mut (*dataptr).addl { d.exit_cb .call(handle.into_inner(), exit_status, term_signal as _); } } } } bitflags! { /// Flags specifying how a stdio should be transmitted to the child process. pub struct StdioFlags: u32 { /// No file descriptor will be provided (or redirected to `/dev/null` if it is fd 0, 1 or /// 2). const IGNORE = uv::uv_stdio_flags_UV_IGNORE as _; /// Open a new pipe into `data.stream`, per the flags below. The `data.stream` field must /// point to a PipeHandle object that has been initialized with `new`, but not yet opened /// or connected. const CREATE_PIPE = uv::uv_stdio_flags_UV_CREATE_PIPE as _; /// The child process will be given a duplicate of the parent's file descriptor given by /// `data.fd`. const INHERIT_FD = uv::uv_stdio_flags_UV_INHERIT_FD as _; /// The child process will be given a duplicate of the parent's file descriptor being used /// by the stream handle given by `data.stream`. const INHERIT_STREAM = uv::uv_stdio_flags_UV_INHERIT_STREAM as _; /// When UV_CREATE_PIPE is specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE determine the /// direction of flow, from the child process' perspective. Both flags may be specified to /// create a duplex data stream. const READABLE_PIPE = uv::uv_stdio_flags_UV_READABLE_PIPE as _; const WRITABLE_PIPE = uv::uv_stdio_flags_UV_WRITABLE_PIPE as _; /// Open the child pipe handle in overlapped mode on Windows. On Unix it is silently /// ignored. const OVERLAPPED_PIPE = uv::uv_stdio_flags_UV_OVERLAPPED_PIPE as _; } } impl Default for StdioFlags { fn default() -> Self { StdioFlags::IGNORE } } bitflags! { /// Flags to be set on the flags field of ProcessOptions. pub struct ProcessFlags: u32 { /// Set the child process' user id. const SETUID = uv::uv_process_flags_UV_PROCESS_SETUID as _; /// Set the child process' group id. const SETGID = uv::uv_process_flags_UV_PROCESS_SETGID as _; /// Do not wrap any arguments in quotes, or perform any other escaping, when converting the /// argument list into a command line string. This option is only meaningful on Windows /// systems. On Unix it is silently ignored. const WINDOWS_VERBATIM_ARGUMENTS = uv::uv_process_flags_UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS as _; /// Spawn the child process in a detached state - this will make it a process group leader, /// and will effectively enable the child to keep running after the parent exits. Note that /// the child process will still keep the parent's event loop alive unless the parent /// process calls uv_unref() on the child's process handle. const DETACHED = uv::uv_process_flags_UV_PROCESS_DETACHED as _; /// Hide the subprocess window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE as _; /// Hide the subprocess console window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_CONSOLE = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_CONSOLE as _; /// Hide the subprocess GUI window that would normally be created. This option is only /// meaningful on Windows systems. On Unix it is silently ignored. const WINDOWS_HIDE_GUI = uv::uv_process_flags_UV_PROCESS_WINDOWS_HIDE_GUI as _; } } pub enum StdioType { Stream(crate::StreamHandle), Fd(i32), } impl Default for StdioType { fn default() -> Self { StdioType::Fd(0) } } impl Inner<uv_stdio_container_data> for StdioType { fn inner(&self) -> uv_stdio_container_data { match self { StdioType::Stream(s) => uv_stdio_container_data { stream: s.inner() }, StdioType::Fd(fd) => uv_stdio_container_data { fd: *fd }, } } } /// Container for each stdio handle or fd passed to a child process. #[derive(Default)] pub struct StdioContainer { pub flags: StdioFlags, pub data: StdioType, } /// Options for spawning the process (passed to spawn()). pub struct ProcessOptions<'a> { /// Called after the process exits. pub exit_cb: ExitCB<'static>, /// Path to program to execute. pub file: &'a str, /// Command line arguments. args[0] should be the path to the program. On Windows this uses /// CreateProcess which concatenates the arguments into a string this can cause some strange /// errors. See the note at windows_verbatim_arguments. pub args: &'a [&'a str], /// This will be set as the environ variable in the subprocess. If this is None then the /// parents environ will be used. pub env: Option<&'a [&'a str]>, /// If Some() this represents a directory the subprocess should execute in. Stands for current /// working directory. pub cwd: Option<&'a str>, /// Various flags that control how spawn() behaves. See the definition of `ProcessFlags`. pub flags: ProcessFlags, /// The `stdio` field points to an array of StdioContainer structs that describe the file /// descriptors that will be made available to the child process. The convention is that /// stdio[0] points to stdin, fd 1 is used for stdout, and fd 2 is stderr. /// /// Note that on windows file descriptors greater than 2 are available to the child process /// only if the child processes uses the MSVCRT runtime. pub stdio: &'a [StdioContainer], /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub uid: crate::Uid, /// Libuv can change the child process' user/group id. This happens only when the appropriate /// bits are set in the flags fields. This is not supported on windows; spawn() will fail and /// set the error to ENOTSUP. pub gid: crate::Gid, } impl<'a> ProcessOptions<'a> { /// Constructs a new ProcessOptions object. The args slice must have at least one member: the /// path to the program to execute. Any additional members of the slice will be passed as /// command line arguments. pub fn new(args: &'a [&'a str]) -> ProcessOptions { assert!( args.len() > 0, "ProcessOptions args slice must contain at least one str" ); ProcessOptions { exit_cb: ().into(), file: args[0], args: args, env: None, cwd: None, flags: ProcessFlags::empty(), stdio: &[], uid: 0, gid: 0, } } } /// Process handles will spawn a new process and allow the user to control it and establish /// communication channels with it using streams. #[derive(Clone, Copy)] pub struct ProcessHandle { handle: *mut uv_process_t, } impl ProcessHandle { /// Create a new process handle pub fn new() -> crate::Result<ProcessHandle> { let layout = std::alloc::Layout::new::<uv_process_t>(); let handle = unsafe { std::alloc::alloc(layout) as *mut uv_process_t }; if handle.is_null() { return Err(crate::Error::ENOMEM); } crate::Handle::initialize_data(uv_handle!(handle), super::ProcessData(Default::default())); Ok(ProcessHandle { handle }) } /// Disables inheritance for file descriptors / handles that this process inherited from its /// parent. The effect is that child processes spawned by this process don’t accidentally /// inherit these handles. /// /// It is recommended to call this function as early in your program as possible, before the /// inherited file descriptors can be closed or duplicated. /// /// Note: This function works on a best-effort basis: there is no guarantee that libuv can /// discover all file descriptors that were inherited. In general it does a better job on /// Windows than it does on Unix. pub fn disable_stdio_inheritance() { unsafe { uv_disable_stdio_inheritance() }; } /// Initializes the process handle and starts the process. /// /// Possible reasons for failing to spawn would include (but not be limited to) the file to /// execute not existing, not having permissions to use the setuid or setgid specified, or not /// having enough memory to allocate for the new process. pub fn spawn( &mut self, r#loop: &crate::Loop, options: ProcessOptions, ) -> Result<(), Box<dyn std::error::Error>> { let exit_cb_uv = use_c_callback!(uv_exit_cb, options.exit_cb); let dataptr = crate::Handle::get_data(uv_handle!(self.handle)); if!dataptr.is_null() { if let super::ProcessData(d) = unsafe { &mut (*dataptr).addl } {
} // CString will ensure we have a terminating null let file = CString::new(options.file)?; // For args, libuv-sys is expecting a "*mut *mut c_char". The only way to get a "*mut // c_char" from a CString is via CString::into_raw() which will "leak" the memory from // rust. We'll need to make sure to reclaim that memory later so it'll be GC'd. So, first // we need to convert all of the arguments to CStrings for the null-termination. Then we // need to grab a *mut pointer to the data using CString::into_raw() which will "leak" the // CStrings out of rust. Then we need to add a final null pointer to the end (the C code // requires it so it can find the end of the array) and collect it all into a Vec. let mut args = options .args .iter() .map(|a| CString::new(*a).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>()?; // env is similar to args except that it is Option'al. let mut env = options .env .map(|env| { env.iter() .map(|e| CString::new(*e).map(|s| s.into_raw())) .chain(std::iter::once(Ok(std::ptr::null_mut()))) .collect::<Result<Vec<*mut std::os::raw::c_char>, std::ffi::NulError>>() }) .transpose()?; // cwd is like file except it's Option'al let cwd = options.cwd.map(|cwd| CString::new(cwd)).transpose()?; // stdio is an array of uv_stdio_container_t objects let mut stdio = options .stdio .iter() .map(|stdio| uv_stdio_container_t { flags: stdio.flags.bits() as _, data: stdio.data.inner(), }) .collect::<Vec<uv_stdio_container_t>>(); let options = uv_process_options_t { exit_cb: exit_cb_uv, file: file.as_ptr(), args: args.as_mut_ptr(), env: env .as_mut() .map_or(std::ptr::null_mut(), |e| e.as_mut_ptr()), cwd: cwd.map_or(std::ptr::null(), |s| s.as_ptr()), flags: options.flags.bits(), stdio_count: options.stdio.len() as _, stdio: stdio.as_mut_ptr(), uid: options.uid, gid: options.gid, }; let result = crate::uvret(unsafe { uv_spawn(r#loop.into_inner(), self.handle, &options as *const _) }) .map_err(|e| Box::new(e) as _); // reclaim data so it'll be freed - I'm pretty sure it's safe to free options here. Under // the hood, libuv is calling fork and execvp. The fork should copy the address space into // the new process, so freeing it here shouldn't affect that. Then execvp is going to // replace the address space, so we don't need to worry about leaking the copy. // For args, we don't need the last element because it's a null pointer. let args: Vec<CString> = args .iter() .take(args.len() - 1) .map(|a| unsafe { CString::from_raw(*a) }) .collect(); std::mem::drop(args); // env is the same as args except it's Option'al let env: Option<Vec<CString>> = env.map(|env| { env.iter() .take(env.len() - 1) .map(|e| unsafe { CString::from_raw(*e) }) .collect() }); std::mem::drop(env); result } /// The PID of the spawned process. It’s set after calling spawn(). pub fn pid(&self) -> i32 { unsafe { uv_process_get_pid(self.handle) as _ } } /// Sends the specified signal to the given process handle. Check the documentation on /// SignalHandle for signal support, specially on Windows. pub fn kill(&mut self, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_process_kill(self.handle, signum) }) } /// Sends the specified signal to the given PID. Check the documentation on SignalHandle for /// signal support, specially on Windows. pub fn kill_pid(pid: i32, signum: i32) -> crate::Result<()> { crate::uvret(unsafe { uv_kill(pid, signum) }) } } impl FromInner<*mut uv_process_t> for ProcessHandle { fn from_inner(handle: *mut uv_process_t) -> ProcessHandle { ProcessHandle { handle } } } impl Inner<*mut uv::uv_handle_t> for ProcessHandle { fn inner(&self) -> *mut uv::uv_handle_t { uv_handle!(self.handle) } } impl From<ProcessHandle> for crate::Handle { fn from(process: ProcessHandle) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(&process)) } } impl crate::ToHandle for ProcessHandle { fn to_handle(&self) -> crate::Handle { crate::Handle::from_inner(Inner::<*mut uv::uv_handle_t>::inner(self)) } } impl TryFrom<crate::Handle> for ProcessHandle { type Error = crate::ConversionError; fn try_from(handle: crate::Handle) -> Result<Self, Self::Error> { let t = handle.get_type(); if t!= crate::HandleType::PROCESS { Err(crate::ConversionError::new(t, crate::HandleType::PROCESS)) } else { Ok((handle.inner() as *mut uv_process_t).into_inner()) } } } impl HandleTrait for ProcessHandle {} impl crate::Loop { /// Create a new process handle and spawn the process pub fn spawn_process( &self, options: ProcessOptions, ) -> Result<ProcessHandle, Box<dyn std::error::Error>> { let mut process = ProcessHandle::new()?; process.spawn(self, options)?; Ok(process) } }
d.exit_cb = options.exit_cb; }
conditional_block
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub const KEY_SIZE: usize = 16; const BLOCK_SIZE: usize = 16; // 128-bit blocks /// A buffer for encrypting blocks with some cipher. /// /// This object should consist of a 'plaintext' block buffer to be filled by the /// user with the unencrypted block and an indepedent 'ciphertext' block buffer /// that will continue the encrypted form of the 'plaintext' buffer upon /// request. pub trait BlockCipherBuffer { fn plaintext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE]; fn ciphertext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]); /// Should encrypt the plaintext buffer writing the result into the internal /// ciphertext buffer. /// /// MUST NOT modify the plaintext buffer. fn encrypt(&mut self); } pub struct
<Block, Nonce> { block: Block, tag_size: usize, length_size: usize, nonce: Nonce, } impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> { /// /// Arguments: /// - block: /// - tag_size: Number of bytes used to store the message authentication /// tag. /// - length_size: Number of bytes used to represent the message length. /// - nonce: pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self { let nonce_size = 15 - length_size; assert_eq!(nonce_size, nonce.as_ref().len()); Self { block, tag_size, length_size, nonce, } } /// Performs in-place encryption of the given message. /// /// Arguments: /// - message: A buffer of size plaintext_length + tag_size. The final /// tag_size bytes can be initially to any value. /// - additional_data: Additional data which will be considered while making /// the CBC-MAC. pub fn encrypt_inplace(&mut self, message: &mut [u8], additional_data: &[u8]) { assert!(message.len() >= self.tag_size); let (plaintext, tag) = message.split_at_mut(message.len() - self.tag_size); self.compute_cbc_mac(plaintext, additional_data, tag); self.apply_ctr_mode(plaintext, tag); } /// Performs in-place decryption of the given message. /// /// Arguments: /// - message: The buffer consisting of an encrypted plaintext + a tag. This /// is also the data generated by encrypt_inplace. /// /// Returns: If the MIC is valid, returns a pointer to the plaintext part of /// the buffer else returns an error. pub fn decrypt_inplace<'b>( &mut self, message: &'b mut [u8], additional_data: &[u8], ) -> Result<&'b [u8], ()> { if message.len() < self.tag_size { return Err(()); } let (ciphertext, tag) = message.split_at_mut(message.len() - self.tag_size); self.apply_ctr_mode(ciphertext, tag); // Buffer to store the computed tag (the tag can be at most BLOCK_SIZE bytes in // length). let mut expected_tag_buf = [0u8; BLOCK_SIZE]; let expected_tag = &mut expected_tag_buf[0..self.tag_size]; self.compute_cbc_mac(ciphertext, additional_data, expected_tag); // TODO: Use a constant time comparison function if expected_tag!= tag { return Err(()); } Ok(ciphertext) } fn compute_cbc_mac(&mut self, plaintext: &[u8], mut additional_data: &[u8], tag: &mut [u8]) { // Set up B_0 for CBC-MAC self.copy_nonce_to_block(); self.setup_for_cbc_mac(!additional_data.is_empty(), plaintext.len()); // Generate X_1 into self.block.ciphertext self.block.encrypt(); if!additional_data.is_empty() { // Construct B_i containing the length of the block. { let mut remaining = &mut self.block.plaintext_mut()[..]; if additional_data.len() < ((1 << 16) - (1 << 8)) { *array_mut_ref![remaining, 0, 2] = (additional_data.len() as u16).to_be_bytes(); remaining = &mut remaining[2..]; } else if additional_data.len() <= (core::u32::MAX as usize) { remaining[0] = 0xFF; remaining[1] = 0xFE; *array_mut_ref![remaining, 2, 4] = (additional_data.len() as u32).to_be_bytes(); remaining = &mut remaining[6..]; } else { remaining[0] = 0xFF; remaining[1] = 0xFF; *array_mut_ref![remaining, 2, 8] = (additional_data.len() as u64).to_be_bytes(); remaining = &mut remaining[10..]; } let n = core::cmp::min(remaining.len(), additional_data.len()); remaining[0..n].copy_from_slice(&additional_data[0..n]); additional_data = &additional_data[n..]; for i in n..remaining.len() { remaining[i] = 0; } } // Store 'X_i XOR B_i' into self.block.plaintext. { let (p, c) = self.block.plaintext_mut_ciphertext(); xor16_inplace(c, p); } // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); // Construct remaining additional data blocks. self.append_cbc_mac_data_blocks(additional_data); } self.append_cbc_mac_data_blocks(plaintext); // Get raw unencrypted tag by taking first tag_size bytes. tag.copy_from_slice(&self.block.ciphertext()[0..tag.len()]); } fn append_cbc_mac_data_blocks(&mut self, mut input: &[u8]) { while input.len() > 0 { let (plaintext, ciphertext) = self.block.plaintext_mut_ciphertext(); // Set the data.plaintext to B_i (the next input block padded with zeros). let n = core::cmp::min(input.len(), BLOCK_SIZE); plaintext[0..n].copy_from_slice(&input[0..n]); input = &input[n..]; for i in n..BLOCK_SIZE { plaintext[i] = 0; } // TODO: Deduplicate these two lines. // Perform 'X_i XOR B_i' xor16_inplace(ciphertext, plaintext); // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); } } /// Applies CTR encryption to the given plaintext and tag encrpyting them /// in-place. fn apply_ctr_mode(&mut self, plaintext: &mut [u8], tag: &mut [u8]) { // Setup A_0 self.copy_nonce_to_block(); self.setup_for_ctr_enc(0); // Generate S_0 self.block.encrypt(); // Encrypt tag as 'T XOR first-M-bytes( S_0 )' and write to the end of the // output buffer. xor_inplace(&self.block.ciphertext()[0..tag.len()], tag); for i in 0..ceil_div(plaintext.len(), BLOCK_SIZE) { let counter = i + 1; // Setup A_(i + 1) self.setup_for_ctr_enc(counter); // Generate S_(i + 1) self.block.encrypt(); let start_i = i * BLOCK_SIZE; let end_i = core::cmp::min(plaintext.len(), start_i + BLOCK_SIZE); xor_inplace( &self.block.ciphertext()[0..(end_i - start_i)], &mut plaintext[start_i..end_i], ); } } fn copy_nonce_to_block(&mut self) { self.block.plaintext_mut()[1..(1 + self.nonce.as_ref().len())] .copy_from_slice(&self.nonce.as_ref()[..]); } fn setup_for_cbc_mac(&mut self, has_additional_data: bool, length: usize) { let block = self.block.plaintext_mut(); block[0] = (if has_additional_data { 1 } else { 0 }) << 6 | ((self.tag_size as u8 - 2) / 2) << 3 | (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes(); } else { todo!(); } } fn setup_for_ctr_enc(&mut self, counter: usize) { let block = self.block.plaintext_mut(); block[0] = (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (counter as u16).to_be_bytes(); } else { todo!(); } } } fn xor16_inplace(a: &[u8; BLOCK_SIZE], b: &mut [u8; BLOCK_SIZE]) { for i in 0..(BLOCK_SIZE / 4) { let a_ref = array_ref![a, 4 * i, 4]; let b_ref = array_mut_ref![b, 4 * i, 4]; *b_ref = (u32::from_ne_bytes(*a_ref) ^ u32::from_ne_bytes(*b_ref)).to_ne_bytes(); } } #[cfg(feature = "std")] pub mod aes { use super::*; use crate::{aes::AESBlockCipher, cipher::BlockCipher}; pub struct AES128BlockEncryptor { cipher: AESBlockCipher, plaintext: [u8; BLOCK_SIZE], ciphertext: [u8; BLOCK_SIZE], } impl AES128BlockEncryptor { pub fn new(key: &[u8]) -> Self { assert_eq!(key.len(), KEY_SIZE); Self { cipher: AESBlockCipher::create(key).unwrap(), plaintext: [0u8; BLOCK_SIZE], ciphertext: [0u8; BLOCK_SIZE], } } } impl BlockCipherBuffer for AES128BlockEncryptor { fn plaintext(&self) -> &[u8; BLOCK_SIZE] { &self.plaintext } fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] { &mut self.plaintext } fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]) { (&mut self.plaintext, &self.ciphertext) } fn encrypt(&mut self) { self.cipher .encrypt_block(&self.plaintext, &mut self.ciphertext); } fn ciphertext(&self) -> &[u8; BLOCK_SIZE] { &self.ciphertext } } } #[cfg(test)] mod tests { use super::aes::*; use super::*; // Test vectors from the RFC #[test] fn works() { let key = hex!("C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"); let nonce = hex!("00000003020100A0A1A2A3A4A5"); let mut data = hex!("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E"); let tag_size = 8; let length_size = 2; let expected_ciphertext = hex!("588C979A61C663D2F066D0C2C0F989806D5F6B61DAC38417E8D12CFDF926E0"); let aad = &data[0..8]; let mut plaintext = data[8..].to_vec(); plaintext.resize(plaintext.len() + tag_size, 0); let mut ccm = CCM::new( AES128BlockEncryptor::new(&key), tag_size, length_size, array_ref![&nonce, 0, 13], ); ccm.encrypt_inplace(&mut plaintext, &aad); assert_eq!(&plaintext, &expected_ciphertext); println!("{:02x?}", &plaintext); } }
CCM
identifier_name
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub const KEY_SIZE: usize = 16; const BLOCK_SIZE: usize = 16; // 128-bit blocks /// A buffer for encrypting blocks with some cipher. /// /// This object should consist of a 'plaintext' block buffer to be filled by the /// user with the unencrypted block and an indepedent 'ciphertext' block buffer /// that will continue the encrypted form of the 'plaintext' buffer upon /// request. pub trait BlockCipherBuffer { fn plaintext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE]; fn ciphertext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]); /// Should encrypt the plaintext buffer writing the result into the internal /// ciphertext buffer. /// /// MUST NOT modify the plaintext buffer. fn encrypt(&mut self); } pub struct CCM<Block, Nonce> { block: Block, tag_size: usize, length_size: usize, nonce: Nonce, } impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> { /// /// Arguments: /// - block: /// - tag_size: Number of bytes used to store the message authentication /// tag. /// - length_size: Number of bytes used to represent the message length. /// - nonce: pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self { let nonce_size = 15 - length_size; assert_eq!(nonce_size, nonce.as_ref().len()); Self { block, tag_size, length_size, nonce, } } /// Performs in-place encryption of the given message. /// /// Arguments: /// - message: A buffer of size plaintext_length + tag_size. The final /// tag_size bytes can be initially to any value. /// - additional_data: Additional data which will be considered while making /// the CBC-MAC. pub fn encrypt_inplace(&mut self, message: &mut [u8], additional_data: &[u8]) { assert!(message.len() >= self.tag_size); let (plaintext, tag) = message.split_at_mut(message.len() - self.tag_size); self.compute_cbc_mac(plaintext, additional_data, tag); self.apply_ctr_mode(plaintext, tag); } /// Performs in-place decryption of the given message. /// /// Arguments: /// - message: The buffer consisting of an encrypted plaintext + a tag. This /// is also the data generated by encrypt_inplace. /// /// Returns: If the MIC is valid, returns a pointer to the plaintext part of /// the buffer else returns an error. pub fn decrypt_inplace<'b>( &mut self, message: &'b mut [u8], additional_data: &[u8], ) -> Result<&'b [u8], ()> { if message.len() < self.tag_size { return Err(()); } let (ciphertext, tag) = message.split_at_mut(message.len() - self.tag_size); self.apply_ctr_mode(ciphertext, tag); // Buffer to store the computed tag (the tag can be at most BLOCK_SIZE bytes in // length). let mut expected_tag_buf = [0u8; BLOCK_SIZE]; let expected_tag = &mut expected_tag_buf[0..self.tag_size]; self.compute_cbc_mac(ciphertext, additional_data, expected_tag); // TODO: Use a constant time comparison function if expected_tag!= tag { return Err(()); } Ok(ciphertext) } fn compute_cbc_mac(&mut self, plaintext: &[u8], mut additional_data: &[u8], tag: &mut [u8]) { // Set up B_0 for CBC-MAC self.copy_nonce_to_block(); self.setup_for_cbc_mac(!additional_data.is_empty(), plaintext.len()); // Generate X_1 into self.block.ciphertext self.block.encrypt(); if!additional_data.is_empty() { // Construct B_i containing the length of the block. { let mut remaining = &mut self.block.plaintext_mut()[..]; if additional_data.len() < ((1 << 16) - (1 << 8)) { *array_mut_ref![remaining, 0, 2] = (additional_data.len() as u16).to_be_bytes(); remaining = &mut remaining[2..]; } else if additional_data.len() <= (core::u32::MAX as usize) { remaining[0] = 0xFF; remaining[1] = 0xFE; *array_mut_ref![remaining, 2, 4] = (additional_data.len() as u32).to_be_bytes(); remaining = &mut remaining[6..]; } else { remaining[0] = 0xFF; remaining[1] = 0xFF; *array_mut_ref![remaining, 2, 8] = (additional_data.len() as u64).to_be_bytes(); remaining = &mut remaining[10..]; } let n = core::cmp::min(remaining.len(), additional_data.len()); remaining[0..n].copy_from_slice(&additional_data[0..n]); additional_data = &additional_data[n..]; for i in n..remaining.len() { remaining[i] = 0; } } // Store 'X_i XOR B_i' into self.block.plaintext. { let (p, c) = self.block.plaintext_mut_ciphertext(); xor16_inplace(c, p); } // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); // Construct remaining additional data blocks. self.append_cbc_mac_data_blocks(additional_data); } self.append_cbc_mac_data_blocks(plaintext); // Get raw unencrypted tag by taking first tag_size bytes. tag.copy_from_slice(&self.block.ciphertext()[0..tag.len()]); } fn append_cbc_mac_data_blocks(&mut self, mut input: &[u8]) { while input.len() > 0 { let (plaintext, ciphertext) = self.block.plaintext_mut_ciphertext(); // Set the data.plaintext to B_i (the next input block padded with zeros). let n = core::cmp::min(input.len(), BLOCK_SIZE); plaintext[0..n].copy_from_slice(&input[0..n]); input = &input[n..]; for i in n..BLOCK_SIZE { plaintext[i] = 0; } // TODO: Deduplicate these two lines. // Perform 'X_i XOR B_i' xor16_inplace(ciphertext, plaintext); // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); } } /// Applies CTR encryption to the given plaintext and tag encrpyting them /// in-place. fn apply_ctr_mode(&mut self, plaintext: &mut [u8], tag: &mut [u8]) { // Setup A_0 self.copy_nonce_to_block(); self.setup_for_ctr_enc(0); // Generate S_0 self.block.encrypt(); // Encrypt tag as 'T XOR first-M-bytes( S_0 )' and write to the end of the // output buffer. xor_inplace(&self.block.ciphertext()[0..tag.len()], tag); for i in 0..ceil_div(plaintext.len(), BLOCK_SIZE) { let counter = i + 1; // Setup A_(i + 1) self.setup_for_ctr_enc(counter); // Generate S_(i + 1) self.block.encrypt(); let start_i = i * BLOCK_SIZE; let end_i = core::cmp::min(plaintext.len(), start_i + BLOCK_SIZE); xor_inplace( &self.block.ciphertext()[0..(end_i - start_i)], &mut plaintext[start_i..end_i], ); } } fn copy_nonce_to_block(&mut self) { self.block.plaintext_mut()[1..(1 + self.nonce.as_ref().len())] .copy_from_slice(&self.nonce.as_ref()[..]); } fn setup_for_cbc_mac(&mut self, has_additional_data: bool, length: usize) { let block = self.block.plaintext_mut(); block[0] = (if has_additional_data
else { 0 }) << 6 | ((self.tag_size as u8 - 2) / 2) << 3 | (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes(); } else { todo!(); } } fn setup_for_ctr_enc(&mut self, counter: usize) { let block = self.block.plaintext_mut(); block[0] = (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (counter as u16).to_be_bytes(); } else { todo!(); } } } fn xor16_inplace(a: &[u8; BLOCK_SIZE], b: &mut [u8; BLOCK_SIZE]) { for i in 0..(BLOCK_SIZE / 4) { let a_ref = array_ref![a, 4 * i, 4]; let b_ref = array_mut_ref![b, 4 * i, 4]; *b_ref = (u32::from_ne_bytes(*a_ref) ^ u32::from_ne_bytes(*b_ref)).to_ne_bytes(); } } #[cfg(feature = "std")] pub mod aes { use super::*; use crate::{aes::AESBlockCipher, cipher::BlockCipher}; pub struct AES128BlockEncryptor { cipher: AESBlockCipher, plaintext: [u8; BLOCK_SIZE], ciphertext: [u8; BLOCK_SIZE], } impl AES128BlockEncryptor { pub fn new(key: &[u8]) -> Self { assert_eq!(key.len(), KEY_SIZE); Self { cipher: AESBlockCipher::create(key).unwrap(), plaintext: [0u8; BLOCK_SIZE], ciphertext: [0u8; BLOCK_SIZE], } } } impl BlockCipherBuffer for AES128BlockEncryptor { fn plaintext(&self) -> &[u8; BLOCK_SIZE] { &self.plaintext } fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] { &mut self.plaintext } fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]) { (&mut self.plaintext, &self.ciphertext) } fn encrypt(&mut self) { self.cipher .encrypt_block(&self.plaintext, &mut self.ciphertext); } fn ciphertext(&self) -> &[u8; BLOCK_SIZE] { &self.ciphertext } } } #[cfg(test)] mod tests { use super::aes::*; use super::*; // Test vectors from the RFC #[test] fn works() { let key = hex!("C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"); let nonce = hex!("00000003020100A0A1A2A3A4A5"); let mut data = hex!("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E"); let tag_size = 8; let length_size = 2; let expected_ciphertext = hex!("588C979A61C663D2F066D0C2C0F989806D5F6B61DAC38417E8D12CFDF926E0"); let aad = &data[0..8]; let mut plaintext = data[8..].to_vec(); plaintext.resize(plaintext.len() + tag_size, 0); let mut ccm = CCM::new( AES128BlockEncryptor::new(&key), tag_size, length_size, array_ref![&nonce, 0, 13], ); ccm.encrypt_inplace(&mut plaintext, &aad); assert_eq!(&plaintext, &expected_ciphertext); println!("{:02x?}", &plaintext); } }
{ 1 }
conditional_block
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub const KEY_SIZE: usize = 16; const BLOCK_SIZE: usize = 16; // 128-bit blocks /// A buffer for encrypting blocks with some cipher. /// /// This object should consist of a 'plaintext' block buffer to be filled by the /// user with the unencrypted block and an indepedent 'ciphertext' block buffer /// that will continue the encrypted form of the 'plaintext' buffer upon /// request. pub trait BlockCipherBuffer { fn plaintext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE]; fn ciphertext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]); /// Should encrypt the plaintext buffer writing the result into the internal /// ciphertext buffer. /// /// MUST NOT modify the plaintext buffer. fn encrypt(&mut self); } pub struct CCM<Block, Nonce> { block: Block, tag_size: usize, length_size: usize, nonce: Nonce, } impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> { /// /// Arguments: /// - block: /// - tag_size: Number of bytes used to store the message authentication /// tag. /// - length_size: Number of bytes used to represent the message length. /// - nonce: pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self { let nonce_size = 15 - length_size; assert_eq!(nonce_size, nonce.as_ref().len()); Self { block, tag_size, length_size, nonce, } } /// Performs in-place encryption of the given message. /// /// Arguments: /// - message: A buffer of size plaintext_length + tag_size. The final /// tag_size bytes can be initially to any value. /// - additional_data: Additional data which will be considered while making /// the CBC-MAC. pub fn encrypt_inplace(&mut self, message: &mut [u8], additional_data: &[u8]) { assert!(message.len() >= self.tag_size); let (plaintext, tag) = message.split_at_mut(message.len() - self.tag_size); self.compute_cbc_mac(plaintext, additional_data, tag); self.apply_ctr_mode(plaintext, tag); } /// Performs in-place decryption of the given message. /// /// Arguments: /// - message: The buffer consisting of an encrypted plaintext + a tag. This /// is also the data generated by encrypt_inplace. /// /// Returns: If the MIC is valid, returns a pointer to the plaintext part of /// the buffer else returns an error. pub fn decrypt_inplace<'b>( &mut self, message: &'b mut [u8], additional_data: &[u8], ) -> Result<&'b [u8], ()> { if message.len() < self.tag_size { return Err(()); } let (ciphertext, tag) = message.split_at_mut(message.len() - self.tag_size); self.apply_ctr_mode(ciphertext, tag); // Buffer to store the computed tag (the tag can be at most BLOCK_SIZE bytes in // length). let mut expected_tag_buf = [0u8; BLOCK_SIZE]; let expected_tag = &mut expected_tag_buf[0..self.tag_size]; self.compute_cbc_mac(ciphertext, additional_data, expected_tag); // TODO: Use a constant time comparison function if expected_tag!= tag { return Err(()); } Ok(ciphertext) } fn compute_cbc_mac(&mut self, plaintext: &[u8], mut additional_data: &[u8], tag: &mut [u8]) { // Set up B_0 for CBC-MAC self.copy_nonce_to_block(); self.setup_for_cbc_mac(!additional_data.is_empty(), plaintext.len()); // Generate X_1 into self.block.ciphertext self.block.encrypt(); if!additional_data.is_empty() { // Construct B_i containing the length of the block. { let mut remaining = &mut self.block.plaintext_mut()[..]; if additional_data.len() < ((1 << 16) - (1 << 8)) { *array_mut_ref![remaining, 0, 2] = (additional_data.len() as u16).to_be_bytes(); remaining = &mut remaining[2..]; } else if additional_data.len() <= (core::u32::MAX as usize) { remaining[0] = 0xFF; remaining[1] = 0xFE; *array_mut_ref![remaining, 2, 4] = (additional_data.len() as u32).to_be_bytes(); remaining = &mut remaining[6..]; } else { remaining[0] = 0xFF; remaining[1] = 0xFF; *array_mut_ref![remaining, 2, 8] = (additional_data.len() as u64).to_be_bytes(); remaining = &mut remaining[10..]; } let n = core::cmp::min(remaining.len(), additional_data.len()); remaining[0..n].copy_from_slice(&additional_data[0..n]); additional_data = &additional_data[n..]; for i in n..remaining.len() { remaining[i] = 0; } } // Store 'X_i XOR B_i' into self.block.plaintext. { let (p, c) = self.block.plaintext_mut_ciphertext(); xor16_inplace(c, p); } // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); // Construct remaining additional data blocks. self.append_cbc_mac_data_blocks(additional_data); } self.append_cbc_mac_data_blocks(plaintext); // Get raw unencrypted tag by taking first tag_size bytes. tag.copy_from_slice(&self.block.ciphertext()[0..tag.len()]); } fn append_cbc_mac_data_blocks(&mut self, mut input: &[u8]) { while input.len() > 0 { let (plaintext, ciphertext) = self.block.plaintext_mut_ciphertext(); // Set the data.plaintext to B_i (the next input block padded with zeros). let n = core::cmp::min(input.len(), BLOCK_SIZE); plaintext[0..n].copy_from_slice(&input[0..n]); input = &input[n..]; for i in n..BLOCK_SIZE { plaintext[i] = 0; } // TODO: Deduplicate these two lines. // Perform 'X_i XOR B_i' xor16_inplace(ciphertext, plaintext); // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); } } /// Applies CTR encryption to the given plaintext and tag encrpyting them /// in-place. fn apply_ctr_mode(&mut self, plaintext: &mut [u8], tag: &mut [u8]) { // Setup A_0 self.copy_nonce_to_block(); self.setup_for_ctr_enc(0); // Generate S_0 self.block.encrypt(); // Encrypt tag as 'T XOR first-M-bytes( S_0 )' and write to the end of the // output buffer. xor_inplace(&self.block.ciphertext()[0..tag.len()], tag); for i in 0..ceil_div(plaintext.len(), BLOCK_SIZE) { let counter = i + 1; // Setup A_(i + 1) self.setup_for_ctr_enc(counter); // Generate S_(i + 1) self.block.encrypt(); let start_i = i * BLOCK_SIZE; let end_i = core::cmp::min(plaintext.len(), start_i + BLOCK_SIZE); xor_inplace( &self.block.ciphertext()[0..(end_i - start_i)], &mut plaintext[start_i..end_i], ); } } fn copy_nonce_to_block(&mut self) { self.block.plaintext_mut()[1..(1 + self.nonce.as_ref().len())] .copy_from_slice(&self.nonce.as_ref()[..]); } fn setup_for_cbc_mac(&mut self, has_additional_data: bool, length: usize) { let block = self.block.plaintext_mut(); block[0] = (if has_additional_data { 1 } else { 0 }) << 6 | ((self.tag_size as u8 - 2) / 2) << 3 | (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes(); } else { todo!(); } } fn setup_for_ctr_enc(&mut self, counter: usize) { let block = self.block.plaintext_mut(); block[0] = (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (counter as u16).to_be_bytes(); } else { todo!(); } } } fn xor16_inplace(a: &[u8; BLOCK_SIZE], b: &mut [u8; BLOCK_SIZE]) { for i in 0..(BLOCK_SIZE / 4) { let a_ref = array_ref![a, 4 * i, 4]; let b_ref = array_mut_ref![b, 4 * i, 4]; *b_ref = (u32::from_ne_bytes(*a_ref) ^ u32::from_ne_bytes(*b_ref)).to_ne_bytes(); } } #[cfg(feature = "std")] pub mod aes { use super::*; use crate::{aes::AESBlockCipher, cipher::BlockCipher}; pub struct AES128BlockEncryptor { cipher: AESBlockCipher, plaintext: [u8; BLOCK_SIZE], ciphertext: [u8; BLOCK_SIZE], } impl AES128BlockEncryptor { pub fn new(key: &[u8]) -> Self
} impl BlockCipherBuffer for AES128BlockEncryptor { fn plaintext(&self) -> &[u8; BLOCK_SIZE] { &self.plaintext } fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] { &mut self.plaintext } fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]) { (&mut self.plaintext, &self.ciphertext) } fn encrypt(&mut self) { self.cipher .encrypt_block(&self.plaintext, &mut self.ciphertext); } fn ciphertext(&self) -> &[u8; BLOCK_SIZE] { &self.ciphertext } } } #[cfg(test)] mod tests { use super::aes::*; use super::*; // Test vectors from the RFC #[test] fn works() { let key = hex!("C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"); let nonce = hex!("00000003020100A0A1A2A3A4A5"); let mut data = hex!("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E"); let tag_size = 8; let length_size = 2; let expected_ciphertext = hex!("588C979A61C663D2F066D0C2C0F989806D5F6B61DAC38417E8D12CFDF926E0"); let aad = &data[0..8]; let mut plaintext = data[8..].to_vec(); plaintext.resize(plaintext.len() + tag_size, 0); let mut ccm = CCM::new( AES128BlockEncryptor::new(&key), tag_size, length_size, array_ref![&nonce, 0, 13], ); ccm.encrypt_inplace(&mut plaintext, &aad); assert_eq!(&plaintext, &expected_ciphertext); println!("{:02x?}", &plaintext); } }
{ assert_eq!(key.len(), KEY_SIZE); Self { cipher: AESBlockCipher::create(key).unwrap(), plaintext: [0u8; BLOCK_SIZE], ciphertext: [0u8; BLOCK_SIZE], } }
identifier_body
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub const KEY_SIZE: usize = 16; const BLOCK_SIZE: usize = 16; // 128-bit blocks /// A buffer for encrypting blocks with some cipher. /// /// This object should consist of a 'plaintext' block buffer to be filled by the /// user with the unencrypted block and an indepedent 'ciphertext' block buffer /// that will continue the encrypted form of the 'plaintext' buffer upon /// request. pub trait BlockCipherBuffer { fn plaintext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE]; fn ciphertext(&self) -> &[u8; BLOCK_SIZE]; fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]); /// Should encrypt the plaintext buffer writing the result into the internal /// ciphertext buffer. /// /// MUST NOT modify the plaintext buffer. fn encrypt(&mut self); } pub struct CCM<Block, Nonce> { block: Block, tag_size: usize, length_size: usize, nonce: Nonce, } impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> { ///
/// - tag_size: Number of bytes used to store the message authentication /// tag. /// - length_size: Number of bytes used to represent the message length. /// - nonce: pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self { let nonce_size = 15 - length_size; assert_eq!(nonce_size, nonce.as_ref().len()); Self { block, tag_size, length_size, nonce, } } /// Performs in-place encryption of the given message. /// /// Arguments: /// - message: A buffer of size plaintext_length + tag_size. The final /// tag_size bytes can be initially to any value. /// - additional_data: Additional data which will be considered while making /// the CBC-MAC. pub fn encrypt_inplace(&mut self, message: &mut [u8], additional_data: &[u8]) { assert!(message.len() >= self.tag_size); let (plaintext, tag) = message.split_at_mut(message.len() - self.tag_size); self.compute_cbc_mac(plaintext, additional_data, tag); self.apply_ctr_mode(plaintext, tag); } /// Performs in-place decryption of the given message. /// /// Arguments: /// - message: The buffer consisting of an encrypted plaintext + a tag. This /// is also the data generated by encrypt_inplace. /// /// Returns: If the MIC is valid, returns a pointer to the plaintext part of /// the buffer else returns an error. pub fn decrypt_inplace<'b>( &mut self, message: &'b mut [u8], additional_data: &[u8], ) -> Result<&'b [u8], ()> { if message.len() < self.tag_size { return Err(()); } let (ciphertext, tag) = message.split_at_mut(message.len() - self.tag_size); self.apply_ctr_mode(ciphertext, tag); // Buffer to store the computed tag (the tag can be at most BLOCK_SIZE bytes in // length). let mut expected_tag_buf = [0u8; BLOCK_SIZE]; let expected_tag = &mut expected_tag_buf[0..self.tag_size]; self.compute_cbc_mac(ciphertext, additional_data, expected_tag); // TODO: Use a constant time comparison function if expected_tag!= tag { return Err(()); } Ok(ciphertext) } fn compute_cbc_mac(&mut self, plaintext: &[u8], mut additional_data: &[u8], tag: &mut [u8]) { // Set up B_0 for CBC-MAC self.copy_nonce_to_block(); self.setup_for_cbc_mac(!additional_data.is_empty(), plaintext.len()); // Generate X_1 into self.block.ciphertext self.block.encrypt(); if!additional_data.is_empty() { // Construct B_i containing the length of the block. { let mut remaining = &mut self.block.plaintext_mut()[..]; if additional_data.len() < ((1 << 16) - (1 << 8)) { *array_mut_ref![remaining, 0, 2] = (additional_data.len() as u16).to_be_bytes(); remaining = &mut remaining[2..]; } else if additional_data.len() <= (core::u32::MAX as usize) { remaining[0] = 0xFF; remaining[1] = 0xFE; *array_mut_ref![remaining, 2, 4] = (additional_data.len() as u32).to_be_bytes(); remaining = &mut remaining[6..]; } else { remaining[0] = 0xFF; remaining[1] = 0xFF; *array_mut_ref![remaining, 2, 8] = (additional_data.len() as u64).to_be_bytes(); remaining = &mut remaining[10..]; } let n = core::cmp::min(remaining.len(), additional_data.len()); remaining[0..n].copy_from_slice(&additional_data[0..n]); additional_data = &additional_data[n..]; for i in n..remaining.len() { remaining[i] = 0; } } // Store 'X_i XOR B_i' into self.block.plaintext. { let (p, c) = self.block.plaintext_mut_ciphertext(); xor16_inplace(c, p); } // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); // Construct remaining additional data blocks. self.append_cbc_mac_data_blocks(additional_data); } self.append_cbc_mac_data_blocks(plaintext); // Get raw unencrypted tag by taking first tag_size bytes. tag.copy_from_slice(&self.block.ciphertext()[0..tag.len()]); } fn append_cbc_mac_data_blocks(&mut self, mut input: &[u8]) { while input.len() > 0 { let (plaintext, ciphertext) = self.block.plaintext_mut_ciphertext(); // Set the data.plaintext to B_i (the next input block padded with zeros). let n = core::cmp::min(input.len(), BLOCK_SIZE); plaintext[0..n].copy_from_slice(&input[0..n]); input = &input[n..]; for i in n..BLOCK_SIZE { plaintext[i] = 0; } // TODO: Deduplicate these two lines. // Perform 'X_i XOR B_i' xor16_inplace(ciphertext, plaintext); // Encrypt 'X_i XOR B_i' to get X_i+1 self.block.encrypt(); } } /// Applies CTR encryption to the given plaintext and tag encrpyting them /// in-place. fn apply_ctr_mode(&mut self, plaintext: &mut [u8], tag: &mut [u8]) { // Setup A_0 self.copy_nonce_to_block(); self.setup_for_ctr_enc(0); // Generate S_0 self.block.encrypt(); // Encrypt tag as 'T XOR first-M-bytes( S_0 )' and write to the end of the // output buffer. xor_inplace(&self.block.ciphertext()[0..tag.len()], tag); for i in 0..ceil_div(plaintext.len(), BLOCK_SIZE) { let counter = i + 1; // Setup A_(i + 1) self.setup_for_ctr_enc(counter); // Generate S_(i + 1) self.block.encrypt(); let start_i = i * BLOCK_SIZE; let end_i = core::cmp::min(plaintext.len(), start_i + BLOCK_SIZE); xor_inplace( &self.block.ciphertext()[0..(end_i - start_i)], &mut plaintext[start_i..end_i], ); } } fn copy_nonce_to_block(&mut self) { self.block.plaintext_mut()[1..(1 + self.nonce.as_ref().len())] .copy_from_slice(&self.nonce.as_ref()[..]); } fn setup_for_cbc_mac(&mut self, has_additional_data: bool, length: usize) { let block = self.block.plaintext_mut(); block[0] = (if has_additional_data { 1 } else { 0 }) << 6 | ((self.tag_size as u8 - 2) / 2) << 3 | (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes(); } else { todo!(); } } fn setup_for_ctr_enc(&mut self, counter: usize) { let block = self.block.plaintext_mut(); block[0] = (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (counter as u16).to_be_bytes(); } else { todo!(); } } } fn xor16_inplace(a: &[u8; BLOCK_SIZE], b: &mut [u8; BLOCK_SIZE]) { for i in 0..(BLOCK_SIZE / 4) { let a_ref = array_ref![a, 4 * i, 4]; let b_ref = array_mut_ref![b, 4 * i, 4]; *b_ref = (u32::from_ne_bytes(*a_ref) ^ u32::from_ne_bytes(*b_ref)).to_ne_bytes(); } } #[cfg(feature = "std")] pub mod aes { use super::*; use crate::{aes::AESBlockCipher, cipher::BlockCipher}; pub struct AES128BlockEncryptor { cipher: AESBlockCipher, plaintext: [u8; BLOCK_SIZE], ciphertext: [u8; BLOCK_SIZE], } impl AES128BlockEncryptor { pub fn new(key: &[u8]) -> Self { assert_eq!(key.len(), KEY_SIZE); Self { cipher: AESBlockCipher::create(key).unwrap(), plaintext: [0u8; BLOCK_SIZE], ciphertext: [0u8; BLOCK_SIZE], } } } impl BlockCipherBuffer for AES128BlockEncryptor { fn plaintext(&self) -> &[u8; BLOCK_SIZE] { &self.plaintext } fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] { &mut self.plaintext } fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; BLOCK_SIZE], &[u8; BLOCK_SIZE]) { (&mut self.plaintext, &self.ciphertext) } fn encrypt(&mut self) { self.cipher .encrypt_block(&self.plaintext, &mut self.ciphertext); } fn ciphertext(&self) -> &[u8; BLOCK_SIZE] { &self.ciphertext } } } #[cfg(test)] mod tests { use super::aes::*; use super::*; // Test vectors from the RFC #[test] fn works() { let key = hex!("C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF"); let nonce = hex!("00000003020100A0A1A2A3A4A5"); let mut data = hex!("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E"); let tag_size = 8; let length_size = 2; let expected_ciphertext = hex!("588C979A61C663D2F066D0C2C0F989806D5F6B61DAC38417E8D12CFDF926E0"); let aad = &data[0..8]; let mut plaintext = data[8..].to_vec(); plaintext.resize(plaintext.len() + tag_size, 0); let mut ccm = CCM::new( AES128BlockEncryptor::new(&key), tag_size, length_size, array_ref![&nonce, 0, 13], ); ccm.encrypt_inplace(&mut plaintext, &aad); assert_eq!(&plaintext, &expected_ciphertext); println!("{:02x?}", &plaintext); } }
/// Arguments: /// - block:
random_line_split
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use bytes::BytesMut; use crate::structs_proto; use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream}; use futures::try_ready; use libp2p_core::{ Multiaddr, PublicKey, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, Negotiated} }; use log::{debug, trace}; use protobuf::Message as ProtobufMessage; use protobuf::parse_from_bytes as protobuf_parse_from_bytes; use protobuf::RepeatedField; use std::convert::TryFrom; use std::io::{Error as IoError, ErrorKind as IoErrorKind}; use std::iter; use tokio_codec::Framed; use tokio_io::{AsyncRead, AsyncWrite}; use unsigned_varint::codec; /// Configuration for an upgrade to the identity protocol. #[derive(Debug, Clone)] pub struct IdentifyProtocolConfig; #[derive(Debug, Clone)] pub struct RemoteInfo { /// Information about the remote. pub info: IdentifyInfo, /// Address the remote sees for us. pub observed_addr: Multiaddr, _priv: () } /// Object used to send back information to the client. pub struct IdentifySender<T> { inner: Framed<T, codec::UviBytes<Vec<u8>>>, } impl<T> IdentifySender<T> where T: AsyncWrite { /// Sends back information to the client. Returns a future that is signalled whenever the /// info have been sent. pub fn send(self, info: IdentifyInfo, observed_addr: &Multiaddr) -> IdentifySenderFuture<T> { debug!("Sending identify info to client"); trace!("Sending: {:?}", info); let listen_addrs = info.listen_addrs .into_iter() .map(|addr| addr.to_vec()) .collect(); let pubkey_bytes = info.public_key.into_protobuf_encoding(); let mut message = structs_proto::Identify::new(); message.set_agentVersion(info.agent_version); message.set_protocolVersion(info.protocol_version); message.set_publicKey(pubkey_bytes); message.set_listenAddrs(listen_addrs); message.set_observedAddr(observed_addr.to_vec()); message.set_protocols(RepeatedField::from_vec(info.protocols)); let bytes = message .write_to_bytes() .expect("writing protobuf failed; should never happen"); IdentifySenderFuture { inner: self.inner, item: Some(bytes), } } } /// Future returned by `IdentifySender::send()`. Must be processed to the end in order to send /// the information to the remote. // Note: we don't use a `futures::sink::Sink` because it requires `T` to implement `Sink`, which // means that we would require `T: AsyncWrite` in this struct definition. This requirement // would then propagate everywhere. #[must_use = "futures do nothing unless polled"] pub struct IdentifySenderFuture<T> { /// The Sink where to send the data. inner: Framed<T, codec::UviBytes<Vec<u8>>>, /// Bytes to send, or `None` if we've already sent them. item: Option<Vec<u8>>, } impl<T> Future for IdentifySenderFuture<T> where T: AsyncWrite { type Item = (); type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if let Some(item) = self.item.take() { if let AsyncSink::NotReady(item) = self.inner.start_send(item)? { self.item = Some(item); return Ok(Async::NotReady); } } // A call to `close()` implies flushing. try_ready!(self.inner.close()); Ok(Async::Ready(())) } } /// Information sent from the listener to the dialer. #[derive(Debug, Clone)] pub struct IdentifyInfo { /// Public key of the node. pub public_key: PublicKey, /// Version of the "global" protocol, e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. pub protocol_version: String, /// Name and version of the client. Can be thought as similar to the `User-Agent` header /// of HTTP. pub agent_version: String, /// Addresses that the node is listening on. pub listen_addrs: Vec<Multiaddr>, /// Protocols supported by the node, e.g. `/ipfs/ping/1.0.0`. pub protocols: Vec<String>, } impl UpgradeInfo for IdentifyProtocolConfig { type Info = &'static [u8]; type InfoIter = iter::Once<Self::Info>; fn
(&self) -> Self::InfoIter { iter::once(b"/ipfs/id/1.0.0") } } impl<C> InboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = IdentifySender<Negotiated<C>>; type Error = IoError; type Future = FutureResult<Self::Output, IoError>; fn upgrade_inbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { trace!("Upgrading inbound connection"); let socket = Framed::new(socket, codec::UviBytes::default()); let sender = IdentifySender { inner: socket }; future::ok(sender) } } impl<C> OutboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = RemoteInfo; type Error = IoError; type Future = IdentifyOutboundFuture<Negotiated<C>>; fn upgrade_outbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { IdentifyOutboundFuture { inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()), shutdown: false, } } } /// Future returned by `OutboundUpgrade::upgrade_outbound`. pub struct IdentifyOutboundFuture<T> { inner: Framed<T, codec::UviBytes<BytesMut>>, /// If true, we have finished shutting down the writing part of `inner`. shutdown: bool, } impl<T> Future for IdentifyOutboundFuture<T> where T: AsyncRead + AsyncWrite, { type Item = RemoteInfo; type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if!self.shutdown { try_ready!(self.inner.close()); self.shutdown = true; } let msg = match try_ready!(self.inner.poll()) { Some(i) => i, None => { debug!("Identify protocol stream closed before receiving info"); return Err(IoErrorKind::InvalidData.into()); } }; debug!("Received identify message"); let (info, observed_addr) = match parse_proto_msg(msg) { Ok(v) => v, Err(err) => { debug!("Failed to parse protobuf message; error = {:?}", err); return Err(err) } }; trace!("Remote observes us as {:?}", observed_addr); trace!("Information received: {:?}", info); Ok(Async::Ready(RemoteInfo { info, observed_addr: observed_addr.clone(), _priv: () })) } } // Turns a protobuf message into an `IdentifyInfo` and an observed address. If something bad // happens, turn it into an `IoError`. fn parse_proto_msg(msg: BytesMut) -> Result<(IdentifyInfo, Multiaddr), IoError> { match protobuf_parse_from_bytes::<structs_proto::Identify>(&msg) { Ok(mut msg) => { // Turn a `Vec<u8>` into a `Multiaddr`. If something bad happens, turn it into // an `IoError`. fn bytes_to_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, IoError> { Multiaddr::try_from(bytes) .map_err(|err| IoError::new(IoErrorKind::InvalidData, err)) } let listen_addrs = { let mut addrs = Vec::new(); for addr in msg.take_listenAddrs().into_iter() { addrs.push(bytes_to_multiaddr(addr)?); } addrs }; let public_key = PublicKey::from_protobuf_encoding(msg.get_publicKey()) .map_err(|e| IoError::new(IoErrorKind::InvalidData, e))?; let observed_addr = bytes_to_multiaddr(msg.take_observedAddr())?; let info = IdentifyInfo { public_key, protocol_version: msg.take_protocolVersion(), agent_version: msg.take_agentVersion(), listen_addrs, protocols: msg.take_protocols().into_vec(), }; Ok((info, observed_addr)) } Err(err) => Err(IoError::new(IoErrorKind::InvalidData, err)), } } #[cfg(test)] mod tests { use crate::protocol::{IdentifyInfo, RemoteInfo, IdentifyProtocolConfig}; use tokio::runtime::current_thread::Runtime; use libp2p_tcp::TcpConfig; use futures::{Future, Stream}; use libp2p_core::{ identity, Transport, transport::ListenerEvent, upgrade::{apply_outbound, apply_inbound} }; use std::{io, sync::mpsc, thread}; #[test] fn correct_transfer() { // We open a server and a client, send info from the server to the client, and check that // they were successfully received. let send_pubkey = identity::Keypair::generate_ed25519().public(); let recv_pubkey = send_pubkey.clone(); let (tx, rx) = mpsc::channel(); let bg_thread = thread::spawn(move || { let transport = TcpConfig::new(); let mut listener = transport .listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()) .unwrap(); let addr = listener.by_ref().wait() .next() .expect("some event") .expect("no error") .into_new_address() .expect("listen address"); tx.send(addr).unwrap(); let future = listener .filter_map(ListenerEvent::into_upgrade) .into_future() .map_err(|(err, _)| err) .and_then(|(client, _)| client.unwrap().0) .and_then(|socket| { apply_inbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|sender| { sender.send( IdentifyInfo { public_key: send_pubkey, protocol_version: "proto_version".to_owned(), agent_version: "agent_version".to_owned(), listen_addrs: vec![ "/ip4/80.81.82.83/tcp/500".parse().unwrap(), "/ip6/::1/udp/1000".parse().unwrap(), ], protocols: vec!["proto1".to_string(), "proto2".to_string()], }, &"/ip4/100.101.102.103/tcp/5000".parse().unwrap(), ) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); }); let transport = TcpConfig::new(); let future = transport.dial(rx.recv().unwrap()) .unwrap() .and_then(|socket| { apply_outbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|RemoteInfo { info, observed_addr,.. }| { assert_eq!(observed_addr, "/ip4/100.101.102.103/tcp/5000".parse().unwrap()); assert_eq!(info.public_key, recv_pubkey); assert_eq!(info.protocol_version, "proto_version"); assert_eq!(info.agent_version, "agent_version"); assert_eq!(info.listen_addrs, &["/ip4/80.81.82.83/tcp/500".parse().unwrap(), "/ip6/::1/udp/1000".parse().unwrap()]); assert_eq!(info.protocols, &["proto1".to_string(), "proto2".to_string()]); Ok(()) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); bg_thread.join().unwrap(); } }
protocol_info
identifier_name
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use bytes::BytesMut; use crate::structs_proto; use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream}; use futures::try_ready; use libp2p_core::{ Multiaddr, PublicKey, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, Negotiated} }; use log::{debug, trace}; use protobuf::Message as ProtobufMessage; use protobuf::parse_from_bytes as protobuf_parse_from_bytes; use protobuf::RepeatedField; use std::convert::TryFrom; use std::io::{Error as IoError, ErrorKind as IoErrorKind}; use std::iter; use tokio_codec::Framed; use tokio_io::{AsyncRead, AsyncWrite}; use unsigned_varint::codec; /// Configuration for an upgrade to the identity protocol. #[derive(Debug, Clone)] pub struct IdentifyProtocolConfig; #[derive(Debug, Clone)] pub struct RemoteInfo { /// Information about the remote. pub info: IdentifyInfo, /// Address the remote sees for us. pub observed_addr: Multiaddr, _priv: () } /// Object used to send back information to the client. pub struct IdentifySender<T> { inner: Framed<T, codec::UviBytes<Vec<u8>>>, } impl<T> IdentifySender<T> where T: AsyncWrite { /// Sends back information to the client. Returns a future that is signalled whenever the /// info have been sent. pub fn send(self, info: IdentifyInfo, observed_addr: &Multiaddr) -> IdentifySenderFuture<T> { debug!("Sending identify info to client"); trace!("Sending: {:?}", info); let listen_addrs = info.listen_addrs .into_iter() .map(|addr| addr.to_vec()) .collect(); let pubkey_bytes = info.public_key.into_protobuf_encoding(); let mut message = structs_proto::Identify::new(); message.set_agentVersion(info.agent_version); message.set_protocolVersion(info.protocol_version); message.set_publicKey(pubkey_bytes); message.set_listenAddrs(listen_addrs); message.set_observedAddr(observed_addr.to_vec()); message.set_protocols(RepeatedField::from_vec(info.protocols)); let bytes = message .write_to_bytes() .expect("writing protobuf failed; should never happen"); IdentifySenderFuture { inner: self.inner, item: Some(bytes), } } } /// Future returned by `IdentifySender::send()`. Must be processed to the end in order to send /// the information to the remote. // Note: we don't use a `futures::sink::Sink` because it requires `T` to implement `Sink`, which // means that we would require `T: AsyncWrite` in this struct definition. This requirement // would then propagate everywhere. #[must_use = "futures do nothing unless polled"] pub struct IdentifySenderFuture<T> { /// The Sink where to send the data. inner: Framed<T, codec::UviBytes<Vec<u8>>>, /// Bytes to send, or `None` if we've already sent them. item: Option<Vec<u8>>, } impl<T> Future for IdentifySenderFuture<T> where T: AsyncWrite { type Item = (); type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if let Some(item) = self.item.take() { if let AsyncSink::NotReady(item) = self.inner.start_send(item)? { self.item = Some(item); return Ok(Async::NotReady); } } // A call to `close()` implies flushing. try_ready!(self.inner.close()); Ok(Async::Ready(())) } } /// Information sent from the listener to the dialer. #[derive(Debug, Clone)] pub struct IdentifyInfo { /// Public key of the node. pub public_key: PublicKey, /// Version of the "global" protocol, e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. pub protocol_version: String, /// Name and version of the client. Can be thought as similar to the `User-Agent` header /// of HTTP. pub agent_version: String, /// Addresses that the node is listening on. pub listen_addrs: Vec<Multiaddr>, /// Protocols supported by the node, e.g. `/ipfs/ping/1.0.0`. pub protocols: Vec<String>, } impl UpgradeInfo for IdentifyProtocolConfig { type Info = &'static [u8]; type InfoIter = iter::Once<Self::Info>; fn protocol_info(&self) -> Self::InfoIter { iter::once(b"/ipfs/id/1.0.0") } } impl<C> InboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = IdentifySender<Negotiated<C>>; type Error = IoError; type Future = FutureResult<Self::Output, IoError>; fn upgrade_inbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { trace!("Upgrading inbound connection"); let socket = Framed::new(socket, codec::UviBytes::default()); let sender = IdentifySender { inner: socket }; future::ok(sender) } } impl<C> OutboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = RemoteInfo; type Error = IoError; type Future = IdentifyOutboundFuture<Negotiated<C>>; fn upgrade_outbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { IdentifyOutboundFuture { inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()), shutdown: false, } } } /// Future returned by `OutboundUpgrade::upgrade_outbound`. pub struct IdentifyOutboundFuture<T> { inner: Framed<T, codec::UviBytes<BytesMut>>, /// If true, we have finished shutting down the writing part of `inner`. shutdown: bool, } impl<T> Future for IdentifyOutboundFuture<T> where T: AsyncRead + AsyncWrite, { type Item = RemoteInfo; type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if!self.shutdown { try_ready!(self.inner.close()); self.shutdown = true; } let msg = match try_ready!(self.inner.poll()) { Some(i) => i, None => { debug!("Identify protocol stream closed before receiving info"); return Err(IoErrorKind::InvalidData.into()); } }; debug!("Received identify message"); let (info, observed_addr) = match parse_proto_msg(msg) { Ok(v) => v, Err(err) => { debug!("Failed to parse protobuf message; error = {:?}", err); return Err(err) } }; trace!("Remote observes us as {:?}", observed_addr); trace!("Information received: {:?}", info); Ok(Async::Ready(RemoteInfo { info, observed_addr: observed_addr.clone(), _priv: () })) } } // Turns a protobuf message into an `IdentifyInfo` and an observed address. If something bad // happens, turn it into an `IoError`. fn parse_proto_msg(msg: BytesMut) -> Result<(IdentifyInfo, Multiaddr), IoError> { match protobuf_parse_from_bytes::<structs_proto::Identify>(&msg) { Ok(mut msg) => { // Turn a `Vec<u8>` into a `Multiaddr`. If something bad happens, turn it into // an `IoError`. fn bytes_to_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, IoError> { Multiaddr::try_from(bytes) .map_err(|err| IoError::new(IoErrorKind::InvalidData, err)) } let listen_addrs = { let mut addrs = Vec::new(); for addr in msg.take_listenAddrs().into_iter() { addrs.push(bytes_to_multiaddr(addr)?); } addrs }; let public_key = PublicKey::from_protobuf_encoding(msg.get_publicKey()) .map_err(|e| IoError::new(IoErrorKind::InvalidData, e))?; let observed_addr = bytes_to_multiaddr(msg.take_observedAddr())?; let info = IdentifyInfo { public_key, protocol_version: msg.take_protocolVersion(), agent_version: msg.take_agentVersion(), listen_addrs, protocols: msg.take_protocols().into_vec(), }; Ok((info, observed_addr)) } Err(err) => Err(IoError::new(IoErrorKind::InvalidData, err)), } } #[cfg(test)] mod tests { use crate::protocol::{IdentifyInfo, RemoteInfo, IdentifyProtocolConfig}; use tokio::runtime::current_thread::Runtime; use libp2p_tcp::TcpConfig; use futures::{Future, Stream}; use libp2p_core::{ identity, Transport, transport::ListenerEvent, upgrade::{apply_outbound, apply_inbound} }; use std::{io, sync::mpsc, thread}; #[test] fn correct_transfer() { // We open a server and a client, send info from the server to the client, and check that // they were successfully received. let send_pubkey = identity::Keypair::generate_ed25519().public(); let recv_pubkey = send_pubkey.clone(); let (tx, rx) = mpsc::channel(); let bg_thread = thread::spawn(move || { let transport = TcpConfig::new(); let mut listener = transport .listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()) .unwrap(); let addr = listener.by_ref().wait() .next() .expect("some event") .expect("no error") .into_new_address() .expect("listen address"); tx.send(addr).unwrap(); let future = listener .filter_map(ListenerEvent::into_upgrade) .into_future() .map_err(|(err, _)| err) .and_then(|(client, _)| client.unwrap().0) .and_then(|socket| { apply_inbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|sender| { sender.send( IdentifyInfo { public_key: send_pubkey, protocol_version: "proto_version".to_owned(), agent_version: "agent_version".to_owned(), listen_addrs: vec![ "/ip4/80.81.82.83/tcp/500".parse().unwrap(),
) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); }); let transport = TcpConfig::new(); let future = transport.dial(rx.recv().unwrap()) .unwrap() .and_then(|socket| { apply_outbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|RemoteInfo { info, observed_addr,.. }| { assert_eq!(observed_addr, "/ip4/100.101.102.103/tcp/5000".parse().unwrap()); assert_eq!(info.public_key, recv_pubkey); assert_eq!(info.protocol_version, "proto_version"); assert_eq!(info.agent_version, "agent_version"); assert_eq!(info.listen_addrs, &["/ip4/80.81.82.83/tcp/500".parse().unwrap(), "/ip6/::1/udp/1000".parse().unwrap()]); assert_eq!(info.protocols, &["proto1".to_string(), "proto2".to_string()]); Ok(()) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); bg_thread.join().unwrap(); } }
"/ip6/::1/udp/1000".parse().unwrap(), ], protocols: vec!["proto1".to_string(), "proto2".to_string()], }, &"/ip4/100.101.102.103/tcp/5000".parse().unwrap(),
random_line_split
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. use bytes::BytesMut; use crate::structs_proto; use futures::{future::{self, FutureResult}, Async, AsyncSink, Future, Poll, Sink, Stream}; use futures::try_ready; use libp2p_core::{ Multiaddr, PublicKey, upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, Negotiated} }; use log::{debug, trace}; use protobuf::Message as ProtobufMessage; use protobuf::parse_from_bytes as protobuf_parse_from_bytes; use protobuf::RepeatedField; use std::convert::TryFrom; use std::io::{Error as IoError, ErrorKind as IoErrorKind}; use std::iter; use tokio_codec::Framed; use tokio_io::{AsyncRead, AsyncWrite}; use unsigned_varint::codec; /// Configuration for an upgrade to the identity protocol. #[derive(Debug, Clone)] pub struct IdentifyProtocolConfig; #[derive(Debug, Clone)] pub struct RemoteInfo { /// Information about the remote. pub info: IdentifyInfo, /// Address the remote sees for us. pub observed_addr: Multiaddr, _priv: () } /// Object used to send back information to the client. pub struct IdentifySender<T> { inner: Framed<T, codec::UviBytes<Vec<u8>>>, } impl<T> IdentifySender<T> where T: AsyncWrite { /// Sends back information to the client. Returns a future that is signalled whenever the /// info have been sent. pub fn send(self, info: IdentifyInfo, observed_addr: &Multiaddr) -> IdentifySenderFuture<T> { debug!("Sending identify info to client"); trace!("Sending: {:?}", info); let listen_addrs = info.listen_addrs .into_iter() .map(|addr| addr.to_vec()) .collect(); let pubkey_bytes = info.public_key.into_protobuf_encoding(); let mut message = structs_proto::Identify::new(); message.set_agentVersion(info.agent_version); message.set_protocolVersion(info.protocol_version); message.set_publicKey(pubkey_bytes); message.set_listenAddrs(listen_addrs); message.set_observedAddr(observed_addr.to_vec()); message.set_protocols(RepeatedField::from_vec(info.protocols)); let bytes = message .write_to_bytes() .expect("writing protobuf failed; should never happen"); IdentifySenderFuture { inner: self.inner, item: Some(bytes), } } } /// Future returned by `IdentifySender::send()`. Must be processed to the end in order to send /// the information to the remote. // Note: we don't use a `futures::sink::Sink` because it requires `T` to implement `Sink`, which // means that we would require `T: AsyncWrite` in this struct definition. This requirement // would then propagate everywhere. #[must_use = "futures do nothing unless polled"] pub struct IdentifySenderFuture<T> { /// The Sink where to send the data. inner: Framed<T, codec::UviBytes<Vec<u8>>>, /// Bytes to send, or `None` if we've already sent them. item: Option<Vec<u8>>, } impl<T> Future for IdentifySenderFuture<T> where T: AsyncWrite { type Item = (); type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if let Some(item) = self.item.take() { if let AsyncSink::NotReady(item) = self.inner.start_send(item)? { self.item = Some(item); return Ok(Async::NotReady); } } // A call to `close()` implies flushing. try_ready!(self.inner.close()); Ok(Async::Ready(())) } } /// Information sent from the listener to the dialer. #[derive(Debug, Clone)] pub struct IdentifyInfo { /// Public key of the node. pub public_key: PublicKey, /// Version of the "global" protocol, e.g. `ipfs/1.0.0` or `polkadot/1.0.0`. pub protocol_version: String, /// Name and version of the client. Can be thought as similar to the `User-Agent` header /// of HTTP. pub agent_version: String, /// Addresses that the node is listening on. pub listen_addrs: Vec<Multiaddr>, /// Protocols supported by the node, e.g. `/ipfs/ping/1.0.0`. pub protocols: Vec<String>, } impl UpgradeInfo for IdentifyProtocolConfig { type Info = &'static [u8]; type InfoIter = iter::Once<Self::Info>; fn protocol_info(&self) -> Self::InfoIter { iter::once(b"/ipfs/id/1.0.0") } } impl<C> InboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = IdentifySender<Negotiated<C>>; type Error = IoError; type Future = FutureResult<Self::Output, IoError>; fn upgrade_inbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { trace!("Upgrading inbound connection"); let socket = Framed::new(socket, codec::UviBytes::default()); let sender = IdentifySender { inner: socket }; future::ok(sender) } } impl<C> OutboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = RemoteInfo; type Error = IoError; type Future = IdentifyOutboundFuture<Negotiated<C>>; fn upgrade_outbound(self, socket: Negotiated<C>, _: Self::Info) -> Self::Future { IdentifyOutboundFuture { inner: Framed::new(socket, codec::UviBytes::<BytesMut>::default()), shutdown: false, } } } /// Future returned by `OutboundUpgrade::upgrade_outbound`. pub struct IdentifyOutboundFuture<T> { inner: Framed<T, codec::UviBytes<BytesMut>>, /// If true, we have finished shutting down the writing part of `inner`. shutdown: bool, } impl<T> Future for IdentifyOutboundFuture<T> where T: AsyncRead + AsyncWrite, { type Item = RemoteInfo; type Error = IoError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if!self.shutdown { try_ready!(self.inner.close()); self.shutdown = true; } let msg = match try_ready!(self.inner.poll()) { Some(i) => i, None => { debug!("Identify protocol stream closed before receiving info"); return Err(IoErrorKind::InvalidData.into()); } }; debug!("Received identify message"); let (info, observed_addr) = match parse_proto_msg(msg) { Ok(v) => v, Err(err) => { debug!("Failed to parse protobuf message; error = {:?}", err); return Err(err) } }; trace!("Remote observes us as {:?}", observed_addr); trace!("Information received: {:?}", info); Ok(Async::Ready(RemoteInfo { info, observed_addr: observed_addr.clone(), _priv: () })) } } // Turns a protobuf message into an `IdentifyInfo` and an observed address. If something bad // happens, turn it into an `IoError`. fn parse_proto_msg(msg: BytesMut) -> Result<(IdentifyInfo, Multiaddr), IoError> { match protobuf_parse_from_bytes::<structs_proto::Identify>(&msg) { Ok(mut msg) => { // Turn a `Vec<u8>` into a `Multiaddr`. If something bad happens, turn it into // an `IoError`. fn bytes_to_multiaddr(bytes: Vec<u8>) -> Result<Multiaddr, IoError>
let listen_addrs = { let mut addrs = Vec::new(); for addr in msg.take_listenAddrs().into_iter() { addrs.push(bytes_to_multiaddr(addr)?); } addrs }; let public_key = PublicKey::from_protobuf_encoding(msg.get_publicKey()) .map_err(|e| IoError::new(IoErrorKind::InvalidData, e))?; let observed_addr = bytes_to_multiaddr(msg.take_observedAddr())?; let info = IdentifyInfo { public_key, protocol_version: msg.take_protocolVersion(), agent_version: msg.take_agentVersion(), listen_addrs, protocols: msg.take_protocols().into_vec(), }; Ok((info, observed_addr)) } Err(err) => Err(IoError::new(IoErrorKind::InvalidData, err)), } } #[cfg(test)] mod tests { use crate::protocol::{IdentifyInfo, RemoteInfo, IdentifyProtocolConfig}; use tokio::runtime::current_thread::Runtime; use libp2p_tcp::TcpConfig; use futures::{Future, Stream}; use libp2p_core::{ identity, Transport, transport::ListenerEvent, upgrade::{apply_outbound, apply_inbound} }; use std::{io, sync::mpsc, thread}; #[test] fn correct_transfer() { // We open a server and a client, send info from the server to the client, and check that // they were successfully received. let send_pubkey = identity::Keypair::generate_ed25519().public(); let recv_pubkey = send_pubkey.clone(); let (tx, rx) = mpsc::channel(); let bg_thread = thread::spawn(move || { let transport = TcpConfig::new(); let mut listener = transport .listen_on("/ip4/127.0.0.1/tcp/0".parse().unwrap()) .unwrap(); let addr = listener.by_ref().wait() .next() .expect("some event") .expect("no error") .into_new_address() .expect("listen address"); tx.send(addr).unwrap(); let future = listener .filter_map(ListenerEvent::into_upgrade) .into_future() .map_err(|(err, _)| err) .and_then(|(client, _)| client.unwrap().0) .and_then(|socket| { apply_inbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|sender| { sender.send( IdentifyInfo { public_key: send_pubkey, protocol_version: "proto_version".to_owned(), agent_version: "agent_version".to_owned(), listen_addrs: vec![ "/ip4/80.81.82.83/tcp/500".parse().unwrap(), "/ip6/::1/udp/1000".parse().unwrap(), ], protocols: vec!["proto1".to_string(), "proto2".to_string()], }, &"/ip4/100.101.102.103/tcp/5000".parse().unwrap(), ) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); }); let transport = TcpConfig::new(); let future = transport.dial(rx.recv().unwrap()) .unwrap() .and_then(|socket| { apply_outbound(socket, IdentifyProtocolConfig) .map_err(|e| io::Error::new(io::ErrorKind::Other, e)) }) .and_then(|RemoteInfo { info, observed_addr,.. }| { assert_eq!(observed_addr, "/ip4/100.101.102.103/tcp/5000".parse().unwrap()); assert_eq!(info.public_key, recv_pubkey); assert_eq!(info.protocol_version, "proto_version"); assert_eq!(info.agent_version, "agent_version"); assert_eq!(info.listen_addrs, &["/ip4/80.81.82.83/tcp/500".parse().unwrap(), "/ip6/::1/udp/1000".parse().unwrap()]); assert_eq!(info.protocols, &["proto1".to_string(), "proto2".to_string()]); Ok(()) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); bg_thread.join().unwrap(); } }
{ Multiaddr::try_from(bytes) .map_err(|err| IoError::new(IoErrorKind::InvalidData, err)) }
identifier_body
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofResponse, }, transcript::{TranscriptProtocol, UpdateTranscript}, CipherText, CommitmentWitness, ElgamalPublicKey, }; use bulletproofs::PedersenGens; use curve25519_dalek::{ constants::RISTRETTO_BASEPOINT_POINT, ristretto::{CompressedRistretto, RistrettoPoint}, scalar::Scalar, }; use merlin::{Transcript, TranscriptRng}; use rand_core::{CryptoRng, RngCore}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use zeroize::Zeroize; use codec::{Decode, Encode, Error as CodecError, Input, Output}; use sp_std::convert::From; /// The domain label for the correctness proof. pub const CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL: &[u8] = b"PolymathCorrectnessFinalResponse"; /// The domain label for the challenge. pub const CORRECTNESS_PROOF_CHALLENGE_LABEL: &[u8] = b"PolymathCorrectnessChallenge"; // ------------------------------------------------------------------------ // Proof of Correct Encryption of the Given Value // ------------------------------------------------------------------------ #[derive(PartialEq, Copy, Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessFinalResponse(Scalar); impl From<Scalar> for CorrectnessFinalResponse { fn from(response: Scalar) -> Self { CorrectnessFinalResponse(response) } } impl Encode for CorrectnessFinalResponse { fn size_hint(&self) -> usize { 32 } fn encode_to<W: Output>(&self, dest: &mut W) { self.0.as_bytes().encode_to(dest) } } impl Decode for CorrectnessFinalResponse { fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError>
} #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessInitialMessage { a: RistrettoPoint, b: RistrettoPoint, } impl Encode for CorrectnessInitialMessage { fn size_hint(&self) -> usize { 64 } fn encode_to<W: Output>(&self, dest: &mut W) { let a = self.a.compress(); let b = self.b.compress(); a.as_bytes().encode_to(dest); b.as_bytes().encode_to(dest); } } impl Decode for CorrectnessInitialMessage { fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> { let (a, b) = <([u8; 32], [u8; 32])>::decode(input)?; let a = CompressedRistretto(a) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'a' point is invalid"))?; let b = CompressedRistretto(b) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'b' point is invalid"))?; Ok(CorrectnessInitialMessage { a, b }) } } /// A default implementation used for testing. impl Default for CorrectnessInitialMessage { fn default() -> Self { CorrectnessInitialMessage { a: RISTRETTO_BASEPOINT_POINT, b: RISTRETTO_BASEPOINT_POINT, } } } impl UpdateTranscript for CorrectnessInitialMessage { fn update_transcript(&self, transcript: &mut Transcript) -> Fallible<()> { transcript.append_domain_separator(CORRECTNESS_PROOF_CHALLENGE_LABEL); transcript.append_validated_point(b"A", &self.a.compress())?; transcript.append_validated_point(b"B", &self.b.compress())?; Ok(()) } } /// Holds the non-interactive proofs of correctness, equivalent of L_correct of MERCAT paper. pub type CorrectnessProof = ZKProofResponse<CorrectnessInitialMessage, CorrectnessFinalResponse>; pub struct CorrectnessProverAwaitingChallenge<'a> { /// The public key used for the elgamal encryption. pub pub_key: ElgamalPublicKey, /// The secret commitment witness. pub w: CommitmentWitness, /// Pedersen Generators pub pc_gens: &'a PedersenGens, } #[derive(Zeroize)] #[zeroize(drop)] pub struct CorrectnessProver { /// The secret commitment witness. w: CommitmentWitness, /// The randomness generate in the first round. u: Scalar, } impl<'a> AssetProofProverAwaitingChallenge for CorrectnessProverAwaitingChallenge<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; type ZKProver = CorrectnessProver; fn create_transcript_rng<T: RngCore + CryptoRng>( &self, rng: &mut T, transcript: &Transcript, ) -> TranscriptRng { transcript.create_transcript_rng_from_witness(rng, &self.w) } fn generate_initial_message( &self, rng: &mut TranscriptRng, ) -> (Self::ZKProver, Self::ZKInitialMessage) { let rand_commitment = Scalar::random(rng); ( CorrectnessProver { w: self.w.clone(), u: rand_commitment, }, CorrectnessInitialMessage { a: rand_commitment * self.pub_key.pub_key, b: rand_commitment * self.pc_gens.B_blinding, }, ) } } impl AssetProofProver<CorrectnessFinalResponse> for CorrectnessProver { fn apply_challenge(&self, c: &ZKPChallenge) -> CorrectnessFinalResponse { CorrectnessFinalResponse(self.u + c.x() * self.w.blinding()) } } pub struct CorrectnessVerifier<'a> { /// The encrypted value (aka the plain text). pub value: Scalar, /// The public key to which the `value` is encrypted. pub pub_key: ElgamalPublicKey, /// The encryption cipher text. pub cipher: CipherText, /// The Generator Points pub pc_gens: &'a PedersenGens, } impl<'a> AssetProofVerifier for CorrectnessVerifier<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; fn verify( &self, challenge: &ZKPChallenge, initial_message: &Self::ZKInitialMessage, z: &Self::ZKFinalResponse, ) -> Fallible<()> { let generators = self.pc_gens; let y_prime = self.cipher.y - (self.value * generators.B); ensure!( z.0 * self.pub_key.pub_key == initial_message.a + challenge.x() * self.cipher.x, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); ensure!( z.0 * generators.B_blinding == initial_message.b + challenge.x() * y_prime, ErrorKind::CorrectnessFinalResponseVerificationError { check: 2 } ); Ok(()) } } // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ #[cfg(test)] mod tests { extern crate wasm_bindgen_test; use super::*; use crate::asset_proofs::*; use rand::{rngs::StdRng, SeedableRng}; use wasm_bindgen_test::*; const SEED_1: [u8; 32] = [17u8; 32]; #[test] #[wasm_bindgen_test] fn test_correctness_proof() { let gens = PedersenGens::default(); let mut rng = StdRng::from_seed(SEED_1); let secret_value = 13u32; let elg_secret = ElgamalSecretKey::new(Scalar::random(&mut rng)); let elg_pub = elg_secret.get_public_key(); let (w, cipher) = elg_pub.encrypt_value(secret_value.into(), &mut rng); let prover = CorrectnessProverAwaitingChallenge { pub_key: elg_pub, w, pc_gens: &gens, }; let verifier = CorrectnessVerifier { value: Scalar::from(secret_value), pub_key: elg_pub, cipher, pc_gens: &gens, }; let mut transcript = Transcript::new(CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL); // Positive tests let mut transcript_rng = prover.create_transcript_rng(&mut rng, &transcript); let (prover, initial_message) = prover.generate_initial_message(&mut transcript_rng); initial_message.update_transcript(&mut transcript).unwrap(); let challenge = transcript .scalar_challenge(CORRECTNESS_PROOF_CHALLENGE_LABEL) .unwrap(); let final_response = prover.apply_challenge(&challenge); let result = verifier.verify(&challenge, &initial_message, &final_response); assert!(result.is_ok()); // Negative tests let bad_initial_message = CorrectnessInitialMessage::default(); let result = verifier.verify(&challenge, &bad_initial_message, &final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); let bad_final_response = CorrectnessFinalResponse(Scalar::default()); let result = verifier.verify(&challenge, &initial_message, &bad_final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); } #[test] #[wasm_bindgen_test] fn serialize_deserialize_proof() { let mut rng = StdRng::from_seed(SEED_1); let secret_value = 42u32; let secret_key = ElgamalSecretKey::new(Scalar::random(&mut rng)); let pub_key = secret_key.get_public_key(); let rand_blind = Scalar::random(&mut rng); let w = CommitmentWitness::new(secret_value.into(), rand_blind); let gens = PedersenGens::default(); let prover = CorrectnessProverAwaitingChallenge { pub_key, w, pc_gens: &gens, }; let (initial_message, final_response) = encryption_proofs::single_property_prover::< StdRng, CorrectnessProverAwaitingChallenge, >(prover, &mut rng) .unwrap(); let bytes = initial_message.encode(); let mut input = bytes.as_slice(); let recovered_initial_message = <CorrectnessInitialMessage>::decode(&mut input).unwrap(); assert_eq!(recovered_initial_message, initial_message); let bytes = final_response.encode(); let mut input = bytes.as_slice(); let recovered_final_response = <CorrectnessFinalResponse>::decode(&mut input).unwrap(); assert_eq!(recovered_final_response, final_response); } }
{ let scalar = <[u8; 32]>::decode(input)?; let scalar = Scalar::from_canonical_bytes(scalar) .ok_or_else(|| CodecError::from("CorrectnessFinalResponse is invalid"))?; Ok(CorrectnessFinalResponse(scalar)) }
identifier_body
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofResponse, }, transcript::{TranscriptProtocol, UpdateTranscript}, CipherText, CommitmentWitness, ElgamalPublicKey, }; use bulletproofs::PedersenGens; use curve25519_dalek::{ constants::RISTRETTO_BASEPOINT_POINT, ristretto::{CompressedRistretto, RistrettoPoint}, scalar::Scalar, }; use merlin::{Transcript, TranscriptRng}; use rand_core::{CryptoRng, RngCore}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use zeroize::Zeroize; use codec::{Decode, Encode, Error as CodecError, Input, Output}; use sp_std::convert::From; /// The domain label for the correctness proof. pub const CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL: &[u8] = b"PolymathCorrectnessFinalResponse"; /// The domain label for the challenge. pub const CORRECTNESS_PROOF_CHALLENGE_LABEL: &[u8] = b"PolymathCorrectnessChallenge"; // ------------------------------------------------------------------------ // Proof of Correct Encryption of the Given Value // ------------------------------------------------------------------------ #[derive(PartialEq, Copy, Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessFinalResponse(Scalar); impl From<Scalar> for CorrectnessFinalResponse { fn from(response: Scalar) -> Self { CorrectnessFinalResponse(response) } } impl Encode for CorrectnessFinalResponse { fn size_hint(&self) -> usize { 32 } fn encode_to<W: Output>(&self, dest: &mut W) { self.0.as_bytes().encode_to(dest) } } impl Decode for CorrectnessFinalResponse { fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> { let scalar = <[u8; 32]>::decode(input)?; let scalar = Scalar::from_canonical_bytes(scalar) .ok_or_else(|| CodecError::from("CorrectnessFinalResponse is invalid"))?; Ok(CorrectnessFinalResponse(scalar)) } } #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessInitialMessage { a: RistrettoPoint, b: RistrettoPoint, } impl Encode for CorrectnessInitialMessage { fn size_hint(&self) -> usize { 64 } fn encode_to<W: Output>(&self, dest: &mut W) { let a = self.a.compress(); let b = self.b.compress(); a.as_bytes().encode_to(dest); b.as_bytes().encode_to(dest); } } impl Decode for CorrectnessInitialMessage { fn
<I: Input>(input: &mut I) -> Result<Self, CodecError> { let (a, b) = <([u8; 32], [u8; 32])>::decode(input)?; let a = CompressedRistretto(a) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'a' point is invalid"))?; let b = CompressedRistretto(b) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'b' point is invalid"))?; Ok(CorrectnessInitialMessage { a, b }) } } /// A default implementation used for testing. impl Default for CorrectnessInitialMessage { fn default() -> Self { CorrectnessInitialMessage { a: RISTRETTO_BASEPOINT_POINT, b: RISTRETTO_BASEPOINT_POINT, } } } impl UpdateTranscript for CorrectnessInitialMessage { fn update_transcript(&self, transcript: &mut Transcript) -> Fallible<()> { transcript.append_domain_separator(CORRECTNESS_PROOF_CHALLENGE_LABEL); transcript.append_validated_point(b"A", &self.a.compress())?; transcript.append_validated_point(b"B", &self.b.compress())?; Ok(()) } } /// Holds the non-interactive proofs of correctness, equivalent of L_correct of MERCAT paper. pub type CorrectnessProof = ZKProofResponse<CorrectnessInitialMessage, CorrectnessFinalResponse>; pub struct CorrectnessProverAwaitingChallenge<'a> { /// The public key used for the elgamal encryption. pub pub_key: ElgamalPublicKey, /// The secret commitment witness. pub w: CommitmentWitness, /// Pedersen Generators pub pc_gens: &'a PedersenGens, } #[derive(Zeroize)] #[zeroize(drop)] pub struct CorrectnessProver { /// The secret commitment witness. w: CommitmentWitness, /// The randomness generate in the first round. u: Scalar, } impl<'a> AssetProofProverAwaitingChallenge for CorrectnessProverAwaitingChallenge<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; type ZKProver = CorrectnessProver; fn create_transcript_rng<T: RngCore + CryptoRng>( &self, rng: &mut T, transcript: &Transcript, ) -> TranscriptRng { transcript.create_transcript_rng_from_witness(rng, &self.w) } fn generate_initial_message( &self, rng: &mut TranscriptRng, ) -> (Self::ZKProver, Self::ZKInitialMessage) { let rand_commitment = Scalar::random(rng); ( CorrectnessProver { w: self.w.clone(), u: rand_commitment, }, CorrectnessInitialMessage { a: rand_commitment * self.pub_key.pub_key, b: rand_commitment * self.pc_gens.B_blinding, }, ) } } impl AssetProofProver<CorrectnessFinalResponse> for CorrectnessProver { fn apply_challenge(&self, c: &ZKPChallenge) -> CorrectnessFinalResponse { CorrectnessFinalResponse(self.u + c.x() * self.w.blinding()) } } pub struct CorrectnessVerifier<'a> { /// The encrypted value (aka the plain text). pub value: Scalar, /// The public key to which the `value` is encrypted. pub pub_key: ElgamalPublicKey, /// The encryption cipher text. pub cipher: CipherText, /// The Generator Points pub pc_gens: &'a PedersenGens, } impl<'a> AssetProofVerifier for CorrectnessVerifier<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; fn verify( &self, challenge: &ZKPChallenge, initial_message: &Self::ZKInitialMessage, z: &Self::ZKFinalResponse, ) -> Fallible<()> { let generators = self.pc_gens; let y_prime = self.cipher.y - (self.value * generators.B); ensure!( z.0 * self.pub_key.pub_key == initial_message.a + challenge.x() * self.cipher.x, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); ensure!( z.0 * generators.B_blinding == initial_message.b + challenge.x() * y_prime, ErrorKind::CorrectnessFinalResponseVerificationError { check: 2 } ); Ok(()) } } // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ #[cfg(test)] mod tests { extern crate wasm_bindgen_test; use super::*; use crate::asset_proofs::*; use rand::{rngs::StdRng, SeedableRng}; use wasm_bindgen_test::*; const SEED_1: [u8; 32] = [17u8; 32]; #[test] #[wasm_bindgen_test] fn test_correctness_proof() { let gens = PedersenGens::default(); let mut rng = StdRng::from_seed(SEED_1); let secret_value = 13u32; let elg_secret = ElgamalSecretKey::new(Scalar::random(&mut rng)); let elg_pub = elg_secret.get_public_key(); let (w, cipher) = elg_pub.encrypt_value(secret_value.into(), &mut rng); let prover = CorrectnessProverAwaitingChallenge { pub_key: elg_pub, w, pc_gens: &gens, }; let verifier = CorrectnessVerifier { value: Scalar::from(secret_value), pub_key: elg_pub, cipher, pc_gens: &gens, }; let mut transcript = Transcript::new(CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL); // Positive tests let mut transcript_rng = prover.create_transcript_rng(&mut rng, &transcript); let (prover, initial_message) = prover.generate_initial_message(&mut transcript_rng); initial_message.update_transcript(&mut transcript).unwrap(); let challenge = transcript .scalar_challenge(CORRECTNESS_PROOF_CHALLENGE_LABEL) .unwrap(); let final_response = prover.apply_challenge(&challenge); let result = verifier.verify(&challenge, &initial_message, &final_response); assert!(result.is_ok()); // Negative tests let bad_initial_message = CorrectnessInitialMessage::default(); let result = verifier.verify(&challenge, &bad_initial_message, &final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); let bad_final_response = CorrectnessFinalResponse(Scalar::default()); let result = verifier.verify(&challenge, &initial_message, &bad_final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); } #[test] #[wasm_bindgen_test] fn serialize_deserialize_proof() { let mut rng = StdRng::from_seed(SEED_1); let secret_value = 42u32; let secret_key = ElgamalSecretKey::new(Scalar::random(&mut rng)); let pub_key = secret_key.get_public_key(); let rand_blind = Scalar::random(&mut rng); let w = CommitmentWitness::new(secret_value.into(), rand_blind); let gens = PedersenGens::default(); let prover = CorrectnessProverAwaitingChallenge { pub_key, w, pc_gens: &gens, }; let (initial_message, final_response) = encryption_proofs::single_property_prover::< StdRng, CorrectnessProverAwaitingChallenge, >(prover, &mut rng) .unwrap(); let bytes = initial_message.encode(); let mut input = bytes.as_slice(); let recovered_initial_message = <CorrectnessInitialMessage>::decode(&mut input).unwrap(); assert_eq!(recovered_initial_message, initial_message); let bytes = final_response.encode(); let mut input = bytes.as_slice(); let recovered_final_response = <CorrectnessFinalResponse>::decode(&mut input).unwrap(); assert_eq!(recovered_final_response, final_response); } }
decode
identifier_name
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofResponse, }, transcript::{TranscriptProtocol, UpdateTranscript}, CipherText, CommitmentWitness, ElgamalPublicKey, }; use bulletproofs::PedersenGens; use curve25519_dalek::{ constants::RISTRETTO_BASEPOINT_POINT, ristretto::{CompressedRistretto, RistrettoPoint}, scalar::Scalar, }; use merlin::{Transcript, TranscriptRng}; use rand_core::{CryptoRng, RngCore}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use zeroize::Zeroize; use codec::{Decode, Encode, Error as CodecError, Input, Output}; use sp_std::convert::From; /// The domain label for the correctness proof. pub const CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL: &[u8] = b"PolymathCorrectnessFinalResponse"; /// The domain label for the challenge. pub const CORRECTNESS_PROOF_CHALLENGE_LABEL: &[u8] = b"PolymathCorrectnessChallenge"; // ------------------------------------------------------------------------ // Proof of Correct Encryption of the Given Value // ------------------------------------------------------------------------ #[derive(PartialEq, Copy, Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessFinalResponse(Scalar); impl From<Scalar> for CorrectnessFinalResponse { fn from(response: Scalar) -> Self { CorrectnessFinalResponse(response) } } impl Encode for CorrectnessFinalResponse { fn size_hint(&self) -> usize { 32 } fn encode_to<W: Output>(&self, dest: &mut W) { self.0.as_bytes().encode_to(dest) } } impl Decode for CorrectnessFinalResponse { fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> { let scalar = <[u8; 32]>::decode(input)?; let scalar = Scalar::from_canonical_bytes(scalar) .ok_or_else(|| CodecError::from("CorrectnessFinalResponse is invalid"))?; Ok(CorrectnessFinalResponse(scalar)) } } #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessInitialMessage { a: RistrettoPoint, b: RistrettoPoint, } impl Encode for CorrectnessInitialMessage { fn size_hint(&self) -> usize { 64 } fn encode_to<W: Output>(&self, dest: &mut W) { let a = self.a.compress(); let b = self.b.compress(); a.as_bytes().encode_to(dest); b.as_bytes().encode_to(dest); } } impl Decode for CorrectnessInitialMessage { fn decode<I: Input>(input: &mut I) -> Result<Self, CodecError> { let (a, b) = <([u8; 32], [u8; 32])>::decode(input)?; let a = CompressedRistretto(a) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'a' point is invalid"))?; let b = CompressedRistretto(b) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'b' point is invalid"))?; Ok(CorrectnessInitialMessage { a, b }) } }
/// A default implementation used for testing. impl Default for CorrectnessInitialMessage { fn default() -> Self { CorrectnessInitialMessage { a: RISTRETTO_BASEPOINT_POINT, b: RISTRETTO_BASEPOINT_POINT, } } } impl UpdateTranscript for CorrectnessInitialMessage { fn update_transcript(&self, transcript: &mut Transcript) -> Fallible<()> { transcript.append_domain_separator(CORRECTNESS_PROOF_CHALLENGE_LABEL); transcript.append_validated_point(b"A", &self.a.compress())?; transcript.append_validated_point(b"B", &self.b.compress())?; Ok(()) } } /// Holds the non-interactive proofs of correctness, equivalent of L_correct of MERCAT paper. pub type CorrectnessProof = ZKProofResponse<CorrectnessInitialMessage, CorrectnessFinalResponse>; pub struct CorrectnessProverAwaitingChallenge<'a> { /// The public key used for the elgamal encryption. pub pub_key: ElgamalPublicKey, /// The secret commitment witness. pub w: CommitmentWitness, /// Pedersen Generators pub pc_gens: &'a PedersenGens, } #[derive(Zeroize)] #[zeroize(drop)] pub struct CorrectnessProver { /// The secret commitment witness. w: CommitmentWitness, /// The randomness generate in the first round. u: Scalar, } impl<'a> AssetProofProverAwaitingChallenge for CorrectnessProverAwaitingChallenge<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; type ZKProver = CorrectnessProver; fn create_transcript_rng<T: RngCore + CryptoRng>( &self, rng: &mut T, transcript: &Transcript, ) -> TranscriptRng { transcript.create_transcript_rng_from_witness(rng, &self.w) } fn generate_initial_message( &self, rng: &mut TranscriptRng, ) -> (Self::ZKProver, Self::ZKInitialMessage) { let rand_commitment = Scalar::random(rng); ( CorrectnessProver { w: self.w.clone(), u: rand_commitment, }, CorrectnessInitialMessage { a: rand_commitment * self.pub_key.pub_key, b: rand_commitment * self.pc_gens.B_blinding, }, ) } } impl AssetProofProver<CorrectnessFinalResponse> for CorrectnessProver { fn apply_challenge(&self, c: &ZKPChallenge) -> CorrectnessFinalResponse { CorrectnessFinalResponse(self.u + c.x() * self.w.blinding()) } } pub struct CorrectnessVerifier<'a> { /// The encrypted value (aka the plain text). pub value: Scalar, /// The public key to which the `value` is encrypted. pub pub_key: ElgamalPublicKey, /// The encryption cipher text. pub cipher: CipherText, /// The Generator Points pub pc_gens: &'a PedersenGens, } impl<'a> AssetProofVerifier for CorrectnessVerifier<'a> { type ZKInitialMessage = CorrectnessInitialMessage; type ZKFinalResponse = CorrectnessFinalResponse; fn verify( &self, challenge: &ZKPChallenge, initial_message: &Self::ZKInitialMessage, z: &Self::ZKFinalResponse, ) -> Fallible<()> { let generators = self.pc_gens; let y_prime = self.cipher.y - (self.value * generators.B); ensure!( z.0 * self.pub_key.pub_key == initial_message.a + challenge.x() * self.cipher.x, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); ensure!( z.0 * generators.B_blinding == initial_message.b + challenge.x() * y_prime, ErrorKind::CorrectnessFinalResponseVerificationError { check: 2 } ); Ok(()) } } // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ #[cfg(test)] mod tests { extern crate wasm_bindgen_test; use super::*; use crate::asset_proofs::*; use rand::{rngs::StdRng, SeedableRng}; use wasm_bindgen_test::*; const SEED_1: [u8; 32] = [17u8; 32]; #[test] #[wasm_bindgen_test] fn test_correctness_proof() { let gens = PedersenGens::default(); let mut rng = StdRng::from_seed(SEED_1); let secret_value = 13u32; let elg_secret = ElgamalSecretKey::new(Scalar::random(&mut rng)); let elg_pub = elg_secret.get_public_key(); let (w, cipher) = elg_pub.encrypt_value(secret_value.into(), &mut rng); let prover = CorrectnessProverAwaitingChallenge { pub_key: elg_pub, w, pc_gens: &gens, }; let verifier = CorrectnessVerifier { value: Scalar::from(secret_value), pub_key: elg_pub, cipher, pc_gens: &gens, }; let mut transcript = Transcript::new(CORRECTNESS_PROOF_FINAL_RESPONSE_LABEL); // Positive tests let mut transcript_rng = prover.create_transcript_rng(&mut rng, &transcript); let (prover, initial_message) = prover.generate_initial_message(&mut transcript_rng); initial_message.update_transcript(&mut transcript).unwrap(); let challenge = transcript .scalar_challenge(CORRECTNESS_PROOF_CHALLENGE_LABEL) .unwrap(); let final_response = prover.apply_challenge(&challenge); let result = verifier.verify(&challenge, &initial_message, &final_response); assert!(result.is_ok()); // Negative tests let bad_initial_message = CorrectnessInitialMessage::default(); let result = verifier.verify(&challenge, &bad_initial_message, &final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); let bad_final_response = CorrectnessFinalResponse(Scalar::default()); let result = verifier.verify(&challenge, &initial_message, &bad_final_response); assert_err!( result, ErrorKind::CorrectnessFinalResponseVerificationError { check: 1 } ); } #[test] #[wasm_bindgen_test] fn serialize_deserialize_proof() { let mut rng = StdRng::from_seed(SEED_1); let secret_value = 42u32; let secret_key = ElgamalSecretKey::new(Scalar::random(&mut rng)); let pub_key = secret_key.get_public_key(); let rand_blind = Scalar::random(&mut rng); let w = CommitmentWitness::new(secret_value.into(), rand_blind); let gens = PedersenGens::default(); let prover = CorrectnessProverAwaitingChallenge { pub_key, w, pc_gens: &gens, }; let (initial_message, final_response) = encryption_proofs::single_property_prover::< StdRng, CorrectnessProverAwaitingChallenge, >(prover, &mut rng) .unwrap(); let bytes = initial_message.encode(); let mut input = bytes.as_slice(); let recovered_initial_message = <CorrectnessInitialMessage>::decode(&mut input).unwrap(); assert_eq!(recovered_initial_message, initial_message); let bytes = final_response.encode(); let mut input = bytes.as_slice(); let recovered_final_response = <CorrectnessFinalResponse>::decode(&mut input).unwrap(); assert_eq!(recovered_final_response, final_response); } }
random_line_split
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> { use std::mem; wgpu::VertexBufferDescriptor { stride: mem::size_of::<Vertex>() as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, attributes: &[ wgpu::VertexAttributeDescriptor { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float3, }, wgpu::VertexAttributeDescriptor { offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float2, }, ], } } } const VERTICES: &[Vertex] = &[ Vertex { position: [-0.5, -0.5, 0.0], tex_coords: [0.0, 0.0], }, Vertex { position: [0.5, -0.5, 0.0], tex_coords: [2.0, 0.0], }, Vertex { position: [0.5, 0.5, 0.0], tex_coords: [2.0, 2.0], }, Vertex { position: [-0.5, 0.5, 0.0], tex_coords: [0.0, 2.0], }, ]; const INDICES: &[u16] = &[2, 1, 0, 3, 2, 0]; struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, swap_chain: wgpu::SwapChain, sc_desc: wgpu::SwapChainDescriptor, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer, num_indices: u32, diffuse_texture: wgpu::Texture, diffuse_texture_view: wgpu::TextureView, diffuse_sampler: wgpu::Sampler, diffuse_bind_group: wgpu::BindGroup, size: winit::dpi::PhysicalSize<u32>, } fn rgba_color(r: u32, g: u32, b: u32, a: u32) -> u32 { r | (g << 8) | (b << 16) | (a << 24) } impl State { fn new(window: &Window) -> Self { let size = window.inner_size(); let surface = wgpu::Surface::create(window); let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { ..Default::default() }) .unwrap(); let (device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: Default::default(), }); let (sc_desc, swap_chain) = Self::create_swap_chain(&device, size, &surface); let ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) = Self::create_texture_stuff(&device, &mut queue); let render_pipeline = Self::create_pipeline(&device, &sc_desc, &texture_bind_group_layout); let vertex_buffer = device .create_buffer_mapped(VERTICES.len(), wgpu::BufferUsage::VERTEX) .fill_from_slice(VERTICES); let index_buffer = device .create_buffer_mapped(INDICES.len(), wgpu::BufferUsage::INDEX) .fill_from_slice(INDICES); let num_indices = INDICES.len() as u32; Self { surface, device, queue, sc_desc, swap_chain, render_pipeline, vertex_buffer, index_buffer, num_indices, diffuse_texture, diffuse_texture_view, diffuse_sampler, diffuse_bind_group, size, } } fn create_pipeline( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, texture_bind_group_layout: &wgpu::BindGroupLayout, ) -> wgpu::RenderPipeline { let vs_src = include_str!("vert.glsl"); let fs_src = include_str!("frag.glsl"); let vs_spirv = glsl_to_spirv::compile(vs_src, glsl_to_spirv::ShaderType::Vertex).unwrap(); let fs_spirv = glsl_to_spirv::compile(fs_src, glsl_to_spirv::ShaderType::Fragment).unwrap(); let vs_data = wgpu::read_spirv(vs_spirv).unwrap(); let fs_data = wgpu::read_spirv(fs_spirv).unwrap(); let vs_module = device.create_shader_module(&vs_data); let fs_module = device.create_shader_module(&fs_data); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { bind_group_layouts: &[&texture_bind_group_layout], }); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { layout: &render_pipeline_layout, vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", }, fragment_stage: Some(wgpu::ProgrammableStageDescriptor { module: &fs_module, entry_point: "main", }), rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw, cull_mode: wgpu::CullMode::Back, depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { format: sc_desc.format, color_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::SrcAlpha, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, write_mask: wgpu::ColorWrite::ALL, }], depth_stencil_state: None, index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[Vertex::desc()], sample_count: 1, sample_mask:!0, alpha_to_coverage_enabled: false, }) } fn create_swap_chain( device: &wgpu::Device, size: PhysicalSize<u32>, surface: &wgpu::Surface, ) -> (wgpu::SwapChainDescriptor, wgpu::SwapChain) { let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Vsync, }; let swapchain = device.create_swap_chain(surface, &sc_desc); (sc_desc, swapchain) } fn create_texture_stuff( device: &wgpu::Device, queue: &mut wgpu::Queue, ) -> ( wgpu::Extent3d, wgpu::Texture, wgpu::Buffer, wgpu::Sampler, wgpu::TextureView, wgpu::BindGroup, wgpu::BindGroupLayout, ) { //let diffuse_bytes = include_bytes!("../happy-tree.png"); let font_bytes = include_bytes!("../ttf/JetBrainsMono-Regular.ttf"); let font = Font::from_bytes(font_bytes as &[u8]).expect("Failed to create font"); let glyph = font .glyph('c') .scaled(Scale { x: 50.0, y: 50.0 }) .positioned(point(10.0, 10.0)); let (gpos_x, gpos_y) = (glyph.position().x, glyph.position().y); let mut font_buffer = vec![]; for _ in 0..40_000 { font_buffer.push(rgba_color(255, 255, 255, 0)); } glyph.draw(|y, x, v| { font_buffer[((x + gpos_x as u32) * 200 + y + gpos_y as u32) as usize] = rgba_color(255, 0, 0, (v * 255.0) as u32); }); let dimensions = (200, 200); let size3d = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth: 1, }; let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor { size: size3d, array_layer_count: 1, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, }); let diffuse_buffer = device .create_buffer_mapped(font_buffer.len(), wgpu::BufferUsage::COPY_SRC) .fill_from_slice(&font_buffer); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); encoder.copy_buffer_to_texture( wgpu::BufferCopyView { buffer: &diffuse_buffer, offset: 0, row_pitch: 4 * dimensions.0, image_height: dimensions.1, }, wgpu::TextureCopyView { texture: &diffuse_texture, mip_level: 0, array_layer: 0, origin: wgpu::Origin3d::ZERO, }, size3d, ); queue.submit(&[encoder.finish()]); let diffuse_texture_view = diffuse_texture.create_default_view(); let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, lod_min_clamp: -100.0, lod_max_clamp: 100.0, compare_function: wgpu::CompareFunction::Always, }); let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[ wgpu::BindGroupLayoutBinding { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::SampledTexture { multisampled: false, dimension: wgpu::TextureViewDimension::D2, }, }, wgpu::BindGroupLayoutBinding { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler, }, ], }); let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &texture_bind_group_layout, bindings: &[ wgpu::Binding { binding: 0, resource: wgpu::BindingResource::TextureView(&diffuse_texture_view), }, wgpu::Binding { binding: 1, resource: wgpu::BindingResource::Sampler(&diffuse_sampler), }, ], }); ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) } fn
(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } fn render(&mut self) { let frame = self.swap_chain.get_next_texture(); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }, }], depth_stencil_attachment: None, }); render_pass.set_pipeline(&self.render_pipeline); render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); render_pass.set_vertex_buffers(0, &[(&self.vertex_buffer, 0)]); render_pass.set_index_buffer(&self.index_buffer, 0); render_pass.draw_indexed(0..self.num_indices, 0, 0..1); } self.queue.submit(&[encoder.finish()]); } } fn main() { let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_inner_size(PhysicalSize::new(500, 500)) .build(&event_loop) .unwrap(); let mut state = State::new(&window); event_loop.run(move |event, _, control_flow| match event { Event::WindowEvent { ref event, window_id, } if window_id == window.id() => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::KeyboardInput { input,.. } => match input { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::Wait, }, WindowEvent::Resized(physical_size) => { state.resize(*physical_size); *control_flow = ControlFlow::Wait; } WindowEvent::ScaleFactorChanged { new_inner_size,.. } => { state.resize(**new_inner_size); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }, Event::MainEventsCleared => { state.render(); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }); }
resize
identifier_name
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> { use std::mem; wgpu::VertexBufferDescriptor { stride: mem::size_of::<Vertex>() as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, attributes: &[ wgpu::VertexAttributeDescriptor { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float3, }, wgpu::VertexAttributeDescriptor { offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float2, }, ], } } } const VERTICES: &[Vertex] = &[ Vertex { position: [-0.5, -0.5, 0.0], tex_coords: [0.0, 0.0], }, Vertex { position: [0.5, -0.5, 0.0], tex_coords: [2.0, 0.0], }, Vertex { position: [0.5, 0.5, 0.0], tex_coords: [2.0, 2.0], }, Vertex { position: [-0.5, 0.5, 0.0], tex_coords: [0.0, 2.0], }, ]; const INDICES: &[u16] = &[2, 1, 0, 3, 2, 0]; struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, swap_chain: wgpu::SwapChain, sc_desc: wgpu::SwapChainDescriptor, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer, num_indices: u32, diffuse_texture: wgpu::Texture, diffuse_texture_view: wgpu::TextureView, diffuse_sampler: wgpu::Sampler, diffuse_bind_group: wgpu::BindGroup, size: winit::dpi::PhysicalSize<u32>, } fn rgba_color(r: u32, g: u32, b: u32, a: u32) -> u32 { r | (g << 8) | (b << 16) | (a << 24) } impl State { fn new(window: &Window) -> Self { let size = window.inner_size(); let surface = wgpu::Surface::create(window); let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { ..Default::default() }) .unwrap(); let (device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: Default::default(), }); let (sc_desc, swap_chain) = Self::create_swap_chain(&device, size, &surface); let ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) = Self::create_texture_stuff(&device, &mut queue); let render_pipeline = Self::create_pipeline(&device, &sc_desc, &texture_bind_group_layout); let vertex_buffer = device .create_buffer_mapped(VERTICES.len(), wgpu::BufferUsage::VERTEX) .fill_from_slice(VERTICES); let index_buffer = device .create_buffer_mapped(INDICES.len(), wgpu::BufferUsage::INDEX) .fill_from_slice(INDICES); let num_indices = INDICES.len() as u32; Self { surface, device, queue, sc_desc, swap_chain, render_pipeline, vertex_buffer, index_buffer, num_indices, diffuse_texture, diffuse_texture_view, diffuse_sampler, diffuse_bind_group, size, } } fn create_pipeline( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, texture_bind_group_layout: &wgpu::BindGroupLayout, ) -> wgpu::RenderPipeline { let vs_src = include_str!("vert.glsl"); let fs_src = include_str!("frag.glsl"); let vs_spirv = glsl_to_spirv::compile(vs_src, glsl_to_spirv::ShaderType::Vertex).unwrap(); let fs_spirv = glsl_to_spirv::compile(fs_src, glsl_to_spirv::ShaderType::Fragment).unwrap(); let vs_data = wgpu::read_spirv(vs_spirv).unwrap(); let fs_data = wgpu::read_spirv(fs_spirv).unwrap(); let vs_module = device.create_shader_module(&vs_data); let fs_module = device.create_shader_module(&fs_data); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { bind_group_layouts: &[&texture_bind_group_layout], }); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { layout: &render_pipeline_layout, vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", }, fragment_stage: Some(wgpu::ProgrammableStageDescriptor { module: &fs_module, entry_point: "main", }), rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw,
depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { format: sc_desc.format, color_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::SrcAlpha, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, write_mask: wgpu::ColorWrite::ALL, }], depth_stencil_state: None, index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[Vertex::desc()], sample_count: 1, sample_mask:!0, alpha_to_coverage_enabled: false, }) } fn create_swap_chain( device: &wgpu::Device, size: PhysicalSize<u32>, surface: &wgpu::Surface, ) -> (wgpu::SwapChainDescriptor, wgpu::SwapChain) { let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Vsync, }; let swapchain = device.create_swap_chain(surface, &sc_desc); (sc_desc, swapchain) } fn create_texture_stuff( device: &wgpu::Device, queue: &mut wgpu::Queue, ) -> ( wgpu::Extent3d, wgpu::Texture, wgpu::Buffer, wgpu::Sampler, wgpu::TextureView, wgpu::BindGroup, wgpu::BindGroupLayout, ) { //let diffuse_bytes = include_bytes!("../happy-tree.png"); let font_bytes = include_bytes!("../ttf/JetBrainsMono-Regular.ttf"); let font = Font::from_bytes(font_bytes as &[u8]).expect("Failed to create font"); let glyph = font .glyph('c') .scaled(Scale { x: 50.0, y: 50.0 }) .positioned(point(10.0, 10.0)); let (gpos_x, gpos_y) = (glyph.position().x, glyph.position().y); let mut font_buffer = vec![]; for _ in 0..40_000 { font_buffer.push(rgba_color(255, 255, 255, 0)); } glyph.draw(|y, x, v| { font_buffer[((x + gpos_x as u32) * 200 + y + gpos_y as u32) as usize] = rgba_color(255, 0, 0, (v * 255.0) as u32); }); let dimensions = (200, 200); let size3d = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth: 1, }; let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor { size: size3d, array_layer_count: 1, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, }); let diffuse_buffer = device .create_buffer_mapped(font_buffer.len(), wgpu::BufferUsage::COPY_SRC) .fill_from_slice(&font_buffer); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); encoder.copy_buffer_to_texture( wgpu::BufferCopyView { buffer: &diffuse_buffer, offset: 0, row_pitch: 4 * dimensions.0, image_height: dimensions.1, }, wgpu::TextureCopyView { texture: &diffuse_texture, mip_level: 0, array_layer: 0, origin: wgpu::Origin3d::ZERO, }, size3d, ); queue.submit(&[encoder.finish()]); let diffuse_texture_view = diffuse_texture.create_default_view(); let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, lod_min_clamp: -100.0, lod_max_clamp: 100.0, compare_function: wgpu::CompareFunction::Always, }); let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[ wgpu::BindGroupLayoutBinding { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::SampledTexture { multisampled: false, dimension: wgpu::TextureViewDimension::D2, }, }, wgpu::BindGroupLayoutBinding { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler, }, ], }); let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &texture_bind_group_layout, bindings: &[ wgpu::Binding { binding: 0, resource: wgpu::BindingResource::TextureView(&diffuse_texture_view), }, wgpu::Binding { binding: 1, resource: wgpu::BindingResource::Sampler(&diffuse_sampler), }, ], }); ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) } fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } fn render(&mut self) { let frame = self.swap_chain.get_next_texture(); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }, }], depth_stencil_attachment: None, }); render_pass.set_pipeline(&self.render_pipeline); render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); render_pass.set_vertex_buffers(0, &[(&self.vertex_buffer, 0)]); render_pass.set_index_buffer(&self.index_buffer, 0); render_pass.draw_indexed(0..self.num_indices, 0, 0..1); } self.queue.submit(&[encoder.finish()]); } } fn main() { let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_inner_size(PhysicalSize::new(500, 500)) .build(&event_loop) .unwrap(); let mut state = State::new(&window); event_loop.run(move |event, _, control_flow| match event { Event::WindowEvent { ref event, window_id, } if window_id == window.id() => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::KeyboardInput { input,.. } => match input { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::Wait, }, WindowEvent::Resized(physical_size) => { state.resize(*physical_size); *control_flow = ControlFlow::Wait; } WindowEvent::ScaleFactorChanged { new_inner_size,.. } => { state.resize(**new_inner_size); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }, Event::MainEventsCleared => { state.render(); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }); }
cull_mode: wgpu::CullMode::Back,
random_line_split
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> wgpu::VertexBufferDescriptor<'a> { use std::mem; wgpu::VertexBufferDescriptor { stride: mem::size_of::<Vertex>() as wgpu::BufferAddress, step_mode: wgpu::InputStepMode::Vertex, attributes: &[ wgpu::VertexAttributeDescriptor { offset: 0, shader_location: 0, format: wgpu::VertexFormat::Float3, }, wgpu::VertexAttributeDescriptor { offset: mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, format: wgpu::VertexFormat::Float2, }, ], } } } const VERTICES: &[Vertex] = &[ Vertex { position: [-0.5, -0.5, 0.0], tex_coords: [0.0, 0.0], }, Vertex { position: [0.5, -0.5, 0.0], tex_coords: [2.0, 0.0], }, Vertex { position: [0.5, 0.5, 0.0], tex_coords: [2.0, 2.0], }, Vertex { position: [-0.5, 0.5, 0.0], tex_coords: [0.0, 2.0], }, ]; const INDICES: &[u16] = &[2, 1, 0, 3, 2, 0]; struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, swap_chain: wgpu::SwapChain, sc_desc: wgpu::SwapChainDescriptor, render_pipeline: wgpu::RenderPipeline, vertex_buffer: wgpu::Buffer, index_buffer: wgpu::Buffer, num_indices: u32, diffuse_texture: wgpu::Texture, diffuse_texture_view: wgpu::TextureView, diffuse_sampler: wgpu::Sampler, diffuse_bind_group: wgpu::BindGroup, size: winit::dpi::PhysicalSize<u32>, } fn rgba_color(r: u32, g: u32, b: u32, a: u32) -> u32 { r | (g << 8) | (b << 16) | (a << 24) } impl State { fn new(window: &Window) -> Self { let size = window.inner_size(); let surface = wgpu::Surface::create(window); let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { ..Default::default() }) .unwrap(); let (device, mut queue) = adapter.request_device(&wgpu::DeviceDescriptor { extensions: wgpu::Extensions { anisotropic_filtering: false, }, limits: Default::default(), }); let (sc_desc, swap_chain) = Self::create_swap_chain(&device, size, &surface); let ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) = Self::create_texture_stuff(&device, &mut queue); let render_pipeline = Self::create_pipeline(&device, &sc_desc, &texture_bind_group_layout); let vertex_buffer = device .create_buffer_mapped(VERTICES.len(), wgpu::BufferUsage::VERTEX) .fill_from_slice(VERTICES); let index_buffer = device .create_buffer_mapped(INDICES.len(), wgpu::BufferUsage::INDEX) .fill_from_slice(INDICES); let num_indices = INDICES.len() as u32; Self { surface, device, queue, sc_desc, swap_chain, render_pipeline, vertex_buffer, index_buffer, num_indices, diffuse_texture, diffuse_texture_view, diffuse_sampler, diffuse_bind_group, size, } } fn create_pipeline( device: &wgpu::Device, sc_desc: &wgpu::SwapChainDescriptor, texture_bind_group_layout: &wgpu::BindGroupLayout, ) -> wgpu::RenderPipeline { let vs_src = include_str!("vert.glsl"); let fs_src = include_str!("frag.glsl"); let vs_spirv = glsl_to_spirv::compile(vs_src, glsl_to_spirv::ShaderType::Vertex).unwrap(); let fs_spirv = glsl_to_spirv::compile(fs_src, glsl_to_spirv::ShaderType::Fragment).unwrap(); let vs_data = wgpu::read_spirv(vs_spirv).unwrap(); let fs_data = wgpu::read_spirv(fs_spirv).unwrap(); let vs_module = device.create_shader_module(&vs_data); let fs_module = device.create_shader_module(&fs_data); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { bind_group_layouts: &[&texture_bind_group_layout], }); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { layout: &render_pipeline_layout, vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", }, fragment_stage: Some(wgpu::ProgrammableStageDescriptor { module: &fs_module, entry_point: "main", }), rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw, cull_mode: wgpu::CullMode::Back, depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { format: sc_desc.format, color_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::SrcAlpha, dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, alpha_blend: wgpu::BlendDescriptor { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, write_mask: wgpu::ColorWrite::ALL, }], depth_stencil_state: None, index_format: wgpu::IndexFormat::Uint16, vertex_buffers: &[Vertex::desc()], sample_count: 1, sample_mask:!0, alpha_to_coverage_enabled: false, }) } fn create_swap_chain( device: &wgpu::Device, size: PhysicalSize<u32>, surface: &wgpu::Surface, ) -> (wgpu::SwapChainDescriptor, wgpu::SwapChain) { let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Vsync, }; let swapchain = device.create_swap_chain(surface, &sc_desc); (sc_desc, swapchain) } fn create_texture_stuff( device: &wgpu::Device, queue: &mut wgpu::Queue, ) -> ( wgpu::Extent3d, wgpu::Texture, wgpu::Buffer, wgpu::Sampler, wgpu::TextureView, wgpu::BindGroup, wgpu::BindGroupLayout, )
width: dimensions.0, height: dimensions.1, depth: 1, }; let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor { size: size3d, array_layer_count: 1, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8UnormSrgb, usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST, }); let diffuse_buffer = device .create_buffer_mapped(font_buffer.len(), wgpu::BufferUsage::COPY_SRC) .fill_from_slice(&font_buffer); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); encoder.copy_buffer_to_texture( wgpu::BufferCopyView { buffer: &diffuse_buffer, offset: 0, row_pitch: 4 * dimensions.0, image_height: dimensions.1, }, wgpu::TextureCopyView { texture: &diffuse_texture, mip_level: 0, array_layer: 0, origin: wgpu::Origin3d::ZERO, }, size3d, ); queue.submit(&[encoder.finish()]); let diffuse_texture_view = diffuse_texture.create_default_view(); let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Nearest, mipmap_filter: wgpu::FilterMode::Nearest, lod_min_clamp: -100.0, lod_max_clamp: 100.0, compare_function: wgpu::CompareFunction::Always, }); let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { bindings: &[ wgpu::BindGroupLayoutBinding { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::SampledTexture { multisampled: false, dimension: wgpu::TextureViewDimension::D2, }, }, wgpu::BindGroupLayoutBinding { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler, }, ], }); let diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &texture_bind_group_layout, bindings: &[ wgpu::Binding { binding: 0, resource: wgpu::BindingResource::TextureView(&diffuse_texture_view), }, wgpu::Binding { binding: 1, resource: wgpu::BindingResource::Sampler(&diffuse_sampler), }, ], }); ( size3d, diffuse_texture, diffuse_buffer, diffuse_sampler, diffuse_texture_view, diffuse_bind_group, texture_bind_group_layout, ) } fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } fn render(&mut self) { let frame = self.swap_chain.get_next_texture(); let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, load_op: wgpu::LoadOp::Clear, store_op: wgpu::StoreOp::Store, clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }, }], depth_stencil_attachment: None, }); render_pass.set_pipeline(&self.render_pipeline); render_pass.set_bind_group(0, &self.diffuse_bind_group, &[]); render_pass.set_vertex_buffers(0, &[(&self.vertex_buffer, 0)]); render_pass.set_index_buffer(&self.index_buffer, 0); render_pass.draw_indexed(0..self.num_indices, 0, 0..1); } self.queue.submit(&[encoder.finish()]); } } fn main() { let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_inner_size(PhysicalSize::new(500, 500)) .build(&event_loop) .unwrap(); let mut state = State::new(&window); event_loop.run(move |event, _, control_flow| match event { Event::WindowEvent { ref event, window_id, } if window_id == window.id() => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::KeyboardInput { input,.. } => match input { KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::Wait, }, WindowEvent::Resized(physical_size) => { state.resize(*physical_size); *control_flow = ControlFlow::Wait; } WindowEvent::ScaleFactorChanged { new_inner_size,.. } => { state.resize(**new_inner_size); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }, Event::MainEventsCleared => { state.render(); *control_flow = ControlFlow::Wait; } _ => *control_flow = ControlFlow::Wait, }); }
{ //let diffuse_bytes = include_bytes!("../happy-tree.png"); let font_bytes = include_bytes!("../ttf/JetBrainsMono-Regular.ttf"); let font = Font::from_bytes(font_bytes as &[u8]).expect("Failed to create font"); let glyph = font .glyph('c') .scaled(Scale { x: 50.0, y: 50.0 }) .positioned(point(10.0, 10.0)); let (gpos_x, gpos_y) = (glyph.position().x, glyph.position().y); let mut font_buffer = vec![]; for _ in 0..40_000 { font_buffer.push(rgba_color(255, 255, 255, 0)); } glyph.draw(|y, x, v| { font_buffer[((x + gpos_x as u32) * 200 + y + gpos_y as u32) as usize] = rgba_color(255, 0, 0, (v * 255.0) as u32); }); let dimensions = (200, 200); let size3d = wgpu::Extent3d {
identifier_body
main.rs
, right, top, bottom) = rg3d::core::futures::join!( resource_manager.request_texture("data/textures/skybox/front.jpg"), resource_manager.request_texture("data/textures/skybox/back.jpg"), resource_manager.request_texture("data/textures/skybox/left.jpg"), resource_manager.request_texture("data/textures/skybox/right.jpg"), resource_manager.request_texture("data/textures/skybox/up.jpg"), resource_manager.request_texture("data/textures/skybox/down.jpg") ); // Unwrap everything. let skybox = SkyBox { front: Some(front.unwrap()), back: Some(back.unwrap()), left: Some(left.unwrap()), right: Some(right.unwrap()), top: Some(top.unwrap()), bottom: Some(bottom.unwrap()), }; // Set S and T coordinate wrap mode, ClampToEdge will remove any possible seams on edges // of the skybox. for skybox_texture in skybox.textures().iter().filter_map(|t| t.clone()) { let mut data = skybox_texture.data_ref(); data.set_s_wrap_mode(TextureWrapMode::ClampToEdge); data.set_t_wrap_mode(TextureWrapMode::ClampToEdge); } skybox } fn create_bullet_impact( graph: &mut Graph, resource_manager: ResourceManager, pos: Vector3<f32>, orientation: UnitQuaternion<f32>, ) -> Handle<Node> { // Create sphere emitter first. let emitter = SphereEmitterBuilder::new( BaseEmitterBuilder::new() .with_max_particles(200) .with_spawn_rate(1000) .with_size_modifier_range(NumericRange::new(-0.01, -0.0125)) .with_size_range(NumericRange::new(0.0010, 0.025)) .with_x_velocity_range(NumericRange::new(-0.01, 0.01)) .with_y_velocity_range(NumericRange::new(0.017, 0.02)) .with_z_velocity_range(NumericRange::new(-0.01, 0.01)) .resurrect_particles(false), ) .with_radius(0.01) .build(); // Color gradient will be used to modify color of each particle over its lifetime. let color_gradient = { let mut gradient = ColorGradient::new(); gradient.add_point(GradientPoint::new(0.00, Color::from_rgba(255, 255, 0, 0))); gradient.add_point(GradientPoint::new(0.05, Color::from_rgba(255, 160, 0, 255))); gradient.add_point(GradientPoint::new(0.95, Color::from_rgba(255, 120, 0, 255))); gradient.add_point(GradientPoint::new(1.00, Color::from_rgba(255, 60, 0, 0))); gradient }; // Create new transform to orient and position particle system. let transform = TransformBuilder::new() .with_local_position(pos) .with_local_rotation(orientation) .build(); // Finally create particle system with limited lifetime. ParticleSystemBuilder::new( BaseBuilder::new() .with_lifetime(1.0) .with_local_transform(transform), ) .with_acceleration(Vector3::new(0.0, -10.0, 0.0)) .with_color_over_lifetime_gradient(color_gradient) .with_emitters(vec![emitter]) // We'll use simple spark texture for each particle. .with_texture(resource_manager.request_texture(Path::new("data/textures/spark.png"))) .build(graph) } impl Player { async fn new( scene: &mut Scene, resource_manager: ResourceManager, sender: Sender<Message>, ) -> Self { // Create a pivot and attach a camera to it, move it a bit up to "emulate" head. let camera; let weapon_pivot; let pivot = BaseBuilder::new() .with_children(&[{ camera = CameraBuilder::new( BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(0.0, 0.25, 0.0)) .build(), ) .with_children(&[{ weapon_pivot = BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(-0.1, -0.05, 0.015)) .build(), ) .build(&mut scene.graph); weapon_pivot }]), ) .with_skybox(create_skybox(resource_manager).await) .build(&mut scene.graph); camera }]) .build(&mut scene.graph); // Create rigid body, it will be used for interaction with the world. let rigid_body_handle = scene.physics.add_body( RigidBodyBuilder::new_dynamic() .lock_rotations() // We don't want the player to tilt. .translation(Vector3::new(0.0, 1.0, -1.0)) // Offset player a bit. .build(), ); // Add capsule collider for the rigid body. let collider = scene.physics.add_collider( ColliderBuilder::capsule_y(0.25, 0.2).build(), &rigid_body_handle, ); // Bind pivot with rigid body. Scene will automatically sync transform of the pivot // with the transform of the rigid body. scene.physics_binder.bind(pivot, rigid_body_handle); Self { pivot, camera, weapon_pivot, rigid_body: rigid_body_handle, controller: Default::default(), sender, collider, weapon: Default::default(), // Leave it unassigned for now. } } fn update(&mut self, scene: &mut Scene) { // Set pitch for the camera. These lines responsible for up-down camera rotation. scene.graph[self.camera].local_transform_mut().set_rotation( UnitQuaternion::from_axis_angle(&Vector3::x_axis(), self.controller.pitch.to_radians()), ); // Borrow the pivot in the graph. let pivot = &mut scene.graph[self.pivot]; // Borrow rigid body in the physics. let body = scene .physics .bodies .get_mut(&self.rigid_body) .unwrap(); // Keep only vertical velocity, and drop horizontal. let mut velocity = Vector3::new(0.0, body.linvel().y, 0.0); // Change the velocity depending on the keys pressed. if self.controller.move_forward { // If we moving forward then add "look" vector of the pivot. velocity += pivot.look_vector(); } if self.controller.move_backward { // If we moving backward then subtract "look" vector of the pivot. velocity -= pivot.look_vector(); } if self.controller.move_left { // If we moving left then add "side" vector of the pivot. velocity += pivot.side_vector(); } if self.controller.move_right { // If we moving right then subtract "side" vector of the pivot. velocity -= pivot.side_vector(); } // Finally new linear velocity. body.set_linvel(velocity, true); // Change the rotation of the rigid body according to current yaw. These lines responsible for // left-right rotation. let mut position = *body.position(); position.rotation = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), self.controller.yaw.to_radians()); body.set_position(position, true); if self.controller.shoot { self.sender .send(Message::ShootWeapon { weapon: self.weapon, }) .unwrap(); } } fn process_input_event(&mut self, event: &Event<()>) { match event { Event::WindowEvent { event,.. } => match event { WindowEvent::KeyboardInput { input,.. } => { if let Some(key_code) = input.virtual_keycode { match key_code { VirtualKeyCode::W => { self.controller.move_forward = input.state == ElementState::Pressed; } VirtualKeyCode::S => { self.controller.move_backward = input.state == ElementState::Pressed; } VirtualKeyCode::A => { self.controller.move_left = input.state == ElementState::Pressed; } VirtualKeyCode::D => { self.controller.move_right = input.state == ElementState::Pressed; } _ => (), } } } &WindowEvent::MouseInput { button, state,.. } => { if button == MouseButton::Left { self.controller.shoot = state == ElementState::Pressed; } } _ => {} }, Event::DeviceEvent { event,.. } => { if let DeviceEvent::MouseMotion { delta } = event { let mouse_sens = 0.5; self.controller.yaw -= mouse_sens * delta.0 as f32; self.controller.pitch = (self.controller.pitch + mouse_sens * delta.1 as f32).clamp(-90.0, 90.0); } } _ => (), } } } fn create_shot_trail( graph: &mut Graph, origin: Vector3<f32>, direction: Vector3<f32>, trail_length: f32, ) { let transform = TransformBuilder::new() .with_local_position(origin) // Scale the trail in XZ plane to make it thin, and apply `trail_length` scale on Y axis // to stretch is out. .with_local_scale(Vector3::new(0.0025, 0.0025, trail_length)) // Rotate the trail along given `direction` .with_local_rotation(UnitQuaternion::face_towards(&direction, &Vector3::y())) .build(); // Create unit cylinder with caps that faces toward Z axis. let shape = Arc::new(RwLock::new(SurfaceData::make_cylinder( 6, // Count of sides 1.0, // Radius 1.0, // Height false, // No caps are needed. // Rotate vertical cylinder around X axis to make it face towards Z axis &UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 90.0f32.to_radians()).to_homogeneous(), ))); MeshBuilder::new( BaseBuilder::new() .with_local_transform(transform) // Shot trail should live ~0.25 seconds, after that it will be automatically // destroyed. .with_lifetime(0.25), ) .with_surfaces(vec![SurfaceBuilder::new(shape) // Set yellow-ish color. .with_color(Color::from_rgba(255, 255, 0, 120)) .build()]) // Do not cast shadows. .with_cast_shadows(false) // Make sure to set Forward render path, otherwise the object won't be // transparent. .with_render_path(RenderPath::Forward) .build(graph); } struct Game { scene: Handle<Scene>, player: Player, weapons: Pool<Weapon>, receiver: Receiver<Message>, sender: Sender<Message>, } impl Game { pub async fn new(engine: &mut GameEngine) -> Self { // Make message queue. let (sender, receiver) = mpsc::channel(); let mut scene = Scene::new(); // Load a scene resource and create its instance. engine .resource_manager .request_model("data/models/scene.rgs") .await .unwrap() .instantiate_geometry(&mut scene); // Create player first. let mut player = Player::new(&mut scene, engine.resource_manager.clone(), sender.clone()).await; // Create weapon next. let weapon = Weapon::new(&mut scene, engine.resource_manager.clone()).await; // "Attach" the weapon to the weapon pivot of the player. scene.graph.link_nodes(weapon.model(), player.weapon_pivot); // Create a container for the weapons. let mut weapons = Pool::new(); // Put the weapon into it - this operation moves the weapon in the pool and returns handle. let weapon = weapons.spawn(weapon); // "Give" the weapon to the player. player.weapon = weapon; Self { player, scene: engine.scenes.add(scene), weapons, sender, receiver, } } fn shoot_weapon(&mut self, weapon: Handle<Weapon>, engine: &mut GameEngine) { let weapon = &mut self.weapons[weapon]; if weapon.can_shoot() { weapon.shoot(); let scene = &mut engine.scenes[self.scene]; let weapon_model = &scene.graph[weapon.model()]; // Make a ray that starts at the weapon's position in the world and look toward // "look" vector of the weapon. let ray = Ray::new( scene.graph[weapon.shot_point()].global_position(), weapon_model.look_vector().scale(1000.0), ); let mut intersections = Vec::new(); scene.physics.cast_ray( RayCastOptions { ray, max_len: ray.dir.norm(), groups: Default::default(), sort_results: true, // We need intersections to be sorted from closest to furthest. }, &mut intersections, ); // Ignore intersections with player's capsule. let trail_length = if let Some(intersection) = intersections .iter() .find(|i| i.collider!= self.player.collider) { // // TODO: Add code to handle intersections with bots. // // For now just apply some force at the point of impact. let collider = scene .physics .colliders .get(&intersection.collider) .unwrap(); scene .physics .bodies .native_mut(collider.parent().unwrap()) .unwrap() .apply_force_at_point( ray.dir.normalize().scale(10.0), intersection.position, true, ); // Add bullet impact effect. let effect_orientation = if intersection.normal.normalize() == Vector3::y() { // Handle singularity when normal of impact point is collinear with Y axis. UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.0) } else { UnitQuaternion::face_towards(&intersection.normal, &Vector3::y()) }; create_bullet_impact( &mut scene.graph, engine.resource_manager.clone(), intersection.position.coords, effect_orientation, ); // Trail length will be the length of line between intersection point and ray origin. (intersection.position.coords - ray.origin).norm() } else { // Otherwise trail length will be just the ray length. ray.dir.norm() }; create_shot_trail(&mut scene.graph, ray.origin, ray.dir, trail_length); } } pub fn update(&mut self, engine: &mut GameEngine, dt: f32) { let scene = &mut engine.scenes[self.scene]; self.player.update(scene); for weapon in self.weapons.iter_mut() { weapon.update(dt, &mut scene.graph); } // We're using `try_recv` here because we don't want to wait until next message - // if the queue is empty just continue to next frame. while let Ok(message) = self.receiver.try_recv() { match message { Message::ShootWeapon { weapon } => { self.shoot_weapon(weapon, engine); } } } } } fn main() { // Configure main window first. let window_builder = WindowBuilder::new().with_title("3D Shooter Tutorial"); // Create event loop that will be used to "listen" events from the OS. let event_loop = EventLoop::new(); // Finally create an instance of the engine. let mut engine = GameEngine::new(window_builder, &event_loop, true).unwrap(); // Initialize game instance. let mut game = rg3d::core::futures::executor::block_on(Game::new(&mut engine)); // Run the event loop of the main window. which will respond to OS and window events and update // engine's state accordingly. Engine lets you to decide which event should be handled, // this is minimal working example if how it should be.
let clock = time::Instant::now(); let mut elapsed_time = 0.0; event_loop.run(move |event, _, control_flow| {
random_line_split
main.rs
Node>; // Our game logic will be updated at 60 Hz rate. const TIMESTEP: f32 = 1.0 / 60.0; #[derive(Default)] struct InputController { move_forward: bool, move_backward: bool, move_left: bool, move_right: bool, pitch: f32, yaw: f32, shoot: bool, } struct Player { pivot: Handle<Node>, camera: Handle<Node>, rigid_body: RigidBodyHandle, controller: InputController, weapon_pivot: Handle<Node>, sender: Sender<Message>, weapon: Handle<Weapon>, collider: ColliderHandle, } async fn create_skybox(resource_manager: ResourceManager) -> SkyBox { // Load skybox textures in parallel. let (front, back, left, right, top, bottom) = rg3d::core::futures::join!( resource_manager.request_texture("data/textures/skybox/front.jpg"), resource_manager.request_texture("data/textures/skybox/back.jpg"), resource_manager.request_texture("data/textures/skybox/left.jpg"), resource_manager.request_texture("data/textures/skybox/right.jpg"), resource_manager.request_texture("data/textures/skybox/up.jpg"), resource_manager.request_texture("data/textures/skybox/down.jpg") ); // Unwrap everything. let skybox = SkyBox { front: Some(front.unwrap()), back: Some(back.unwrap()), left: Some(left.unwrap()), right: Some(right.unwrap()), top: Some(top.unwrap()), bottom: Some(bottom.unwrap()), }; // Set S and T coordinate wrap mode, ClampToEdge will remove any possible seams on edges // of the skybox. for skybox_texture in skybox.textures().iter().filter_map(|t| t.clone()) { let mut data = skybox_texture.data_ref(); data.set_s_wrap_mode(TextureWrapMode::ClampToEdge); data.set_t_wrap_mode(TextureWrapMode::ClampToEdge); } skybox } fn create_bullet_impact( graph: &mut Graph, resource_manager: ResourceManager, pos: Vector3<f32>, orientation: UnitQuaternion<f32>, ) -> Handle<Node> { // Create sphere emitter first. let emitter = SphereEmitterBuilder::new( BaseEmitterBuilder::new() .with_max_particles(200) .with_spawn_rate(1000) .with_size_modifier_range(NumericRange::new(-0.01, -0.0125)) .with_size_range(NumericRange::new(0.0010, 0.025)) .with_x_velocity_range(NumericRange::new(-0.01, 0.01)) .with_y_velocity_range(NumericRange::new(0.017, 0.02)) .with_z_velocity_range(NumericRange::new(-0.01, 0.01)) .resurrect_particles(false), ) .with_radius(0.01) .build(); // Color gradient will be used to modify color of each particle over its lifetime. let color_gradient = { let mut gradient = ColorGradient::new(); gradient.add_point(GradientPoint::new(0.00, Color::from_rgba(255, 255, 0, 0))); gradient.add_point(GradientPoint::new(0.05, Color::from_rgba(255, 160, 0, 255))); gradient.add_point(GradientPoint::new(0.95, Color::from_rgba(255, 120, 0, 255))); gradient.add_point(GradientPoint::new(1.00, Color::from_rgba(255, 60, 0, 0))); gradient }; // Create new transform to orient and position particle system. let transform = TransformBuilder::new() .with_local_position(pos) .with_local_rotation(orientation) .build(); // Finally create particle system with limited lifetime. ParticleSystemBuilder::new( BaseBuilder::new() .with_lifetime(1.0) .with_local_transform(transform), ) .with_acceleration(Vector3::new(0.0, -10.0, 0.0)) .with_color_over_lifetime_gradient(color_gradient) .with_emitters(vec![emitter]) // We'll use simple spark texture for each particle. .with_texture(resource_manager.request_texture(Path::new("data/textures/spark.png"))) .build(graph) } impl Player { async fn new( scene: &mut Scene, resource_manager: ResourceManager, sender: Sender<Message>, ) -> Self { // Create a pivot and attach a camera to it, move it a bit up to "emulate" head. let camera; let weapon_pivot; let pivot = BaseBuilder::new() .with_children(&[{ camera = CameraBuilder::new( BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(0.0, 0.25, 0.0)) .build(), ) .with_children(&[{ weapon_pivot = BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(-0.1, -0.05, 0.015)) .build(), ) .build(&mut scene.graph); weapon_pivot }]), ) .with_skybox(create_skybox(resource_manager).await) .build(&mut scene.graph); camera }]) .build(&mut scene.graph); // Create rigid body, it will be used for interaction with the world. let rigid_body_handle = scene.physics.add_body( RigidBodyBuilder::new_dynamic() .lock_rotations() // We don't want the player to tilt. .translation(Vector3::new(0.0, 1.0, -1.0)) // Offset player a bit. .build(), ); // Add capsule collider for the rigid body. let collider = scene.physics.add_collider( ColliderBuilder::capsule_y(0.25, 0.2).build(), &rigid_body_handle, ); // Bind pivot with rigid body. Scene will automatically sync transform of the pivot // with the transform of the rigid body. scene.physics_binder.bind(pivot, rigid_body_handle); Self { pivot, camera, weapon_pivot, rigid_body: rigid_body_handle, controller: Default::default(), sender, collider, weapon: Default::default(), // Leave it unassigned for now. } } fn update(&mut self, scene: &mut Scene) { // Set pitch for the camera. These lines responsible for up-down camera rotation. scene.graph[self.camera].local_transform_mut().set_rotation( UnitQuaternion::from_axis_angle(&Vector3::x_axis(), self.controller.pitch.to_radians()), ); // Borrow the pivot in the graph. let pivot = &mut scene.graph[self.pivot]; // Borrow rigid body in the physics. let body = scene .physics .bodies .get_mut(&self.rigid_body) .unwrap(); // Keep only vertical velocity, and drop horizontal. let mut velocity = Vector3::new(0.0, body.linvel().y, 0.0); // Change the velocity depending on the keys pressed. if self.controller.move_forward { // If we moving forward then add "look" vector of the pivot. velocity += pivot.look_vector(); } if self.controller.move_backward { // If we moving backward then subtract "look" vector of the pivot. velocity -= pivot.look_vector(); } if self.controller.move_left { // If we moving left then add "side" vector of the pivot. velocity += pivot.side_vector(); } if self.controller.move_right { // If we moving right then subtract "side" vector of the pivot. velocity -= pivot.side_vector(); } // Finally new linear velocity. body.set_linvel(velocity, true); // Change the rotation of the rigid body according to current yaw. These lines responsible for // left-right rotation. let mut position = *body.position(); position.rotation = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), self.controller.yaw.to_radians()); body.set_position(position, true); if self.controller.shoot { self.sender .send(Message::ShootWeapon { weapon: self.weapon, }) .unwrap(); } } fn process_input_event(&mut self, event: &Event<()>) { match event { Event::WindowEvent { event,.. } => match event { WindowEvent::KeyboardInput { input,.. } => { if let Some(key_code) = input.virtual_keycode { match key_code { VirtualKeyCode::W => { self.controller.move_forward = input.state == ElementState::Pressed; } VirtualKeyCode::S => { self.controller.move_backward = input.state == ElementState::Pressed; } VirtualKeyCode::A => { self.controller.move_left = input.state == ElementState::Pressed; } VirtualKeyCode::D => { self.controller.move_right = input.state == ElementState::Pressed; } _ => (), } } } &WindowEvent::MouseInput { button, state,.. } => { if button == MouseButton::Left { self.controller.shoot = state == ElementState::Pressed; } } _ => {} }, Event::DeviceEvent { event,.. } => { if let DeviceEvent::MouseMotion { delta } = event { let mouse_sens = 0.5; self.controller.yaw -= mouse_sens * delta.0 as f32; self.controller.pitch = (self.controller.pitch + mouse_sens * delta.1 as f32).clamp(-90.0, 90.0); } } _ => (), } } } fn create_shot_trail( graph: &mut Graph, origin: Vector3<f32>, direction: Vector3<f32>, trail_length: f32, ) { let transform = TransformBuilder::new() .with_local_position(origin) // Scale the trail in XZ plane to make it thin, and apply `trail_length` scale on Y axis // to stretch is out. .with_local_scale(Vector3::new(0.0025, 0.0025, trail_length)) // Rotate the trail along given `direction` .with_local_rotation(UnitQuaternion::face_towards(&direction, &Vector3::y())) .build(); // Create unit cylinder with caps that faces toward Z axis. let shape = Arc::new(RwLock::new(SurfaceData::make_cylinder( 6, // Count of sides 1.0, // Radius 1.0, // Height false, // No caps are needed. // Rotate vertical cylinder around X axis to make it face towards Z axis &UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 90.0f32.to_radians()).to_homogeneous(), ))); MeshBuilder::new( BaseBuilder::new() .with_local_transform(transform) // Shot trail should live ~0.25 seconds, after that it will be automatically // destroyed. .with_lifetime(0.25), ) .with_surfaces(vec![SurfaceBuilder::new(shape) // Set yellow-ish color. .with_color(Color::from_rgba(255, 255, 0, 120)) .build()]) // Do not cast shadows. .with_cast_shadows(false) // Make sure to set Forward render path, otherwise the object won't be // transparent. .with_render_path(RenderPath::Forward) .build(graph); } struct Game { scene: Handle<Scene>, player: Player, weapons: Pool<Weapon>, receiver: Receiver<Message>, sender: Sender<Message>, } impl Game { pub async fn new(engine: &mut GameEngine) -> Self { // Make message queue. let (sender, receiver) = mpsc::channel(); let mut scene = Scene::new(); // Load a scene resource and create its instance. engine .resource_manager .request_model("data/models/scene.rgs") .await .unwrap() .instantiate_geometry(&mut scene); // Create player first. let mut player = Player::new(&mut scene, engine.resource_manager.clone(), sender.clone()).await; // Create weapon next. let weapon = Weapon::new(&mut scene, engine.resource_manager.clone()).await; // "Attach" the weapon to the weapon pivot of the player. scene.graph.link_nodes(weapon.model(), player.weapon_pivot); // Create a container for the weapons. let mut weapons = Pool::new(); // Put the weapon into it - this operation moves the weapon in the pool and returns handle. let weapon = weapons.spawn(weapon); // "Give" the weapon to the player. player.weapon = weapon; Self { player, scene: engine.scenes.add(scene), weapons, sender, receiver, } } fn shoot_weapon(&mut self, weapon: Handle<Weapon>, engine: &mut GameEngine) { let weapon = &mut self.weapons[weapon]; if weapon.can_shoot() { weapon.shoot(); let scene = &mut engine.scenes[self.scene]; let weapon_model = &scene.graph[weapon.model()]; // Make a ray that starts at the weapon's position in the world and look toward // "look" vector of the weapon. let ray = Ray::new( scene.graph[weapon.shot_point()].global_position(), weapon_model.look_vector().scale(1000.0), ); let mut intersections = Vec::new(); scene.physics.cast_ray( RayCastOptions { ray, max_len: ray.dir.norm(), groups: Default::default(), sort_results: true, // We need intersections to be sorted from closest to furthest. }, &mut intersections, ); // Ignore intersections with player's capsule. let trail_length = if let Some(intersection) = intersections .iter() .find(|i| i.collider!= self.player.collider) { // // TODO: Add code to handle intersections with bots. // // For now just apply some force at the point of impact. let collider = scene .physics .colliders .get(&intersection.collider) .unwrap(); scene .physics .bodies .native_mut(collider.parent().unwrap()) .unwrap() .apply_force_at_point( ray.dir.normalize().scale(10.0), intersection.position, true, ); // Add bullet impact effect. let effect_orientation = if intersection.normal.normalize() == Vector3::y() { // Handle singularity when normal of impact point is collinear with Y axis. UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.0) } else { UnitQuaternion::face_towards(&intersection.normal, &Vector3::y()) }; create_bullet_impact( &mut scene.graph, engine.resource_manager.clone(), intersection.position.coords, effect_orientation, ); // Trail length will be the length of line between intersection point and ray origin. (intersection.position.coords - ray.origin).norm() } else { // Otherwise trail length will be just the ray length. ray.dir.norm() }; create_shot_trail(&mut scene.graph, ray.origin, ray.dir, trail_length); } } pub fn update(&mut self, engine: &mut GameEngine, dt: f32) { let scene = &mut engine.scenes[self.scene]; self.player.update(scene); for weapon in self.weapons.iter_mut() { weapon.update(dt, &mut scene.graph); } // We're using `try_recv` here because we don't want to wait until next message - // if the queue is empty just continue to next frame. while let Ok(message) = self.receiver.try_recv() { match message { Message::ShootWeapon { weapon } => { self.shoot_weapon(weapon, engine); } } } } } fn
() { // Configure main window first.
main
identifier_name
main.rs
Node>; // Our game logic will be updated at 60 Hz rate. const TIMESTEP: f32 = 1.0 / 60.0; #[derive(Default)] struct InputController { move_forward: bool, move_backward: bool, move_left: bool, move_right: bool, pitch: f32, yaw: f32, shoot: bool, } struct Player { pivot: Handle<Node>, camera: Handle<Node>, rigid_body: RigidBodyHandle, controller: InputController, weapon_pivot: Handle<Node>, sender: Sender<Message>, weapon: Handle<Weapon>, collider: ColliderHandle, } async fn create_skybox(resource_manager: ResourceManager) -> SkyBox { // Load skybox textures in parallel. let (front, back, left, right, top, bottom) = rg3d::core::futures::join!( resource_manager.request_texture("data/textures/skybox/front.jpg"), resource_manager.request_texture("data/textures/skybox/back.jpg"), resource_manager.request_texture("data/textures/skybox/left.jpg"), resource_manager.request_texture("data/textures/skybox/right.jpg"), resource_manager.request_texture("data/textures/skybox/up.jpg"), resource_manager.request_texture("data/textures/skybox/down.jpg") ); // Unwrap everything. let skybox = SkyBox { front: Some(front.unwrap()), back: Some(back.unwrap()), left: Some(left.unwrap()), right: Some(right.unwrap()), top: Some(top.unwrap()), bottom: Some(bottom.unwrap()), }; // Set S and T coordinate wrap mode, ClampToEdge will remove any possible seams on edges // of the skybox. for skybox_texture in skybox.textures().iter().filter_map(|t| t.clone()) { let mut data = skybox_texture.data_ref(); data.set_s_wrap_mode(TextureWrapMode::ClampToEdge); data.set_t_wrap_mode(TextureWrapMode::ClampToEdge); } skybox } fn create_bullet_impact( graph: &mut Graph, resource_manager: ResourceManager, pos: Vector3<f32>, orientation: UnitQuaternion<f32>, ) -> Handle<Node> { // Create sphere emitter first. let emitter = SphereEmitterBuilder::new( BaseEmitterBuilder::new() .with_max_particles(200) .with_spawn_rate(1000) .with_size_modifier_range(NumericRange::new(-0.01, -0.0125)) .with_size_range(NumericRange::new(0.0010, 0.025)) .with_x_velocity_range(NumericRange::new(-0.01, 0.01)) .with_y_velocity_range(NumericRange::new(0.017, 0.02)) .with_z_velocity_range(NumericRange::new(-0.01, 0.01)) .resurrect_particles(false), ) .with_radius(0.01) .build(); // Color gradient will be used to modify color of each particle over its lifetime. let color_gradient = { let mut gradient = ColorGradient::new(); gradient.add_point(GradientPoint::new(0.00, Color::from_rgba(255, 255, 0, 0))); gradient.add_point(GradientPoint::new(0.05, Color::from_rgba(255, 160, 0, 255))); gradient.add_point(GradientPoint::new(0.95, Color::from_rgba(255, 120, 0, 255))); gradient.add_point(GradientPoint::new(1.00, Color::from_rgba(255, 60, 0, 0))); gradient }; // Create new transform to orient and position particle system. let transform = TransformBuilder::new() .with_local_position(pos) .with_local_rotation(orientation) .build(); // Finally create particle system with limited lifetime. ParticleSystemBuilder::new( BaseBuilder::new() .with_lifetime(1.0) .with_local_transform(transform), ) .with_acceleration(Vector3::new(0.0, -10.0, 0.0)) .with_color_over_lifetime_gradient(color_gradient) .with_emitters(vec![emitter]) // We'll use simple spark texture for each particle. .with_texture(resource_manager.request_texture(Path::new("data/textures/spark.png"))) .build(graph) } impl Player { async fn new( scene: &mut Scene, resource_manager: ResourceManager, sender: Sender<Message>, ) -> Self
.build(&mut scene.graph); weapon_pivot }]), ) .with_skybox(create_skybox(resource_manager).await) .build(&mut scene.graph); camera }]) .build(&mut scene.graph); // Create rigid body, it will be used for interaction with the world. let rigid_body_handle = scene.physics.add_body( RigidBodyBuilder::new_dynamic() .lock_rotations() // We don't want the player to tilt. .translation(Vector3::new(0.0, 1.0, -1.0)) // Offset player a bit. .build(), ); // Add capsule collider for the rigid body. let collider = scene.physics.add_collider( ColliderBuilder::capsule_y(0.25, 0.2).build(), &rigid_body_handle, ); // Bind pivot with rigid body. Scene will automatically sync transform of the pivot // with the transform of the rigid body. scene.physics_binder.bind(pivot, rigid_body_handle); Self { pivot, camera, weapon_pivot, rigid_body: rigid_body_handle, controller: Default::default(), sender, collider, weapon: Default::default(), // Leave it unassigned for now. } } fn update(&mut self, scene: &mut Scene) { // Set pitch for the camera. These lines responsible for up-down camera rotation. scene.graph[self.camera].local_transform_mut().set_rotation( UnitQuaternion::from_axis_angle(&Vector3::x_axis(), self.controller.pitch.to_radians()), ); // Borrow the pivot in the graph. let pivot = &mut scene.graph[self.pivot]; // Borrow rigid body in the physics. let body = scene .physics .bodies .get_mut(&self.rigid_body) .unwrap(); // Keep only vertical velocity, and drop horizontal. let mut velocity = Vector3::new(0.0, body.linvel().y, 0.0); // Change the velocity depending on the keys pressed. if self.controller.move_forward { // If we moving forward then add "look" vector of the pivot. velocity += pivot.look_vector(); } if self.controller.move_backward { // If we moving backward then subtract "look" vector of the pivot. velocity -= pivot.look_vector(); } if self.controller.move_left { // If we moving left then add "side" vector of the pivot. velocity += pivot.side_vector(); } if self.controller.move_right { // If we moving right then subtract "side" vector of the pivot. velocity -= pivot.side_vector(); } // Finally new linear velocity. body.set_linvel(velocity, true); // Change the rotation of the rigid body according to current yaw. These lines responsible for // left-right rotation. let mut position = *body.position(); position.rotation = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), self.controller.yaw.to_radians()); body.set_position(position, true); if self.controller.shoot { self.sender .send(Message::ShootWeapon { weapon: self.weapon, }) .unwrap(); } } fn process_input_event(&mut self, event: &Event<()>) { match event { Event::WindowEvent { event,.. } => match event { WindowEvent::KeyboardInput { input,.. } => { if let Some(key_code) = input.virtual_keycode { match key_code { VirtualKeyCode::W => { self.controller.move_forward = input.state == ElementState::Pressed; } VirtualKeyCode::S => { self.controller.move_backward = input.state == ElementState::Pressed; } VirtualKeyCode::A => { self.controller.move_left = input.state == ElementState::Pressed; } VirtualKeyCode::D => { self.controller.move_right = input.state == ElementState::Pressed; } _ => (), } } } &WindowEvent::MouseInput { button, state,.. } => { if button == MouseButton::Left { self.controller.shoot = state == ElementState::Pressed; } } _ => {} }, Event::DeviceEvent { event,.. } => { if let DeviceEvent::MouseMotion { delta } = event { let mouse_sens = 0.5; self.controller.yaw -= mouse_sens * delta.0 as f32; self.controller.pitch = (self.controller.pitch + mouse_sens * delta.1 as f32).clamp(-90.0, 90.0); } } _ => (), } } } fn create_shot_trail( graph: &mut Graph, origin: Vector3<f32>, direction: Vector3<f32>, trail_length: f32, ) { let transform = TransformBuilder::new() .with_local_position(origin) // Scale the trail in XZ plane to make it thin, and apply `trail_length` scale on Y axis // to stretch is out. .with_local_scale(Vector3::new(0.0025, 0.0025, trail_length)) // Rotate the trail along given `direction` .with_local_rotation(UnitQuaternion::face_towards(&direction, &Vector3::y())) .build(); // Create unit cylinder with caps that faces toward Z axis. let shape = Arc::new(RwLock::new(SurfaceData::make_cylinder( 6, // Count of sides 1.0, // Radius 1.0, // Height false, // No caps are needed. // Rotate vertical cylinder around X axis to make it face towards Z axis &UnitQuaternion::from_axis_angle(&Vector3::x_axis(), 90.0f32.to_radians()).to_homogeneous(), ))); MeshBuilder::new( BaseBuilder::new() .with_local_transform(transform) // Shot trail should live ~0.25 seconds, after that it will be automatically // destroyed. .with_lifetime(0.25), ) .with_surfaces(vec![SurfaceBuilder::new(shape) // Set yellow-ish color. .with_color(Color::from_rgba(255, 255, 0, 120)) .build()]) // Do not cast shadows. .with_cast_shadows(false) // Make sure to set Forward render path, otherwise the object won't be // transparent. .with_render_path(RenderPath::Forward) .build(graph); } struct Game { scene: Handle<Scene>, player: Player, weapons: Pool<Weapon>, receiver: Receiver<Message>, sender: Sender<Message>, } impl Game { pub async fn new(engine: &mut GameEngine) -> Self { // Make message queue. let (sender, receiver) = mpsc::channel(); let mut scene = Scene::new(); // Load a scene resource and create its instance. engine .resource_manager .request_model("data/models/scene.rgs") .await .unwrap() .instantiate_geometry(&mut scene); // Create player first. let mut player = Player::new(&mut scene, engine.resource_manager.clone(), sender.clone()).await; // Create weapon next. let weapon = Weapon::new(&mut scene, engine.resource_manager.clone()).await; // "Attach" the weapon to the weapon pivot of the player. scene.graph.link_nodes(weapon.model(), player.weapon_pivot); // Create a container for the weapons. let mut weapons = Pool::new(); // Put the weapon into it - this operation moves the weapon in the pool and returns handle. let weapon = weapons.spawn(weapon); // "Give" the weapon to the player. player.weapon = weapon; Self { player, scene: engine.scenes.add(scene), weapons, sender, receiver, } } fn shoot_weapon(&mut self, weapon: Handle<Weapon>, engine: &mut GameEngine) { let weapon = &mut self.weapons[weapon]; if weapon.can_shoot() { weapon.shoot(); let scene = &mut engine.scenes[self.scene]; let weapon_model = &scene.graph[weapon.model()]; // Make a ray that starts at the weapon's position in the world and look toward // "look" vector of the weapon. let ray = Ray::new( scene.graph[weapon.shot_point()].global_position(), weapon_model.look_vector().scale(1000.0), ); let mut intersections = Vec::new(); scene.physics.cast_ray( RayCastOptions { ray, max_len: ray.dir.norm(), groups: Default::default(), sort_results: true, // We need intersections to be sorted from closest to furthest. }, &mut intersections, ); // Ignore intersections with player's capsule. let trail_length = if let Some(intersection) = intersections .iter() .find(|i| i.collider!= self.player.collider) { // // TODO: Add code to handle intersections with bots. // // For now just apply some force at the point of impact. let collider = scene .physics .colliders .get(&intersection.collider) .unwrap(); scene .physics .bodies .native_mut(collider.parent().unwrap()) .unwrap() .apply_force_at_point( ray.dir.normalize().scale(10.0), intersection.position, true, ); // Add bullet impact effect. let effect_orientation = if intersection.normal.normalize() == Vector3::y() { // Handle singularity when normal of impact point is collinear with Y axis. UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.0) } else { UnitQuaternion::face_towards(&intersection.normal, &Vector3::y()) }; create_bullet_impact( &mut scene.graph, engine.resource_manager.clone(), intersection.position.coords, effect_orientation, ); // Trail length will be the length of line between intersection point and ray origin. (intersection.position.coords - ray.origin).norm() } else { // Otherwise trail length will be just the ray length. ray.dir.norm() }; create_shot_trail(&mut scene.graph, ray.origin, ray.dir, trail_length); } } pub fn update(&mut self, engine: &mut GameEngine, dt: f32) { let scene = &mut engine.scenes[self.scene]; self.player.update(scene); for weapon in self.weapons.iter_mut() { weapon.update(dt, &mut scene.graph); } // We're using `try_recv` here because we don't want to wait until next message - // if the queue is empty just continue to next frame. while let Ok(message) = self.receiver.try_recv() { match message { Message::ShootWeapon { weapon } => { self.shoot_weapon(weapon, engine); } } } } } fn main() { // Configure main window first.
{ // Create a pivot and attach a camera to it, move it a bit up to "emulate" head. let camera; let weapon_pivot; let pivot = BaseBuilder::new() .with_children(&[{ camera = CameraBuilder::new( BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(0.0, 0.25, 0.0)) .build(), ) .with_children(&[{ weapon_pivot = BaseBuilder::new() .with_local_transform( TransformBuilder::new() .with_local_position(Vector3::new(-0.1, -0.05, 0.015)) .build(), )
identifier_body
lib.rs
#![deny( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, unused, missing_docs )] //! # luomu-libpcap //! //! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/). //! //! We are split in two different crates: //! //! * `luomu-libpcap-sys` for unsafe Rust bindings generated directly from //! `libpcap`. //! * `luomu-libpcap` for safe and sane libpcap interface. //! //! `luomu-libpcap` crate is split into two parts itself: //! //! * `functions` module contains safe wrappers and sane return values for //! libpcap functions. //! * the root of the project contains `Pcap` struct et al. for more Rusty API //! to interact with libpcap. //! //! You probably want to use the `Pcap` struct and other things from root of //! this crate. use std::collections::{BTreeSet, HashSet}; use std::convert::TryFrom; use std::default; use std::net::IpAddr; use std::ops::Deref; use std::path::Path; use std::result; use std::time::Duration; use luomu_common::{Address, MacAddr}; use luomu_libpcap_sys as libpcap; pub mod functions; use functions::*; mod error; pub use error::Error; mod packet; pub use packet::{BorrowedPacket, OwnedPacket, Packet}; #[cfg(feature = "async-tokio")] pub mod tokio; /// A `Result` wrapping luomu-libpcap's errors in `Err` side pub type Result<T> = result::Result<T, Error>; /// Keeper of the `libpcap`'s `pcap_t`. pub struct PcapT { pcap_t: *mut libpcap::pcap_t, #[allow(dead_code)] errbuf: Vec<u8>, interface: Option<String>, } // I assume the pcap_t pointer is safe to move between threads, but it can only // be used from one thread. libpcap documentation is vague about thread safety, // so we try this. unsafe impl Send for PcapT {} impl PcapT { /// get interface name /// /// `get_interface` returns the interface name if known or "<unknown>". pub fn get_inteface(&self) -> String { if let Some(name) = &self.interface { name.to_owned() } else { String::from("<unknown>") } } /// get libpcap error message text /// /// `get_error()` returns the error pertaining to the last pcap library error. /// /// This function can also fail, how awesome is that? The `Result` of /// `Ok(Error)` contains the error from libpcap as intended. `Err(Error)` /// contains the error happened while calling this function. pub fn get_error(&self) -> Result<Error> { get_error(self) } } impl Drop for PcapT { fn drop(&mut self) { log::trace!("PcapT::drop({:p})", self.pcap_t); unsafe { luomu_libpcap_sys::pcap_close(self.pcap_t) } } } /// Pcap capture /// /// This contains everything needed to capture the packets from network. /// /// To get started use `Pcap::builder()` to start a new Pcap capture builder. /// Use it to set required options for the capture and then call /// `PcapBuider::activate()` to activate the capture. /// /// Then `Pcap::capture()` can be used to start an iterator for capturing /// packets. pub struct Pcap { pcap_t: PcapT, } impl Pcap { /// Create a live capture handle /// /// This is used to create a packet capture handle to look at packets on the /// network. `source` is a string that specifies the network device to open. pub fn new(source: &str) -> Result<Pcap> { let pcap_t = pcap_create(source)?; Ok(Pcap { pcap_t }) } /// Create a capture handle for reading packets from given savefile. /// /// This function can be used to create handle to read packes from saved /// pcap -file. Use `capture()` to get iterator for packets in the file. pub fn offline<P: AsRef<Path>>(savefile: P) -> Result<Pcap> { Ok(Pcap { pcap_t: pcap_open_offline(savefile)?, }) } /// Use builder to create a live capture handle /// /// This is used to create a packet capture handle to look at packets on the /// network. source is a string that specifies the network device to open. pub fn builder(source: &str) -> Result<PcapBuilder> { let pcap_t = pcap_create(source)?; Ok(PcapBuilder { pcap_t }) } /// set a filter expression /// /// `Set a filter for capture. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn set_filter(&self, filter: &str) -> Result<()> { let mut bpf_program = PcapFilter::compile_with_pcap_t(&self.pcap_t, filter)?; pcap_setfilter(&self.pcap_t, &mut bpf_program) } /// Start capturing packets /// /// This returns an iterator `PcapIter` which can be used to get captured /// packets. pub fn capture(&self) -> PcapIter<'_> { PcapIter::new(&self.pcap_t) } /// Transmit a packet pub fn inject(&self, buf: &[u8]) -> Result<usize> { pcap_inject(&self.pcap_t, buf) } /// activate a capture /// /// This is used to activate a packet capture to look at packets on the /// network, with the options that were set on the handle being in effect. pub fn activate(&self) -> Result<()> { pcap_activate(&self.pcap_t) } /// get capture statistics /// /// Returns statistics from current capture. The values represent packet /// statistics from the start of the run to the time of the call. pub fn stats(&self) -> Result<PcapStat> { let mut stats: PcapStat = Default::default(); match pcap_stats(&self.pcap_t, &mut stats) { Ok(()) => Ok(stats), Err(e) => Err(e), } } } impl Deref for Pcap { type Target = PcapT; fn deref(&self) -> &Self::Target { &self.pcap_t } } /// Builder for a `Pcap`. Call `Pcap::builder()` to get started. pub struct PcapBuilder { pcap_t: PcapT, } impl PcapBuilder { /// set the buffer size for a capture /// /// `set_buffer_size()` sets the buffer size that will be used on a capture /// handle when the handle is activated to buffer_size, which is in units of /// bytes. pub fn set_buffer_size(self, buffer_size: usize) -> Result<PcapBuilder> { pcap_set_buffer_size(&self.pcap_t, buffer_size)?; Ok(self) } /// set promiscuous mode for a capture /// /// `set_promisc()` sets whether promiscuous mode should be set on a capture /// handle when the handle is activated. pub fn set_promiscuous(self, promiscuous: bool) -> Result<PcapBuilder> { pcap_set_promisc(&self.pcap_t, promiscuous)?; Ok(self) } /// set immediate mode for a capture /// /// `set_immediate_mode()` sets whether immediate mode should be set on a /// capture handle when the handle is activated. In immediate mode, packets /// are always delivered as soon as they arrive, with no buffering. pub fn set_immediate(self, immediate: bool) -> Result<PcapBuilder> { pcap_set_immediate_mode(&self.pcap_t, immediate)?; Ok(self) } /// set packet buffer timeout for a capture /// /// `pcap_set_timeout()` sets the packet buffer timeout that will be used on a /// capture handle when the handle is activated to to_ms, which is in units of /// milliseconds. pub fn set_timeout(self, to_ms: Duration) -> Result<PcapBuilder> { pcap_set_timeout( &self.pcap_t, (to_ms.as_millis().min(i32::MAX as u128)) as i32, )?; Ok(self) } /// set the snapshot length for a capture /// /// `set_snaplen()` sets the snapshot length to be used on a capture handle /// when the handle is activated to snaplen. /// /// `libpcap` says 65535 bytes should be enough for everyone. pub fn set_snaplen(self, snaplen: usize) -> Result<PcapBuilder> { pcap_set_snaplen(&self.pcap_t, snaplen)?; Ok(self) } /// activate a capture /// /// `activate()` is used to activate a packet capture to look at packets on /// the network, with the options that were set on the handle being in /// effect. pub fn activate(self) -> Result<Pcap> { pcap_activate(&self.pcap_t)?; Ok(Pcap { pcap_t: self.pcap_t, }) } } /// A BPF filter program for Pcap. pub struct PcapFilter { bpf_program: libpcap::bpf_program, } impl PcapFilter { /// compile a filter expression /// /// `compile()` is used to compile the filter into a filter program. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn compile(filter: &str) -> Result<PcapFilter> { let pcap = pcap_open_dead()?; pcap_compile(&pcap, filter) } /// compile a filter expression with `PcapT` /// /// `compile_with_pcap_t()` is used to compile the filter into a filter /// program. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn compile_with_pcap_t(pcap_t: &PcapT, filter_str: &str) -> Result<PcapFilter> { pcap_compile(pcap_t, filter_str) } /// Get length of the compiled filter pub fn get_raw_filter_len(&self) -> u32 { self.bpf_program.bf_len } /// Get pointer to the raw compiled filter program. /// Raw filter may be used when attaching filter to socket outside libpcap. /// # Safety /// Note that the pointer is valid only as long as this filter is valid. /// The returned pointer will be cast as *void since there is no common /// structure to which export the program. pub unsafe fn get_raw_filter(&self) -> &std::ffi::c_void { (self.bpf_program.bf_insns as *const std::ffi::c_void) .as_ref() .unwrap() } } impl Drop for PcapFilter { fn drop(&mut self) { log::trace!("PcapFilter::drop({:p})", &self.bpf_program); unsafe { luomu_libpcap_sys::pcap_freecode(&mut self.bpf_program) } } } /// Pcap capture iterator pub struct PcapIter<'p> { pcap_t: &'p PcapT, } impl<'p> PcapIter<'p> { fn new(pcap_t: &'p PcapT) -> Self { PcapIter { pcap_t } } } impl<'p> Iterator for PcapIter<'p> { type Item = BorrowedPacket; fn next(&mut self) -> Option<Self::Item> { loop { match pcap_next_ex(self.pcap_t) { Ok(p) => return Some(p), Err(e) => match e { // pcap_next_ex() sometimes seems to return // "packet buffer expired" (whatever that means), // even if the immediate mode is set. Just retry in // this case. Error::Timeout => continue, _ => return None, }, } } } } /// Pcap capture statistics pub struct PcapStat { stats: libpcap::pcap_stat, } impl default::Default for PcapStat { fn default() -> Self { PcapStat { stats: libpcap::pcap_stat { ps_recv: 0, ps_drop: 0, ps_ifdrop: 0, }, } } } impl PcapStat { /// Return number of packets received. pub fn
(&self) -> u32 { self.stats.ps_recv } /// Return number of packets dropped because there was no room in the /// operating system's buffer when they arrived, because packets weren't /// being read fast enough. pub fn packets_dropped(&self) -> u32 { self.stats.ps_drop } /// Return number of packets dropped by the network interface or its driver. pub fn packets_dropped_interface(&self) -> u32 { self.stats.ps_ifdrop } } /// Keeper of the `libpcap`'s `pcap_if_t`. pub struct PcapIfT { pcap_if_t: *mut libpcap::pcap_if_t, } impl PcapIfT { /// get a list of capture devices /// /// Constructs a list of network devices that can be opened with /// `Pcap::new()` and `Pcap::builder()`. Note that there may be network /// devices that cannot be opened by the process calling, because, for /// example, that process does not have sufficient privileges to open them /// for capturing; if so, those devices will not appear on the list. pub fn new() -> Result<Self> { pcap_findalldevs() } /// Return iterator for iterating capture devices. pub fn iter(&self) -> InterfaceIter { InterfaceIter { start: self.pcap_if_t, next: Some(self.pcap_if_t), } } /// Get all capture devices. pub fn get_interfaces(&self) -> HashSet<Interface> { self.iter().collect() } /// Find capture device with interface name `name`. pub fn find_interface_with_name(&self, name: &str) -> Option<Interface> { for interface in self.get_interfaces() { if interface.has_name(name) { log::trace!("find_interface_with_name({}) = {:?}", name, interface); return Some(interface); } } None } /// Find capture device which have IP address `ip`. pub fn find_interface_with_ip(&self, ip: &IpAddr) -> Option<String> { for interface in self.get_interfaces() { if interface.has_address(ip) { log::trace!("find_interface_with_ip({}) = {:?}", ip, interface); return Some(interface.name); } } None } } impl Drop for PcapIfT { fn drop(&mut self) { log::trace!("PcapIfT::drop({:?})", self.pcap_if_t); unsafe { luomu_libpcap_sys::pcap_freealldevs(self.pcap_if_t) } } } /// A network device that can be opened with `Pcap::new()` and /// `Pcap::builder()`. #[derive(Debug, PartialEq, Eq, Hash)] pub struct Interface { /// Devices name pub name: String, /// Devices description pub description: Option<String>, /// All addresses found from device pub addresses: BTreeSet<InterfaceAddress>, /// Flags set for device pub flags: BTreeSet<InterfaceFlag>, } impl Interface { /// True if interface is up pub fn is_up(&self) -> bool { self.flags.get(&InterfaceFlag::Up).is_some() } /// True if interface is running pub fn is_running(&self) -> bool { self.flags.get(&InterfaceFlag::Running).is_some() } /// True if interface is loopback pub fn is_loopback(&self) -> bool { self.flags.get(&InterfaceFlag::Loopback).is_some() } /// True if interface is has name `name` pub fn has_name(&self, name: &str) -> bool { self.name == name } /// Return MAC aka Ethernet address of the interface pub fn get_ether_address(&self) -> Option<MacAddr> { for ia in &self.addresses { if let Address::Mac(addr) = ia.addr { return Some(addr); } } None } /// Return IP addresses of interface pub fn get_ip_addresses(&self) -> HashSet<IpAddr> { self.addresses .iter() .filter_map(|i| IpAddr::try_from(&i.addr).ok()) .collect() } /// True if interface is has IP address `ip` pub fn has_address(&self, ip: &IpAddr) -> bool { self.get_ip_addresses().get(ip).is_some() } } /// Interface iterator /// /// Iterates all capture interfaces. pub struct InterfaceIter { // First item in linked list, only used for trace logging start: *mut libpcap::pcap_if_t, // Next item in linked list, used for iteration next: Option<*mut libpcap::pcap_if_t>, } impl Iterator for InterfaceIter { type Item = Interface; fn next(&mut self) -> Option<Interface> { log::trace!( "InterfaceIter(start: {:p}, next: {:p})", self.start, self.next.unwrap_or(std::ptr::null_mut()) ); let pcap_if_t = self.next?; if pcap_if_t.is_null() { self.next = None; return None; } let next = unsafe { (*pcap_if_t).next }; if next.is_null() { self.next = None; } else { self.next = Some(next); } match try_interface_from(pcap_if_t) { Ok(dev) => Some(dev), Err(err) => { log::error!("try_interface_from{:p}: {}", pcap_if_t, err); None } } } } /// Collection of addresses for network interface. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct InterfaceAddress { /// Network interface's address addr: Address, /// The netmask corresponding to the address pointed to by addr. netmask: Option<Address>, /// The broadcast address corresponding to the address pointed to by addr; /// may be `None` if the device doesn't support broadcasts. broadaddr: Option<Address>, /// The destination address corresponding to the address pointed to by addr; /// may be `None` if the device isn't a point-to-point interface. dstaddr: Option<Address>, } /// Iterator for network device's addresses. pub struct AddressIter { // First item in linked list, only used for trace logging start: *mut libpcap::pcap_addr_t, // Next item in linked list, used for iteration next: Option<*mut libpcap::pcap_addr_t>, } impl Iterator for AddressIter { type Item = InterfaceAddress; fn next(&mut self) -> Option<InterfaceAddress> { log::trace!( "AddressIter(start: {:p}, next: {:p})", self.start, self.next.unwrap_or(std::ptr::null_mut()) ); let pcap_addr_t = self.next?; if pcap_addr_t.is_null() { self.next = None; return None; } let next = unsafe { (*pcap_addr_t).next }; if next.is_null() { self.next = None; } else { self.next = Some(next); } if let Some(dev) = try_address_from(pcap_addr_t) { Some(dev) } else { // Address was something we don't know how to handle. Move // to next address in list. self.next() } } } /// Various flags which can be set on network interface #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum InterfaceFlag { /// set if the interface is a loopback interface Loopback, /// set if the interface is up Up, /// set if the interface is running Running, }
packets_received
identifier_name
lib.rs
#![deny( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, unused, missing_docs )] //! # luomu-libpcap //! //! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/). //! //! We are split in two different crates: //! //! * `luomu-libpcap-sys` for unsafe Rust bindings generated directly from //! `libpcap`. //! * `luomu-libpcap` for safe and sane libpcap interface. //! //! `luomu-libpcap` crate is split into two parts itself: //! //! * `functions` module contains safe wrappers and sane return values for //! libpcap functions. //! * the root of the project contains `Pcap` struct et al. for more Rusty API //! to interact with libpcap. //! //! You probably want to use the `Pcap` struct and other things from root of //! this crate. use std::collections::{BTreeSet, HashSet}; use std::convert::TryFrom; use std::default; use std::net::IpAddr; use std::ops::Deref; use std::path::Path; use std::result; use std::time::Duration; use luomu_common::{Address, MacAddr}; use luomu_libpcap_sys as libpcap; pub mod functions; use functions::*; mod error; pub use error::Error; mod packet; pub use packet::{BorrowedPacket, OwnedPacket, Packet}; #[cfg(feature = "async-tokio")] pub mod tokio; /// A `Result` wrapping luomu-libpcap's errors in `Err` side pub type Result<T> = result::Result<T, Error>; /// Keeper of the `libpcap`'s `pcap_t`. pub struct PcapT { pcap_t: *mut libpcap::pcap_t, #[allow(dead_code)] errbuf: Vec<u8>, interface: Option<String>, } // I assume the pcap_t pointer is safe to move between threads, but it can only // be used from one thread. libpcap documentation is vague about thread safety, // so we try this. unsafe impl Send for PcapT {} impl PcapT { /// get interface name /// /// `get_interface` returns the interface name if known or "<unknown>". pub fn get_inteface(&self) -> String { if let Some(name) = &self.interface { name.to_owned() } else { String::from("<unknown>") } } /// get libpcap error message text /// /// `get_error()` returns the error pertaining to the last pcap library error. /// /// This function can also fail, how awesome is that? The `Result` of /// `Ok(Error)` contains the error from libpcap as intended. `Err(Error)` /// contains the error happened while calling this function. pub fn get_error(&self) -> Result<Error> { get_error(self) } } impl Drop for PcapT { fn drop(&mut self) { log::trace!("PcapT::drop({:p})", self.pcap_t); unsafe { luomu_libpcap_sys::pcap_close(self.pcap_t) } } } /// Pcap capture /// /// This contains everything needed to capture the packets from network. /// /// To get started use `Pcap::builder()` to start a new Pcap capture builder. /// Use it to set required options for the capture and then call /// `PcapBuider::activate()` to activate the capture. /// /// Then `Pcap::capture()` can be used to start an iterator for capturing /// packets. pub struct Pcap { pcap_t: PcapT, } impl Pcap { /// Create a live capture handle /// /// This is used to create a packet capture handle to look at packets on the /// network. `source` is a string that specifies the network device to open. pub fn new(source: &str) -> Result<Pcap> { let pcap_t = pcap_create(source)?; Ok(Pcap { pcap_t }) } /// Create a capture handle for reading packets from given savefile. /// /// This function can be used to create handle to read packes from saved /// pcap -file. Use `capture()` to get iterator for packets in the file. pub fn offline<P: AsRef<Path>>(savefile: P) -> Result<Pcap> { Ok(Pcap { pcap_t: pcap_open_offline(savefile)?, }) } /// Use builder to create a live capture handle /// /// This is used to create a packet capture handle to look at packets on the /// network. source is a string that specifies the network device to open. pub fn builder(source: &str) -> Result<PcapBuilder> { let pcap_t = pcap_create(source)?; Ok(PcapBuilder { pcap_t }) } /// set a filter expression /// /// `Set a filter for capture. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn set_filter(&self, filter: &str) -> Result<()> { let mut bpf_program = PcapFilter::compile_with_pcap_t(&self.pcap_t, filter)?; pcap_setfilter(&self.pcap_t, &mut bpf_program) } /// Start capturing packets /// /// This returns an iterator `PcapIter` which can be used to get captured /// packets.
pub fn capture(&self) -> PcapIter<'_> { PcapIter::new(&self.pcap_t) } /// Transmit a packet pub fn inject(&self, buf: &[u8]) -> Result<usize> { pcap_inject(&self.pcap_t, buf) } /// activate a capture /// /// This is used to activate a packet capture to look at packets on the /// network, with the options that were set on the handle being in effect. pub fn activate(&self) -> Result<()> { pcap_activate(&self.pcap_t) } /// get capture statistics /// /// Returns statistics from current capture. The values represent packet /// statistics from the start of the run to the time of the call. pub fn stats(&self) -> Result<PcapStat> { let mut stats: PcapStat = Default::default(); match pcap_stats(&self.pcap_t, &mut stats) { Ok(()) => Ok(stats), Err(e) => Err(e), } } } impl Deref for Pcap { type Target = PcapT; fn deref(&self) -> &Self::Target { &self.pcap_t } } /// Builder for a `Pcap`. Call `Pcap::builder()` to get started. pub struct PcapBuilder { pcap_t: PcapT, } impl PcapBuilder { /// set the buffer size for a capture /// /// `set_buffer_size()` sets the buffer size that will be used on a capture /// handle when the handle is activated to buffer_size, which is in units of /// bytes. pub fn set_buffer_size(self, buffer_size: usize) -> Result<PcapBuilder> { pcap_set_buffer_size(&self.pcap_t, buffer_size)?; Ok(self) } /// set promiscuous mode for a capture /// /// `set_promisc()` sets whether promiscuous mode should be set on a capture /// handle when the handle is activated. pub fn set_promiscuous(self, promiscuous: bool) -> Result<PcapBuilder> { pcap_set_promisc(&self.pcap_t, promiscuous)?; Ok(self) } /// set immediate mode for a capture /// /// `set_immediate_mode()` sets whether immediate mode should be set on a /// capture handle when the handle is activated. In immediate mode, packets /// are always delivered as soon as they arrive, with no buffering. pub fn set_immediate(self, immediate: bool) -> Result<PcapBuilder> { pcap_set_immediate_mode(&self.pcap_t, immediate)?; Ok(self) } /// set packet buffer timeout for a capture /// /// `pcap_set_timeout()` sets the packet buffer timeout that will be used on a /// capture handle when the handle is activated to to_ms, which is in units of /// milliseconds. pub fn set_timeout(self, to_ms: Duration) -> Result<PcapBuilder> { pcap_set_timeout( &self.pcap_t, (to_ms.as_millis().min(i32::MAX as u128)) as i32, )?; Ok(self) } /// set the snapshot length for a capture /// /// `set_snaplen()` sets the snapshot length to be used on a capture handle /// when the handle is activated to snaplen. /// /// `libpcap` says 65535 bytes should be enough for everyone. pub fn set_snaplen(self, snaplen: usize) -> Result<PcapBuilder> { pcap_set_snaplen(&self.pcap_t, snaplen)?; Ok(self) } /// activate a capture /// /// `activate()` is used to activate a packet capture to look at packets on /// the network, with the options that were set on the handle being in /// effect. pub fn activate(self) -> Result<Pcap> { pcap_activate(&self.pcap_t)?; Ok(Pcap { pcap_t: self.pcap_t, }) } } /// A BPF filter program for Pcap. pub struct PcapFilter { bpf_program: libpcap::bpf_program, } impl PcapFilter { /// compile a filter expression /// /// `compile()` is used to compile the filter into a filter program. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn compile(filter: &str) -> Result<PcapFilter> { let pcap = pcap_open_dead()?; pcap_compile(&pcap, filter) } /// compile a filter expression with `PcapT` /// /// `compile_with_pcap_t()` is used to compile the filter into a filter /// program. See /// [pcap-filter(7)](https://www.tcpdump.org/manpages/pcap-filter.7.html) /// for the syntax of that string. pub fn compile_with_pcap_t(pcap_t: &PcapT, filter_str: &str) -> Result<PcapFilter> { pcap_compile(pcap_t, filter_str) } /// Get length of the compiled filter pub fn get_raw_filter_len(&self) -> u32 { self.bpf_program.bf_len } /// Get pointer to the raw compiled filter program. /// Raw filter may be used when attaching filter to socket outside libpcap. /// # Safety /// Note that the pointer is valid only as long as this filter is valid. /// The returned pointer will be cast as *void since there is no common /// structure to which export the program. pub unsafe fn get_raw_filter(&self) -> &std::ffi::c_void { (self.bpf_program.bf_insns as *const std::ffi::c_void) .as_ref() .unwrap() } } impl Drop for PcapFilter { fn drop(&mut self) { log::trace!("PcapFilter::drop({:p})", &self.bpf_program); unsafe { luomu_libpcap_sys::pcap_freecode(&mut self.bpf_program) } } } /// Pcap capture iterator pub struct PcapIter<'p> { pcap_t: &'p PcapT, } impl<'p> PcapIter<'p> { fn new(pcap_t: &'p PcapT) -> Self { PcapIter { pcap_t } } } impl<'p> Iterator for PcapIter<'p> { type Item = BorrowedPacket; fn next(&mut self) -> Option<Self::Item> { loop { match pcap_next_ex(self.pcap_t) { Ok(p) => return Some(p), Err(e) => match e { // pcap_next_ex() sometimes seems to return // "packet buffer expired" (whatever that means), // even if the immediate mode is set. Just retry in // this case. Error::Timeout => continue, _ => return None, }, } } } } /// Pcap capture statistics pub struct PcapStat { stats: libpcap::pcap_stat, } impl default::Default for PcapStat { fn default() -> Self { PcapStat { stats: libpcap::pcap_stat { ps_recv: 0, ps_drop: 0, ps_ifdrop: 0, }, } } } impl PcapStat { /// Return number of packets received. pub fn packets_received(&self) -> u32 { self.stats.ps_recv } /// Return number of packets dropped because there was no room in the /// operating system's buffer when they arrived, because packets weren't /// being read fast enough. pub fn packets_dropped(&self) -> u32 { self.stats.ps_drop } /// Return number of packets dropped by the network interface or its driver. pub fn packets_dropped_interface(&self) -> u32 { self.stats.ps_ifdrop } } /// Keeper of the `libpcap`'s `pcap_if_t`. pub struct PcapIfT { pcap_if_t: *mut libpcap::pcap_if_t, } impl PcapIfT { /// get a list of capture devices /// /// Constructs a list of network devices that can be opened with /// `Pcap::new()` and `Pcap::builder()`. Note that there may be network /// devices that cannot be opened by the process calling, because, for /// example, that process does not have sufficient privileges to open them /// for capturing; if so, those devices will not appear on the list. pub fn new() -> Result<Self> { pcap_findalldevs() } /// Return iterator for iterating capture devices. pub fn iter(&self) -> InterfaceIter { InterfaceIter { start: self.pcap_if_t, next: Some(self.pcap_if_t), } } /// Get all capture devices. pub fn get_interfaces(&self) -> HashSet<Interface> { self.iter().collect() } /// Find capture device with interface name `name`. pub fn find_interface_with_name(&self, name: &str) -> Option<Interface> { for interface in self.get_interfaces() { if interface.has_name(name) { log::trace!("find_interface_with_name({}) = {:?}", name, interface); return Some(interface); } } None } /// Find capture device which have IP address `ip`. pub fn find_interface_with_ip(&self, ip: &IpAddr) -> Option<String> { for interface in self.get_interfaces() { if interface.has_address(ip) { log::trace!("find_interface_with_ip({}) = {:?}", ip, interface); return Some(interface.name); } } None } } impl Drop for PcapIfT { fn drop(&mut self) { log::trace!("PcapIfT::drop({:?})", self.pcap_if_t); unsafe { luomu_libpcap_sys::pcap_freealldevs(self.pcap_if_t) } } } /// A network device that can be opened with `Pcap::new()` and /// `Pcap::builder()`. #[derive(Debug, PartialEq, Eq, Hash)] pub struct Interface { /// Devices name pub name: String, /// Devices description pub description: Option<String>, /// All addresses found from device pub addresses: BTreeSet<InterfaceAddress>, /// Flags set for device pub flags: BTreeSet<InterfaceFlag>, } impl Interface { /// True if interface is up pub fn is_up(&self) -> bool { self.flags.get(&InterfaceFlag::Up).is_some() } /// True if interface is running pub fn is_running(&self) -> bool { self.flags.get(&InterfaceFlag::Running).is_some() } /// True if interface is loopback pub fn is_loopback(&self) -> bool { self.flags.get(&InterfaceFlag::Loopback).is_some() } /// True if interface is has name `name` pub fn has_name(&self, name: &str) -> bool { self.name == name } /// Return MAC aka Ethernet address of the interface pub fn get_ether_address(&self) -> Option<MacAddr> { for ia in &self.addresses { if let Address::Mac(addr) = ia.addr { return Some(addr); } } None } /// Return IP addresses of interface pub fn get_ip_addresses(&self) -> HashSet<IpAddr> { self.addresses .iter() .filter_map(|i| IpAddr::try_from(&i.addr).ok()) .collect() } /// True if interface is has IP address `ip` pub fn has_address(&self, ip: &IpAddr) -> bool { self.get_ip_addresses().get(ip).is_some() } } /// Interface iterator /// /// Iterates all capture interfaces. pub struct InterfaceIter { // First item in linked list, only used for trace logging start: *mut libpcap::pcap_if_t, // Next item in linked list, used for iteration next: Option<*mut libpcap::pcap_if_t>, } impl Iterator for InterfaceIter { type Item = Interface; fn next(&mut self) -> Option<Interface> { log::trace!( "InterfaceIter(start: {:p}, next: {:p})", self.start, self.next.unwrap_or(std::ptr::null_mut()) ); let pcap_if_t = self.next?; if pcap_if_t.is_null() { self.next = None; return None; } let next = unsafe { (*pcap_if_t).next }; if next.is_null() { self.next = None; } else { self.next = Some(next); } match try_interface_from(pcap_if_t) { Ok(dev) => Some(dev), Err(err) => { log::error!("try_interface_from{:p}: {}", pcap_if_t, err); None } } } } /// Collection of addresses for network interface. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct InterfaceAddress { /// Network interface's address addr: Address, /// The netmask corresponding to the address pointed to by addr. netmask: Option<Address>, /// The broadcast address corresponding to the address pointed to by addr; /// may be `None` if the device doesn't support broadcasts. broadaddr: Option<Address>, /// The destination address corresponding to the address pointed to by addr; /// may be `None` if the device isn't a point-to-point interface. dstaddr: Option<Address>, } /// Iterator for network device's addresses. pub struct AddressIter { // First item in linked list, only used for trace logging start: *mut libpcap::pcap_addr_t, // Next item in linked list, used for iteration next: Option<*mut libpcap::pcap_addr_t>, } impl Iterator for AddressIter { type Item = InterfaceAddress; fn next(&mut self) -> Option<InterfaceAddress> { log::trace!( "AddressIter(start: {:p}, next: {:p})", self.start, self.next.unwrap_or(std::ptr::null_mut()) ); let pcap_addr_t = self.next?; if pcap_addr_t.is_null() { self.next = None; return None; } let next = unsafe { (*pcap_addr_t).next }; if next.is_null() { self.next = None; } else { self.next = Some(next); } if let Some(dev) = try_address_from(pcap_addr_t) { Some(dev) } else { // Address was something we don't know how to handle. Move // to next address in list. self.next() } } } /// Various flags which can be set on network interface #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum InterfaceFlag { /// set if the interface is a loopback interface Loopback, /// set if the interface is up Up, /// set if the interface is running Running, }
random_line_split
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Self::Stop, 5 => Self::Zombie, _ => Self::Unknown, } } } impl LocalProcessInfo { pub fn current_working_dir(pid: u32) -> Option<PathBuf> { let mut pathinfo: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() }; let size = std::mem::size_of_val(&pathinfo) as libc::c_int; let ret = unsafe { libc::proc_pidinfo( pid as _, libc::PROC_PIDVNODEPATHINFO, 0, &mut pathinfo as *mut _ as *mut _, size, ) }; if ret!= size { return None; } // Workaround a workaround for an old rustc version supported by libc; // the type of vip_path should just be [c_char; MAXPATHLEN] but it // is defined as a horrible nested array by the libc crate: // `[[c_char; 32]; 32]`. // Urgh. Let's re-cast it as the correct kind of slice. let vip_path = unsafe { std::slice::from_raw_parts( pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8, libc::MAXPATHLEN as usize, ) }; let nul = vip_path.iter().position(|&c| c == 0)?; Some(OsStr::from_bytes(&vip_path[0..nul]).into()) } pub fn executable_path(pid: u32) -> Option<PathBuf> { let mut buffer: Vec<u8> = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _); let x = unsafe { libc::proc_pidpath( pid as _, buffer.as_mut_ptr() as *mut _, libc::PROC_PIDPATHINFO_MAXSIZE as _, ) }; if x <= 0 { return None; } unsafe { buffer.set_len(x as usize) }; Some(OsString::from_vec(buffer).into()) } pub fn with_root_pid(pid: u32) -> Option<Self> { /// Enumerate all current process identifiers fn all_pids() -> Vec<libc::pid_t> { let num_pids = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; if num_pids < 1 { return vec![]; } // Give a bit of padding to avoid looping if processes are spawning // rapidly while we're trying to collect this info const PADDING: usize = 32; let mut pids: Vec<libc::pid_t> = Vec::with_capacity(num_pids as usize + PADDING); loop { let n = unsafe { libc::proc_listallpids( pids.as_mut_ptr() as *mut _, (pids.capacity() * std::mem::size_of::<libc::pid_t>()) as _, ) }; if n < 1 { return vec![]; } let n = n as usize; if n > pids.capacity() { pids.reserve(n + PADDING); continue; } unsafe { pids.set_len(n) }; return pids; } } /// Obtain info block for a pid. /// Note that the process could have gone away since we first /// observed the pid and the time we call this, so we must /// be able to tolerate this failing. fn info_for_pid(pid: libc::pid_t) -> Option<libc::proc_bsdinfo> { let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; let wanted_size = std::mem::size_of::<libc::proc_bsdinfo>() as _; let res = unsafe { libc::proc_pidinfo( pid, libc::PROC_PIDTBSDINFO, 0, &mut info as *mut _ as *mut _, wanted_size, ) }; if res == wanted_size { Some(info) } else { None } } fn cwd_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::current_working_dir(pid as _).unwrap_or_else(PathBuf::new) } fn exe_and_args_for_pid_sysctl(pid: libc::pid_t) -> Option<(PathBuf, Vec<String>)> { use libc::c_int; let mut size = 64 * 1024; let mut buf: Vec<u8> = Vec::with_capacity(size); let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; let res = unsafe { libc::sysctl( mib.as_mut_ptr(), mib.len() as _, buf.as_mut_ptr() as *mut _, &mut size, std::ptr::null_mut(), 0, ) }; if res == -1 { return None; } if size < (std::mem::size_of::<c_int>() * 2) { // Not big enough return None; } unsafe { buf.set_len(size) }; parse_exe_and_argv_sysctl(buf) } fn exe_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::executable_path(pid as _).unwrap_or_else(PathBuf::new) } let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bsdinfo]) -> LocalProcessInfo { let mut children = HashMap::new(); for kid in procs { if kid.pbi_ppid == info.pbi_pid { children.insert(kid.pbi_pid, build_proc(kid, procs)); } } let (executable, argv) = exe_and_args_for_pid_sysctl(info.pbi_pid as _) .unwrap_or_else(|| (exe_for_pid(info.pbi_pid as _), vec![])); let name = unsafe { std::ffi::CStr::from_ptr(info.pbi_comm.as_ptr() as _) }; let name = name.to_str().unwrap_or("").to_string(); LocalProcessInfo { pid: info.pbi_pid, ppid: info.pbi_ppid, name, executable, cwd: cwd_for_pid(info.pbi_pid as _), argv, start_time: info.pbi_start_tvsec, status: LocalProcessStatus::from(info.pbi_status), children, } } if let Some(info) = procs.iter().find(|info| info.pbi_pid == pid) { Some(build_proc(info, &procs)) } else { None } } } fn parse_exe_and_argv_sysctl(buf: Vec<u8>) -> Option<(PathBuf, Vec<String>)>
let nul = ptr.iter().position(|&c| c == 0)?; let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); *ptr = ptr.get(nul + 1..)?; // Find the position of the first non null byte. `.position()` // will return None if we run off the end. if let Some(not_nul) = ptr.iter().position(|&c| c!= 0) { // If there are no trailing nulls, not_nul will be 0 // and this call will be a noop *ptr = ptr.get(not_nul..)?; } Some(s) } let exe_path = consume_cstr(&mut ptr)?.into(); let mut args = vec![]; for _ in 0..argc { args.push(consume_cstr(&mut ptr)?); } Some((exe_path, args)) } #[cfg(test)] mod tests { use std::path::Path; use super::parse_exe_and_argv_sysctl; #[test] fn test_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 0, 0, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_no_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the trailing 0s between the exe_path and the argv let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_multiple_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add trailing 0s between argv items let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_trailing_zeros_at_end() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add zeroes to the end of the buffer let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, 0, 0, 0, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_malformed() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the last 0, making a malformed null-terminated string let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, ]; assert!(parse_exe_and_argv_sysctl(buf).is_none()); } }
{ use libc::c_int; // The data in our buffer is laid out like this: // argc - c_int // exe_path - NUL terminated string // argv[0] - NUL terminated string // argv[1] - NUL terminated string // ... // argv[n] - NUL terminated string // envp[0] - NUL terminated string // ... let mut ptr = &buf[0..buf.len()]; let argc: c_int = unsafe { std::ptr::read(ptr.as_ptr() as *const c_int) }; ptr = &ptr[std::mem::size_of::<c_int>()..]; fn consume_cstr(ptr: &mut &[u8]) -> Option<String> { // Parse to the end of a null terminated string
identifier_body
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Self::Stop, 5 => Self::Zombie, _ => Self::Unknown, } } } impl LocalProcessInfo { pub fn current_working_dir(pid: u32) -> Option<PathBuf> { let mut pathinfo: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() }; let size = std::mem::size_of_val(&pathinfo) as libc::c_int; let ret = unsafe { libc::proc_pidinfo( pid as _, libc::PROC_PIDVNODEPATHINFO, 0, &mut pathinfo as *mut _ as *mut _, size, ) }; if ret!= size { return None; } // Workaround a workaround for an old rustc version supported by libc; // the type of vip_path should just be [c_char; MAXPATHLEN] but it // is defined as a horrible nested array by the libc crate: // `[[c_char; 32]; 32]`. // Urgh. Let's re-cast it as the correct kind of slice. let vip_path = unsafe { std::slice::from_raw_parts( pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8, libc::MAXPATHLEN as usize, ) }; let nul = vip_path.iter().position(|&c| c == 0)?; Some(OsStr::from_bytes(&vip_path[0..nul]).into()) } pub fn executable_path(pid: u32) -> Option<PathBuf> { let mut buffer: Vec<u8> = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _); let x = unsafe { libc::proc_pidpath( pid as _, buffer.as_mut_ptr() as *mut _, libc::PROC_PIDPATHINFO_MAXSIZE as _, ) }; if x <= 0 { return None; } unsafe { buffer.set_len(x as usize) }; Some(OsString::from_vec(buffer).into()) } pub fn with_root_pid(pid: u32) -> Option<Self> { /// Enumerate all current process identifiers fn all_pids() -> Vec<libc::pid_t> { let num_pids = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; if num_pids < 1 { return vec![]; } // Give a bit of padding to avoid looping if processes are spawning // rapidly while we're trying to collect this info const PADDING: usize = 32; let mut pids: Vec<libc::pid_t> = Vec::with_capacity(num_pids as usize + PADDING); loop { let n = unsafe { libc::proc_listallpids( pids.as_mut_ptr() as *mut _, (pids.capacity() * std::mem::size_of::<libc::pid_t>()) as _, ) }; if n < 1 { return vec![]; } let n = n as usize; if n > pids.capacity() { pids.reserve(n + PADDING); continue; } unsafe { pids.set_len(n) }; return pids; } } /// Obtain info block for a pid. /// Note that the process could have gone away since we first /// observed the pid and the time we call this, so we must /// be able to tolerate this failing. fn info_for_pid(pid: libc::pid_t) -> Option<libc::proc_bsdinfo> { let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; let wanted_size = std::mem::size_of::<libc::proc_bsdinfo>() as _; let res = unsafe { libc::proc_pidinfo( pid, libc::PROC_PIDTBSDINFO, 0, &mut info as *mut _ as *mut _, wanted_size, ) }; if res == wanted_size { Some(info) } else { None } } fn cwd_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::current_working_dir(pid as _).unwrap_or_else(PathBuf::new) } fn exe_and_args_for_pid_sysctl(pid: libc::pid_t) -> Option<(PathBuf, Vec<String>)> { use libc::c_int; let mut size = 64 * 1024; let mut buf: Vec<u8> = Vec::with_capacity(size); let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; let res = unsafe { libc::sysctl( mib.as_mut_ptr(), mib.len() as _, buf.as_mut_ptr() as *mut _, &mut size, std::ptr::null_mut(), 0, ) }; if res == -1 { return None; } if size < (std::mem::size_of::<c_int>() * 2) { // Not big enough return None; } unsafe { buf.set_len(size) };
} fn exe_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::executable_path(pid as _).unwrap_or_else(PathBuf::new) } let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bsdinfo]) -> LocalProcessInfo { let mut children = HashMap::new(); for kid in procs { if kid.pbi_ppid == info.pbi_pid { children.insert(kid.pbi_pid, build_proc(kid, procs)); } } let (executable, argv) = exe_and_args_for_pid_sysctl(info.pbi_pid as _) .unwrap_or_else(|| (exe_for_pid(info.pbi_pid as _), vec![])); let name = unsafe { std::ffi::CStr::from_ptr(info.pbi_comm.as_ptr() as _) }; let name = name.to_str().unwrap_or("").to_string(); LocalProcessInfo { pid: info.pbi_pid, ppid: info.pbi_ppid, name, executable, cwd: cwd_for_pid(info.pbi_pid as _), argv, start_time: info.pbi_start_tvsec, status: LocalProcessStatus::from(info.pbi_status), children, } } if let Some(info) = procs.iter().find(|info| info.pbi_pid == pid) { Some(build_proc(info, &procs)) } else { None } } } fn parse_exe_and_argv_sysctl(buf: Vec<u8>) -> Option<(PathBuf, Vec<String>)> { use libc::c_int; // The data in our buffer is laid out like this: // argc - c_int // exe_path - NUL terminated string // argv[0] - NUL terminated string // argv[1] - NUL terminated string //... // argv[n] - NUL terminated string // envp[0] - NUL terminated string //... let mut ptr = &buf[0..buf.len()]; let argc: c_int = unsafe { std::ptr::read(ptr.as_ptr() as *const c_int) }; ptr = &ptr[std::mem::size_of::<c_int>()..]; fn consume_cstr(ptr: &mut &[u8]) -> Option<String> { // Parse to the end of a null terminated string let nul = ptr.iter().position(|&c| c == 0)?; let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); *ptr = ptr.get(nul + 1..)?; // Find the position of the first non null byte. `.position()` // will return None if we run off the end. if let Some(not_nul) = ptr.iter().position(|&c| c!= 0) { // If there are no trailing nulls, not_nul will be 0 // and this call will be a noop *ptr = ptr.get(not_nul..)?; } Some(s) } let exe_path = consume_cstr(&mut ptr)?.into(); let mut args = vec![]; for _ in 0..argc { args.push(consume_cstr(&mut ptr)?); } Some((exe_path, args)) } #[cfg(test)] mod tests { use std::path::Path; use super::parse_exe_and_argv_sysctl; #[test] fn test_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 0, 0, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_no_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the trailing 0s between the exe_path and the argv let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_multiple_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add trailing 0s between argv items let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_trailing_zeros_at_end() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add zeroes to the end of the buffer let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, 0, 0, 0, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_malformed() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the last 0, making a malformed null-terminated string let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, ]; assert!(parse_exe_and_argv_sysctl(buf).is_none()); } }
parse_exe_and_argv_sysctl(buf)
random_line_split
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Self::Stop, 5 => Self::Zombie, _ => Self::Unknown, } } } impl LocalProcessInfo { pub fn current_working_dir(pid: u32) -> Option<PathBuf> { let mut pathinfo: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() }; let size = std::mem::size_of_val(&pathinfo) as libc::c_int; let ret = unsafe { libc::proc_pidinfo( pid as _, libc::PROC_PIDVNODEPATHINFO, 0, &mut pathinfo as *mut _ as *mut _, size, ) }; if ret!= size { return None; } // Workaround a workaround for an old rustc version supported by libc; // the type of vip_path should just be [c_char; MAXPATHLEN] but it // is defined as a horrible nested array by the libc crate: // `[[c_char; 32]; 32]`. // Urgh. Let's re-cast it as the correct kind of slice. let vip_path = unsafe { std::slice::from_raw_parts( pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8, libc::MAXPATHLEN as usize, ) }; let nul = vip_path.iter().position(|&c| c == 0)?; Some(OsStr::from_bytes(&vip_path[0..nul]).into()) } pub fn executable_path(pid: u32) -> Option<PathBuf> { let mut buffer: Vec<u8> = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _); let x = unsafe { libc::proc_pidpath( pid as _, buffer.as_mut_ptr() as *mut _, libc::PROC_PIDPATHINFO_MAXSIZE as _, ) }; if x <= 0 { return None; } unsafe { buffer.set_len(x as usize) }; Some(OsString::from_vec(buffer).into()) } pub fn with_root_pid(pid: u32) -> Option<Self> { /// Enumerate all current process identifiers fn all_pids() -> Vec<libc::pid_t> { let num_pids = unsafe { libc::proc_listallpids(std::ptr::null_mut(), 0) }; if num_pids < 1 { return vec![]; } // Give a bit of padding to avoid looping if processes are spawning // rapidly while we're trying to collect this info const PADDING: usize = 32; let mut pids: Vec<libc::pid_t> = Vec::with_capacity(num_pids as usize + PADDING); loop { let n = unsafe { libc::proc_listallpids( pids.as_mut_ptr() as *mut _, (pids.capacity() * std::mem::size_of::<libc::pid_t>()) as _, ) }; if n < 1 { return vec![]; } let n = n as usize; if n > pids.capacity() { pids.reserve(n + PADDING); continue; } unsafe { pids.set_len(n) }; return pids; } } /// Obtain info block for a pid. /// Note that the process could have gone away since we first /// observed the pid and the time we call this, so we must /// be able to tolerate this failing. fn info_for_pid(pid: libc::pid_t) -> Option<libc::proc_bsdinfo> { let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; let wanted_size = std::mem::size_of::<libc::proc_bsdinfo>() as _; let res = unsafe { libc::proc_pidinfo( pid, libc::PROC_PIDTBSDINFO, 0, &mut info as *mut _ as *mut _, wanted_size, ) }; if res == wanted_size { Some(info) } else { None } } fn cwd_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::current_working_dir(pid as _).unwrap_or_else(PathBuf::new) } fn exe_and_args_for_pid_sysctl(pid: libc::pid_t) -> Option<(PathBuf, Vec<String>)> { use libc::c_int; let mut size = 64 * 1024; let mut buf: Vec<u8> = Vec::with_capacity(size); let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid as c_int]; let res = unsafe { libc::sysctl( mib.as_mut_ptr(), mib.len() as _, buf.as_mut_ptr() as *mut _, &mut size, std::ptr::null_mut(), 0, ) }; if res == -1 { return None; } if size < (std::mem::size_of::<c_int>() * 2) { // Not big enough return None; } unsafe { buf.set_len(size) }; parse_exe_and_argv_sysctl(buf) } fn exe_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::executable_path(pid as _).unwrap_or_else(PathBuf::new) } let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bsdinfo]) -> LocalProcessInfo { let mut children = HashMap::new(); for kid in procs { if kid.pbi_ppid == info.pbi_pid { children.insert(kid.pbi_pid, build_proc(kid, procs)); } } let (executable, argv) = exe_and_args_for_pid_sysctl(info.pbi_pid as _) .unwrap_or_else(|| (exe_for_pid(info.pbi_pid as _), vec![])); let name = unsafe { std::ffi::CStr::from_ptr(info.pbi_comm.as_ptr() as _) }; let name = name.to_str().unwrap_or("").to_string(); LocalProcessInfo { pid: info.pbi_pid, ppid: info.pbi_ppid, name, executable, cwd: cwd_for_pid(info.pbi_pid as _), argv, start_time: info.pbi_start_tvsec, status: LocalProcessStatus::from(info.pbi_status), children, } } if let Some(info) = procs.iter().find(|info| info.pbi_pid == pid) { Some(build_proc(info, &procs)) } else { None } } } fn parse_exe_and_argv_sysctl(buf: Vec<u8>) -> Option<(PathBuf, Vec<String>)> { use libc::c_int; // The data in our buffer is laid out like this: // argc - c_int // exe_path - NUL terminated string // argv[0] - NUL terminated string // argv[1] - NUL terminated string //... // argv[n] - NUL terminated string // envp[0] - NUL terminated string //... let mut ptr = &buf[0..buf.len()]; let argc: c_int = unsafe { std::ptr::read(ptr.as_ptr() as *const c_int) }; ptr = &ptr[std::mem::size_of::<c_int>()..]; fn
(ptr: &mut &[u8]) -> Option<String> { // Parse to the end of a null terminated string let nul = ptr.iter().position(|&c| c == 0)?; let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); *ptr = ptr.get(nul + 1..)?; // Find the position of the first non null byte. `.position()` // will return None if we run off the end. if let Some(not_nul) = ptr.iter().position(|&c| c!= 0) { // If there are no trailing nulls, not_nul will be 0 // and this call will be a noop *ptr = ptr.get(not_nul..)?; } Some(s) } let exe_path = consume_cstr(&mut ptr)?.into(); let mut args = vec![]; for _ in 0..argc { args.push(consume_cstr(&mut ptr)?); } Some((exe_path, args)) } #[cfg(test)] mod tests { use std::path::Path; use super::parse_exe_and_argv_sysctl; #[test] fn test_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 0, 0, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_no_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the trailing 0s between the exe_path and the argv let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 115, 108, 101, 101, 112, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_multiple_trailing_zeros() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add trailing 0s between argv items let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_trailing_zeros_at_end() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to add zeroes to the end of the buffer let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, 0, 0, 0, 0, 0, ]; let (exe_path, argv) = parse_exe_and_argv_sysctl(buf).unwrap(); assert_eq!(exe_path, Path::new("/bin/sleep").to_path_buf()); assert_eq!(argv, vec!["sleep".to_string(), "5".to_string()]); } #[test] fn test_malformed() { // Example data generated from running'sleep 5' on the commit author's local machine, // then modified to remove the last 0, making a malformed null-terminated string let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 101, 112, 0, 0, 0, 115, 108, 101, 101, 112, 0, 0, 0, 53, ]; assert!(parse_exe_and_argv_sysctl(buf).is_none()); } }
consume_cstr
identifier_name
wallet.rs
store persistent state. fn persistent_state_address( network: NetworkId, master_xpriv: &bip32::ExtendedPrivKey, ) -> String { let child = bip32::ChildNumber::from_hardened_idx(350).unwrap(); let child_xpriv = master_xpriv.derive_priv(&SECP, &[child]).unwrap(); let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); match network { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => elements::Address::p2wpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ) .to_string(), NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), } } /// Store the persistent wallet state. fn save_persistent_state(&self) -> Result<(), Error> { let state = PersistentWalletState { next_external_child: self.next_external_child.get(), next_internal_child: self.next_internal_child.get(), }; let store_addr = Wallet::persistent_state_address(self.network.id(), &self.master_xpriv); // Generic call for liquid compat. self.rpc.call("setlabel", &[store_addr.into(), serde_json::to_string(&state)?.into()])?; Ok(()) } /// Load the persistent wallet state from the node. #[allow(clippy::match_wild_err_arm)] fn load_persistent_state( rpc: &bitcoincore_rpc::Client, state_addr: &str, ) -> Result<PersistentWalletState, Error> { let info: Value = rpc.call("getaddressinfo", &[state_addr.into()])?; match info.get("label") { None => Err(Error::WalletNotRegistered), Some(&Value::String(ref label)) => { Ok(match serde_json::from_str::<PersistentWalletState>(label) { Err(_) => panic!( "corrupt persistent wallet state label (address: {}): {}", state_addr, label ), Ok(s) => s, }) } Some(_) => unreachable!(), } } /// Calculates the bip32 seeds from the mnemonic phrase. /// In order are returned: /// - the master xpriv /// - the external address xpriv /// - the internal address xpriv fn calc_xkeys( seed: &[u8], ) -> (bip32::ExtendedPrivKey, bip32::ExtendedPrivKey, bip32::ExtendedPrivKey) { // Network isn't of importance here. let master_xpriv = bip32::ExtendedPrivKey::new_master(BNetwork::Bitcoin, &seed[..]).unwrap(); // Add BIP-44 derivations for external and internal addresses. let external_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/0").unwrap()) .unwrap(); let internal_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/1").unwrap()) .unwrap(); (master_xpriv, external_xpriv, internal_xpriv) } /// Register a new [Wallet]. pub fn register(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); // create the wallet in Core let tmp_rpc = network.connect(None)?; match tmp_rpc.create_wallet(fp.as_str(), Some(true))?.warning { None => {} Some(ref s) if s.is_empty() => {} Some(warning) => { warn!("Received warning when creating wallet {} in Core: {}", fp, warning,) } } let rpc = network.connect(Some(&fp))?; // Check if the user was already registered. let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); match Wallet::load_persistent_state(&rpc, &state_addr) { Err(Error::WalletNotRegistered) => {} // good Ok(_) => return Err(Error::WalletAlreadyRegistered), Err(e) => { warn!("Unexpected error while registering wallet: {}", e); return Err(e); } } let wallet = Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), next_internal_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }; wallet.save_persistent_state()?; Ok(wallet) } /// Login to an existing [Wallet]. pub fn login(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); let tmp_rpc = network.connect(None)?; tmp_rpc.load_wallet(&fp)?; let rpc = network.connect(Some(&fp))?; let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); let state = Wallet::load_persistent_state(&rpc, &state_addr)?; Ok(Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(state.next_external_child), next_internal_child: cell::Cell::new(state.next_internal_child), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }) } pub fn fingerprint(&self) -> bip32::Fingerprint { self.master_xpriv.fingerprint(&SECP) } pub fn logout(self) -> Result<(), Error> { self.rpc.unload_wallet(None)?; Ok(()) } pub fn mnemonic(&self) -> String { self.mnemonic.clone() } fn derive_private_key( &self, fp: bip32::Fingerprint, child: bip32::ChildNumber, ) -> Result<secp256k1::SecretKey, Error> { let xpriv = if fp == self.external_xpriv.fingerprint(&SECP) {
error!("Address is labeled with unknown master xpriv fingerprint: {:?}", fp); return Err(Error::CorruptNodeData); }; let privkey = xpriv.derive_priv(&SECP, &[child])?.private_key; Ok(privkey.key) } pub fn updates(&mut self) -> Result<Vec<Value>, Error> { let mut msgs = vec![]; // check for new blocks let tip = self.rpc.get_best_block_hash()?; if self.tip!= Some(tip) { let info: Value = self.rpc.call("getblock", &[tip.to_hex().into(), 1.into()])?; msgs.push(json!({ "event": "block", "block": { "block_height": info["height"].as_u64().req()?, "block_hash": tip.to_hex() } })); self.tip = Some(tip); } // check for new transactions // XXX does the app care about the transaction data in the event? if let Some(last_tx) = self._get_transactions(1, 0)?.0.get(0) { let txid = last_tx["txhash"].as_str().req()?; let txid = sha256d::Hash::from_hex(txid)?; if self.last_tx!= Some(txid) { self.last_tx = Some(txid); msgs.push(json!({ "event": "transaction", "transaction": last_tx })); } } // update fees once every FEE_ESTIMATES_TTL if self.cached_fees.1.elapsed() >= FEE_ESTIMATES_TTL { self.cached_fees = (self._make_fee_estimates()?, Instant::now()); msgs.push(json!({ "event": "fees", "fees": self.cached_fees.0 })); } // TODO: // {"event":"subaccount","subaccount":{"bits":"701144.66","btc":"0.70114466","fiat":"0.7712591260000000622741556099981585311432","fiat_currency":"EUR","fiat_rate":"1.10000000000000008881784197001252","has_transactions":true,"mbtc":"701.14466","name":"","pointer":0,"receiving_id":"GA3MQKVp6pP7royXDuZcw55F2TXTgg","recovery_chain_code":"","recovery_pub_key":"","satoshi":70114466,"type":"2of2","ubtc":"701144.66"}} // XXX use zmq? Ok(msgs) } pub fn get_account(&self) -> Result<Value, Error> { let has_transactions = self._get_transactions(1, 0)?.1; extend( json!({ "type": "core", "pointer": 0, "receiving_id": "", "name": "RPC wallet", "has_transactions": has_transactions, }), self._get_balance(0)?, ) } pub fn get_balance(&self, details: &Value) -> Result<Value, Error> { let min_conf = details["num_confs"].as_u64().req()? as u32; self._get_balance(min_conf) } fn _get_balance(&self, min_conf: u32) -> Result<Value, Error> { //TODO(stevenroose) implement in rust-bitcoincore-rpc once bitcoin::Amount lands let mut args = vec![Value::Null, json!(min_conf), json!(true)]; #[cfg(feature = "liquid")] { if let NetworkId::Elements(net) = self.network.id() { args.push(coins::liq::asset_hex(net).into()); } } let balance: f64 = self.rpc.call("getbalance", &args)?; Ok(self._convert_satoshi(btc_to_usat(balance))) } pub fn get_transactions(&self, details: &Value) -> Result<Value, Error> { let page = details["page_id"].as_u64().req()? as usize; let (txs, potentially_has_more) = self._get_transactions(PER_PAGE, PER_PAGE * page)?; Ok(json!({ "list": txs, "page_id": page, "next_page_id": if potentially_has_more { Some(page+1) } else { None }, })) } fn _get_transactions(&self, limit: usize, start: usize) -> Result<(Vec<Value>, bool), Error> { // fetch listtranssactions let txdescs: Vec<Value> = self .rpc .call("listtransactions", &["*".into(), limit.into(), start.into(), true.into()])?; let potentially_has_more = txdescs.len() == limit; // fetch full transactions and convert to GDK format let mut txs = Vec::new(); for desc in txdescs.into_iter() { let txid = sha256d::Hash::from_hex(desc["txid"].as_str().req()?)?; let blockhash = &desc["blockhash"]; let tx_hex: String = self.rpc.call( "getrawtransaction", &[txid.to_hex().into(), false.into(), blockhash.clone()], )?; txs.push(format_gdk_tx(&desc, &hex::decode(&tx_hex)?, self.network.id())?); } Ok((txs, potentially_has_more)) } pub fn get_transaction(&self, txid: &str) -> Result<Value, Error> { let txid = sha256d::Hash::from_hex(txid)?; let desc: Value = self.rpc.call("gettransaction", &[txid.to_hex().into(), true.into()])?; let raw_tx = hex::decode(desc["hex"].as_str().req()?)?; format_gdk_tx(&desc, &raw_tx, self.network.id()) } pub fn create_transaction(&self, details: &Value) -> Result<String, Error> { debug!("create_transaction(): {:?}", details); let unfunded_tx = match self.network.id() { NetworkId::Bitcoin(..) => coins::btc::create_transaction(&self.rpc, details)?, NetworkId::Elements(..) => coins::liq::create_transaction(&self.rpc, details)?, }; debug!("create_transaction unfunded tx: {:?}", hex::encode(&unfunded_tx)); // TODO explicit handling for id_no_amount_specified id_fee_rate_is_below_minimum id_invalid_replacement_fee_rate // id_send_all_requires_a_single_output Ok(hex::encode(unfunded_tx)) } pub fn sign_transaction(&self, details: &Value) -> Result<String, Error> { debug!("sign_transaction(): {:?}", details); let change_address = self.next_address(&self.internal_xpriv, &self.next_internal_child)?; // If we don't have any inputs, we can fail early. let unspent: Vec<Value> = self.rpc.call("listunspent", &[0.into()])?; if unspent.is_empty() { return Err(Error::NoUtxosFound); } debug!("list_unspent: {:?}", unspent); let raw_tx = match self.network.id() { NetworkId::Bitcoin(_) => { coins::btc::sign_transaction(&self.rpc, details, &change_address, |fp, child| { self.derive_private_key(*fp, *child) })? } NetworkId::Elements(net) => coins::liq::sign_transaction( &self.rpc, net, details, &change_address, |fp, child| self.derive_private_key(*fp, *child), )?, }; let hex_tx = hex::encode(&raw_tx); //TODO(stevenroose) remove when confident in signing code let ret: Vec<Value> = self.rpc.call("testmempoolaccept", &[vec![hex_tx.clone()].into()])?; let accept = ret.into_iter().next().unwrap(); if!(accept["allowed"].as_bool().req()?) { error!( "sign_transaction(): signed tx is not valid: {}", accept["reject-reason"].as_str().req()? ); // TODO(stevenroose) should we return an error?? } Ok(hex_tx) } pub fn send_transaction(&self, details: &Value) -> Result<String, Error> { let tx_hex = details["hex"].as_str().req()?; Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } pub fn send_raw_transaction(&self, tx_hex: &str) -> Result<String, Error> { Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } /// Return the next address for the derivation and import it in Core. fn next_address( &self, xpriv: &bip32::ExtendedPrivKey, child: &cell::Cell<bip32::ChildNumber>, ) -> Result<String, Error> { let child_xpriv = xpriv.derive_priv(&SECP, &[child.get()])?; let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); let meta = AddressMeta { fingerprint: Some(xpriv.fingerprint(&SECP)), child: Some(child.get()), ..Default::default() }; let address_str = match self.network.id() { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => { let mut addr = elements::Address::p2shwpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ); let blinding_key = wally::asset_blinding_key_to_ec_private_key( &self.master_blinding_key, &addr.script_pubkey(), ); let blinding_pubkey = secp256k1::PublicKey::from_secret_key(&SECP, &blinding_key); addr.blinding_pubkey = Some(blinding_pubkey); // Store blinding privkey in the node. let addr_str = addr.to_string(); coins::liq::store_blinding_key(&self.rpc, &addr_str, &blinding_key)?; addr_str } NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), }; // Since this is a newly generated address, rescanning is not required. self.rpc.import_public_key(&child_xpub.public_key, Some(&meta.to_label()?), Some(false))?; child.set(match child.get() { bip32::ChildNumber::Normal { index, } => bip32::ChildNumber::from_normal_idx(index + 1)?, _ => unreachable!(), }); self.save_persistent_state()?; Ok(address_str) } pub fn get_receive_address(&self, _details: &Value) -> Result<Value, Error> { let address = self.next_address(&self.external_xpriv, &self.next_external_child)?; // { // "address": "2N2x4EgizS2w3DUiWYWW9pEf4sGYRfo6PAX", // "address_type": "p2wsh", // "branch": 1, // "pointer": 13, // "script": "52210338832debc5e15ce143d5cf9241147ac0019e7516d3d9569e04b0e18f3278718921025dfaa85d64963252604e1b139b40182bb859a9e2e1aa2904876c34e82158d85452ae", // "script_type": 14, // "subtype": null // } Ok(json!({ "address": address, "address_type": "p2wpkh", })) } pub fn get_fee_estimates(&self) -> Option<&Value> { // will not be available before the first "tick", which should
self.external_xpriv } else if fp == self.internal_xpriv.fingerprint(&SECP) { self.internal_xpriv } else {
random_line_split
wallet.rs
]).unwrap(); let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); match network { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => elements::Address::p2wpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ) .to_string(), NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), } } /// Store the persistent wallet state. fn save_persistent_state(&self) -> Result<(), Error> { let state = PersistentWalletState { next_external_child: self.next_external_child.get(), next_internal_child: self.next_internal_child.get(), }; let store_addr = Wallet::persistent_state_address(self.network.id(), &self.master_xpriv); // Generic call for liquid compat. self.rpc.call("setlabel", &[store_addr.into(), serde_json::to_string(&state)?.into()])?; Ok(()) } /// Load the persistent wallet state from the node. #[allow(clippy::match_wild_err_arm)] fn load_persistent_state( rpc: &bitcoincore_rpc::Client, state_addr: &str, ) -> Result<PersistentWalletState, Error> { let info: Value = rpc.call("getaddressinfo", &[state_addr.into()])?; match info.get("label") { None => Err(Error::WalletNotRegistered), Some(&Value::String(ref label)) => { Ok(match serde_json::from_str::<PersistentWalletState>(label) { Err(_) => panic!( "corrupt persistent wallet state label (address: {}): {}", state_addr, label ), Ok(s) => s, }) } Some(_) => unreachable!(), } } /// Calculates the bip32 seeds from the mnemonic phrase. /// In order are returned: /// - the master xpriv /// - the external address xpriv /// - the internal address xpriv fn calc_xkeys( seed: &[u8], ) -> (bip32::ExtendedPrivKey, bip32::ExtendedPrivKey, bip32::ExtendedPrivKey) { // Network isn't of importance here. let master_xpriv = bip32::ExtendedPrivKey::new_master(BNetwork::Bitcoin, &seed[..]).unwrap(); // Add BIP-44 derivations for external and internal addresses. let external_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/0").unwrap()) .unwrap(); let internal_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/1").unwrap()) .unwrap(); (master_xpriv, external_xpriv, internal_xpriv) } /// Register a new [Wallet]. pub fn register(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); // create the wallet in Core let tmp_rpc = network.connect(None)?; match tmp_rpc.create_wallet(fp.as_str(), Some(true))?.warning { None => {} Some(ref s) if s.is_empty() => {} Some(warning) => { warn!("Received warning when creating wallet {} in Core: {}", fp, warning,) } } let rpc = network.connect(Some(&fp))?; // Check if the user was already registered. let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); match Wallet::load_persistent_state(&rpc, &state_addr) { Err(Error::WalletNotRegistered) => {} // good Ok(_) => return Err(Error::WalletAlreadyRegistered), Err(e) => { warn!("Unexpected error while registering wallet: {}", e); return Err(e); } } let wallet = Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), next_internal_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }; wallet.save_persistent_state()?; Ok(wallet) } /// Login to an existing [Wallet]. pub fn login(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); let tmp_rpc = network.connect(None)?; tmp_rpc.load_wallet(&fp)?; let rpc = network.connect(Some(&fp))?; let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); let state = Wallet::load_persistent_state(&rpc, &state_addr)?; Ok(Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(state.next_external_child), next_internal_child: cell::Cell::new(state.next_internal_child), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }) } pub fn fingerprint(&self) -> bip32::Fingerprint { self.master_xpriv.fingerprint(&SECP) } pub fn logout(self) -> Result<(), Error> { self.rpc.unload_wallet(None)?; Ok(()) } pub fn mnemonic(&self) -> String { self.mnemonic.clone() } fn derive_private_key( &self, fp: bip32::Fingerprint, child: bip32::ChildNumber, ) -> Result<secp256k1::SecretKey, Error> { let xpriv = if fp == self.external_xpriv.fingerprint(&SECP) { self.external_xpriv } else if fp == self.internal_xpriv.fingerprint(&SECP) { self.internal_xpriv } else { error!("Address is labeled with unknown master xpriv fingerprint: {:?}", fp); return Err(Error::CorruptNodeData); }; let privkey = xpriv.derive_priv(&SECP, &[child])?.private_key; Ok(privkey.key) } pub fn updates(&mut self) -> Result<Vec<Value>, Error> { let mut msgs = vec![]; // check for new blocks let tip = self.rpc.get_best_block_hash()?; if self.tip!= Some(tip) { let info: Value = self.rpc.call("getblock", &[tip.to_hex().into(), 1.into()])?; msgs.push(json!({ "event": "block", "block": { "block_height": info["height"].as_u64().req()?, "block_hash": tip.to_hex() } })); self.tip = Some(tip); } // check for new transactions // XXX does the app care about the transaction data in the event? if let Some(last_tx) = self._get_transactions(1, 0)?.0.get(0) { let txid = last_tx["txhash"].as_str().req()?; let txid = sha256d::Hash::from_hex(txid)?; if self.last_tx!= Some(txid) { self.last_tx = Some(txid); msgs.push(json!({ "event": "transaction", "transaction": last_tx })); } } // update fees once every FEE_ESTIMATES_TTL if self.cached_fees.1.elapsed() >= FEE_ESTIMATES_TTL { self.cached_fees = (self._make_fee_estimates()?, Instant::now()); msgs.push(json!({ "event": "fees", "fees": self.cached_fees.0 })); } // TODO: // {"event":"subaccount","subaccount":{"bits":"701144.66","btc":"0.70114466","fiat":"0.7712591260000000622741556099981585311432","fiat_currency":"EUR","fiat_rate":"1.10000000000000008881784197001252","has_transactions":true,"mbtc":"701.14466","name":"","pointer":0,"receiving_id":"GA3MQKVp6pP7royXDuZcw55F2TXTgg","recovery_chain_code":"","recovery_pub_key":"","satoshi":70114466,"type":"2of2","ubtc":"701144.66"}} // XXX use zmq? Ok(msgs) } pub fn get_account(&self) -> Result<Value, Error> { let has_transactions = self._get_transactions(1, 0)?.1; extend( json!({ "type": "core", "pointer": 0, "receiving_id": "", "name": "RPC wallet", "has_transactions": has_transactions, }), self._get_balance(0)?, ) } pub fn get_balance(&self, details: &Value) -> Result<Value, Error> { let min_conf = details["num_confs"].as_u64().req()? as u32; self._get_balance(min_conf) } fn _get_balance(&self, min_conf: u32) -> Result<Value, Error> { //TODO(stevenroose) implement in rust-bitcoincore-rpc once bitcoin::Amount lands let mut args = vec![Value::Null, json!(min_conf), json!(true)]; #[cfg(feature = "liquid")] { if let NetworkId::Elements(net) = self.network.id() { args.push(coins::liq::asset_hex(net).into()); } } let balance: f64 = self.rpc.call("getbalance", &args)?; Ok(self._convert_satoshi(btc_to_usat(balance))) } pub fn get_transactions(&self, details: &Value) -> Result<Value, Error> { let page = details["page_id"].as_u64().req()? as usize; let (txs, potentially_has_more) = self._get_transactions(PER_PAGE, PER_PAGE * page)?; Ok(json!({ "list": txs, "page_id": page, "next_page_id": if potentially_has_more { Some(page+1) } else { None }, })) } fn _get_transactions(&self, limit: usize, start: usize) -> Result<(Vec<Value>, bool), Error> { // fetch listtranssactions let txdescs: Vec<Value> = self .rpc .call("listtransactions", &["*".into(), limit.into(), start.into(), true.into()])?; let potentially_has_more = txdescs.len() == limit; // fetch full transactions and convert to GDK format let mut txs = Vec::new(); for desc in txdescs.into_iter() { let txid = sha256d::Hash::from_hex(desc["txid"].as_str().req()?)?; let blockhash = &desc["blockhash"]; let tx_hex: String = self.rpc.call( "getrawtransaction", &[txid.to_hex().into(), false.into(), blockhash.clone()], )?; txs.push(format_gdk_tx(&desc, &hex::decode(&tx_hex)?, self.network.id())?); } Ok((txs, potentially_has_more)) } pub fn get_transaction(&self, txid: &str) -> Result<Value, Error> { let txid = sha256d::Hash::from_hex(txid)?; let desc: Value = self.rpc.call("gettransaction", &[txid.to_hex().into(), true.into()])?; let raw_tx = hex::decode(desc["hex"].as_str().req()?)?; format_gdk_tx(&desc, &raw_tx, self.network.id()) } pub fn create_transaction(&self, details: &Value) -> Result<String, Error> { debug!("create_transaction(): {:?}", details); let unfunded_tx = match self.network.id() { NetworkId::Bitcoin(..) => coins::btc::create_transaction(&self.rpc, details)?, NetworkId::Elements(..) => coins::liq::create_transaction(&self.rpc, details)?, }; debug!("create_transaction unfunded tx: {:?}", hex::encode(&unfunded_tx)); // TODO explicit handling for id_no_amount_specified id_fee_rate_is_below_minimum id_invalid_replacement_fee_rate // id_send_all_requires_a_single_output Ok(hex::encode(unfunded_tx)) } pub fn sign_transaction(&self, details: &Value) -> Result<String, Error> { debug!("sign_transaction(): {:?}", details); let change_address = self.next_address(&self.internal_xpriv, &self.next_internal_child)?; // If we don't have any inputs, we can fail early. let unspent: Vec<Value> = self.rpc.call("listunspent", &[0.into()])?; if unspent.is_empty() { return Err(Error::NoUtxosFound); } debug!("list_unspent: {:?}", unspent); let raw_tx = match self.network.id() { NetworkId::Bitcoin(_) => { coins::btc::sign_transaction(&self.rpc, details, &change_address, |fp, child| { self.derive_private_key(*fp, *child) })? } NetworkId::Elements(net) => coins::liq::sign_transaction( &self.rpc, net, details, &change_address, |fp, child| self.derive_private_key(*fp, *child), )?, }; let hex_tx = hex::encode(&raw_tx); //TODO(stevenroose) remove when confident in signing code let ret: Vec<Value> = self.rpc.call("testmempoolaccept", &[vec![hex_tx.clone()].into()])?; let accept = ret.into_iter().next().unwrap(); if!(accept["allowed"].as_bool().req()?) { error!( "sign_transaction(): signed tx is not valid: {}", accept["reject-reason"].as_str().req()? ); // TODO(stevenroose) should we return an error?? } Ok(hex_tx) } pub fn send_transaction(&self, details: &Value) -> Result<String, Error> { let tx_hex = details["hex"].as_str().req()?; Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } pub fn send_raw_transaction(&self, tx_hex: &str) -> Result<String, Error> { Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } /// Return the next address for the derivation and import it in Core. fn next_address( &self, xpriv: &bip32::ExtendedPrivKey, child: &cell::Cell<bip32::ChildNumber>, ) -> Result<String, Error> { let child_xpriv = xpriv.derive_priv(&SECP, &[child.get()])?; let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); let meta = AddressMeta { fingerprint: Some(xpriv.fingerprint(&SECP)), child: Some(child.get()), ..Default::default() }; let address_str = match self.network.id() { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => { let mut addr = elements::Address::p2shwpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ); let blinding_key = wally::asset_blinding_key_to_ec_private_key( &self.master_blinding_key, &addr.script_pubkey(), ); let blinding_pubkey = secp256k1::PublicKey::from_secret_key(&SECP, &blinding_key); addr.blinding_pubkey = Some(blinding_pubkey); // Store blinding privkey in the node. let addr_str = addr.to_string(); coins::liq::store_blinding_key(&self.rpc, &addr_str, &blinding_key)?; addr_str } NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), }; // Since this is a newly generated address, rescanning is not required. self.rpc.import_public_key(&child_xpub.public_key, Some(&meta.to_label()?), Some(false))?; child.set(match child.get() { bip32::ChildNumber::Normal { index, } => bip32::ChildNumber::from_normal_idx(index + 1)?, _ => unreachable!(), }); self.save_persistent_state()?; Ok(address_str) } pub fn get_receive_address(&self, _details: &Value) -> Result<Value, Error> { let address = self.next_address(&self.external_xpriv, &self.next_external_child)?; // { // "address": "2N2x4EgizS2w3DUiWYWW9pEf4sGYRfo6PAX", // "address_type": "p2wsh", // "branch": 1, // "pointer": 13, // "script": "52210338832debc5e15ce143d5cf9241147ac0019e7516d3d9569e04b0e18f3278718921025dfaa85d64963252604e1b139b40182bb859a9e2e1aa2904876c34e82158d85452ae", // "script_type": 14, // "subtype": null // } Ok(json!({ "address": address, "address_type": "p2wpkh", })) } pub fn get_fee_estimates(&self) -> Option<&Value> { // will not be available before the first "tick", which should // happen as soon as GA_connect initializes the wallet if self.cached_fees.0.is_null() { None } else { Some(&self.cached_fees.0) } } pub fn
_make_fee_estimates
identifier_name
wallet.rs
let child = bip32::ChildNumber::from_hardened_idx(350).unwrap(); let child_xpriv = master_xpriv.derive_priv(&SECP, &[child]).unwrap(); let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); match network { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => elements::Address::p2wpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ) .to_string(), NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), } } /// Store the persistent wallet state. fn save_persistent_state(&self) -> Result<(), Error> { let state = PersistentWalletState { next_external_child: self.next_external_child.get(), next_internal_child: self.next_internal_child.get(), }; let store_addr = Wallet::persistent_state_address(self.network.id(), &self.master_xpriv); // Generic call for liquid compat. self.rpc.call("setlabel", &[store_addr.into(), serde_json::to_string(&state)?.into()])?; Ok(()) } /// Load the persistent wallet state from the node. #[allow(clippy::match_wild_err_arm)] fn load_persistent_state( rpc: &bitcoincore_rpc::Client, state_addr: &str, ) -> Result<PersistentWalletState, Error> { let info: Value = rpc.call("getaddressinfo", &[state_addr.into()])?; match info.get("label") { None => Err(Error::WalletNotRegistered), Some(&Value::String(ref label)) => { Ok(match serde_json::from_str::<PersistentWalletState>(label) { Err(_) => panic!( "corrupt persistent wallet state label (address: {}): {}", state_addr, label ), Ok(s) => s, }) } Some(_) => unreachable!(), } } /// Calculates the bip32 seeds from the mnemonic phrase. /// In order are returned: /// - the master xpriv /// - the external address xpriv /// - the internal address xpriv fn calc_xkeys( seed: &[u8], ) -> (bip32::ExtendedPrivKey, bip32::ExtendedPrivKey, bip32::ExtendedPrivKey) { // Network isn't of importance here. let master_xpriv = bip32::ExtendedPrivKey::new_master(BNetwork::Bitcoin, &seed[..]).unwrap(); // Add BIP-44 derivations for external and internal addresses. let external_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/0").unwrap()) .unwrap(); let internal_xpriv = master_xpriv .derive_priv(&SECP, &bip32::DerivationPath::from_str("m/44'/0'/0'/0'/1").unwrap()) .unwrap(); (master_xpriv, external_xpriv, internal_xpriv) } /// Register a new [Wallet]. pub fn register(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); // create the wallet in Core let tmp_rpc = network.connect(None)?; match tmp_rpc.create_wallet(fp.as_str(), Some(true))?.warning { None => {} Some(ref s) if s.is_empty() => {} Some(warning) => { warn!("Received warning when creating wallet {} in Core: {}", fp, warning,) } } let rpc = network.connect(Some(&fp))?; // Check if the user was already registered. let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); match Wallet::load_persistent_state(&rpc, &state_addr) { Err(Error::WalletNotRegistered) => {} // good Ok(_) => return Err(Error::WalletAlreadyRegistered), Err(e) => { warn!("Unexpected error while registering wallet: {}", e); return Err(e); } } let wallet = Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), next_internal_child: cell::Cell::new(bip32::ChildNumber::from_normal_idx(0).unwrap()), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }; wallet.save_persistent_state()?; Ok(wallet) } /// Login to an existing [Wallet]. pub fn login(network: &'static Network, mnemonic: &str) -> Result<Wallet, Error> { let seed = wally::bip39_mnemonic_to_seed(&mnemonic, "")?; let (master_xpriv, external_xpriv, internal_xpriv) = Wallet::calc_xkeys(&seed); let fp = hex::encode(master_xpriv.fingerprint(&SECP).as_bytes()); let tmp_rpc = network.connect(None)?; tmp_rpc.load_wallet(&fp)?; let rpc = network.connect(Some(&fp))?; let state_addr = Wallet::persistent_state_address(network.id(), &master_xpriv); let state = Wallet::load_persistent_state(&rpc, &state_addr)?; Ok(Wallet { network: network, rpc: rpc, mnemonic: mnemonic.to_owned(), master_xpriv: master_xpriv, external_xpriv: external_xpriv, internal_xpriv: internal_xpriv, #[cfg(feature = "liquid")] master_blinding_key: wally::asset_blinding_key_from_seed(&seed), next_external_child: cell::Cell::new(state.next_external_child), next_internal_child: cell::Cell::new(state.next_internal_child), tip: None, last_tx: None, cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2), }) } pub fn fingerprint(&self) -> bip32::Fingerprint { self.master_xpriv.fingerprint(&SECP) } pub fn logout(self) -> Result<(), Error> { self.rpc.unload_wallet(None)?; Ok(()) } pub fn mnemonic(&self) -> String { self.mnemonic.clone() } fn derive_private_key( &self, fp: bip32::Fingerprint, child: bip32::ChildNumber, ) -> Result<secp256k1::SecretKey, Error> { let xpriv = if fp == self.external_xpriv.fingerprint(&SECP) { self.external_xpriv } else if fp == self.internal_xpriv.fingerprint(&SECP) { self.internal_xpriv } else { error!("Address is labeled with unknown master xpriv fingerprint: {:?}", fp); return Err(Error::CorruptNodeData); }; let privkey = xpriv.derive_priv(&SECP, &[child])?.private_key; Ok(privkey.key) } pub fn updates(&mut self) -> Result<Vec<Value>, Error> { let mut msgs = vec![]; // check for new blocks let tip = self.rpc.get_best_block_hash()?; if self.tip!= Some(tip) { let info: Value = self.rpc.call("getblock", &[tip.to_hex().into(), 1.into()])?; msgs.push(json!({ "event": "block", "block": { "block_height": info["height"].as_u64().req()?, "block_hash": tip.to_hex() } })); self.tip = Some(tip); } // check for new transactions // XXX does the app care about the transaction data in the event? if let Some(last_tx) = self._get_transactions(1, 0)?.0.get(0) { let txid = last_tx["txhash"].as_str().req()?; let txid = sha256d::Hash::from_hex(txid)?; if self.last_tx!= Some(txid) { self.last_tx = Some(txid); msgs.push(json!({ "event": "transaction", "transaction": last_tx })); } } // update fees once every FEE_ESTIMATES_TTL if self.cached_fees.1.elapsed() >= FEE_ESTIMATES_TTL { self.cached_fees = (self._make_fee_estimates()?, Instant::now()); msgs.push(json!({ "event": "fees", "fees": self.cached_fees.0 })); } // TODO: // {"event":"subaccount","subaccount":{"bits":"701144.66","btc":"0.70114466","fiat":"0.7712591260000000622741556099981585311432","fiat_currency":"EUR","fiat_rate":"1.10000000000000008881784197001252","has_transactions":true,"mbtc":"701.14466","name":"","pointer":0,"receiving_id":"GA3MQKVp6pP7royXDuZcw55F2TXTgg","recovery_chain_code":"","recovery_pub_key":"","satoshi":70114466,"type":"2of2","ubtc":"701144.66"}} // XXX use zmq? Ok(msgs) } pub fn get_account(&self) -> Result<Value, Error> { let has_transactions = self._get_transactions(1, 0)?.1; extend( json!({ "type": "core", "pointer": 0, "receiving_id": "", "name": "RPC wallet", "has_transactions": has_transactions, }), self._get_balance(0)?, ) } pub fn get_balance(&self, details: &Value) -> Result<Value, Error> { let min_conf = details["num_confs"].as_u64().req()? as u32; self._get_balance(min_conf) } fn _get_balance(&self, min_conf: u32) -> Result<Value, Error> { //TODO(stevenroose) implement in rust-bitcoincore-rpc once bitcoin::Amount lands let mut args = vec![Value::Null, json!(min_conf), json!(true)]; #[cfg(feature = "liquid")] { if let NetworkId::Elements(net) = self.network.id() { args.push(coins::liq::asset_hex(net).into()); } } let balance: f64 = self.rpc.call("getbalance", &args)?; Ok(self._convert_satoshi(btc_to_usat(balance))) } pub fn get_transactions(&self, details: &Value) -> Result<Value, Error> { let page = details["page_id"].as_u64().req()? as usize; let (txs, potentially_has_more) = self._get_transactions(PER_PAGE, PER_PAGE * page)?; Ok(json!({ "list": txs, "page_id": page, "next_page_id": if potentially_has_more { Some(page+1) } else { None }, })) } fn _get_transactions(&self, limit: usize, start: usize) -> Result<(Vec<Value>, bool), Error> { // fetch listtranssactions let txdescs: Vec<Value> = self .rpc .call("listtransactions", &["*".into(), limit.into(), start.into(), true.into()])?; let potentially_has_more = txdescs.len() == limit; // fetch full transactions and convert to GDK format let mut txs = Vec::new(); for desc in txdescs.into_iter() { let txid = sha256d::Hash::from_hex(desc["txid"].as_str().req()?)?; let blockhash = &desc["blockhash"]; let tx_hex: String = self.rpc.call( "getrawtransaction", &[txid.to_hex().into(), false.into(), blockhash.clone()], )?; txs.push(format_gdk_tx(&desc, &hex::decode(&tx_hex)?, self.network.id())?); } Ok((txs, potentially_has_more)) } pub fn get_transaction(&self, txid: &str) -> Result<Value, Error> { let txid = sha256d::Hash::from_hex(txid)?; let desc: Value = self.rpc.call("gettransaction", &[txid.to_hex().into(), true.into()])?; let raw_tx = hex::decode(desc["hex"].as_str().req()?)?; format_gdk_tx(&desc, &raw_tx, self.network.id()) } pub fn create_transaction(&self, details: &Value) -> Result<String, Error> { debug!("create_transaction(): {:?}", details); let unfunded_tx = match self.network.id() { NetworkId::Bitcoin(..) => coins::btc::create_transaction(&self.rpc, details)?, NetworkId::Elements(..) => coins::liq::create_transaction(&self.rpc, details)?, }; debug!("create_transaction unfunded tx: {:?}", hex::encode(&unfunded_tx)); // TODO explicit handling for id_no_amount_specified id_fee_rate_is_below_minimum id_invalid_replacement_fee_rate // id_send_all_requires_a_single_output Ok(hex::encode(unfunded_tx)) } pub fn sign_transaction(&self, details: &Value) -> Result<String, Error> { debug!("sign_transaction(): {:?}", details); let change_address = self.next_address(&self.internal_xpriv, &self.next_internal_child)?; // If we don't have any inputs, we can fail early. let unspent: Vec<Value> = self.rpc.call("listunspent", &[0.into()])?; if unspent.is_empty() { return Err(Error::NoUtxosFound); } debug!("list_unspent: {:?}", unspent); let raw_tx = match self.network.id() { NetworkId::Bitcoin(_) => { coins::btc::sign_transaction(&self.rpc, details, &change_address, |fp, child| { self.derive_private_key(*fp, *child) })? } NetworkId::Elements(net) => coins::liq::sign_transaction( &self.rpc, net, details, &change_address, |fp, child| self.derive_private_key(*fp, *child), )?, }; let hex_tx = hex::encode(&raw_tx); //TODO(stevenroose) remove when confident in signing code let ret: Vec<Value> = self.rpc.call("testmempoolaccept", &[vec![hex_tx.clone()].into()])?; let accept = ret.into_iter().next().unwrap(); if!(accept["allowed"].as_bool().req()?) { error!( "sign_transaction(): signed tx is not valid: {}", accept["reject-reason"].as_str().req()? ); // TODO(stevenroose) should we return an error?? } Ok(hex_tx) } pub fn send_transaction(&self, details: &Value) -> Result<String, Error> { let tx_hex = details["hex"].as_str().req()?; Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } pub fn send_raw_transaction(&self, tx_hex: &str) -> Result<String, Error> { Ok(self.rpc.call::<String>("sendrawtransaction", &[tx_hex.into()])?) } /// Return the next address for the derivation and import it in Core. fn next_address( &self, xpriv: &bip32::ExtendedPrivKey, child: &cell::Cell<bip32::ChildNumber>, ) -> Result<String, Error> { let child_xpriv = xpriv.derive_priv(&SECP, &[child.get()])?; let child_xpub = bip32::ExtendedPubKey::from_private(&SECP, &child_xpriv); let meta = AddressMeta { fingerprint: Some(xpriv.fingerprint(&SECP)), child: Some(child.get()), ..Default::default() }; let address_str = match self.network.id() { #[cfg(feature = "liquid")] NetworkId::Elements(enet) => { let mut addr = elements::Address::p2shwpkh( &child_xpub.public_key, None, coins::liq::address_params(enet), ); let blinding_key = wally::asset_blinding_key_to_ec_private_key( &self.master_blinding_key, &addr.script_pubkey(), ); let blinding_pubkey = secp256k1::PublicKey::from_secret_key(&SECP, &blinding_key); addr.blinding_pubkey = Some(blinding_pubkey); // Store blinding privkey in the node. let addr_str = addr.to_string(); coins::liq::store_blinding_key(&self.rpc, &addr_str, &blinding_key)?; addr_str } NetworkId::Bitcoin(bnet) => Address::p2wpkh(&child_xpub.public_key, bnet).to_string(), #[cfg(not(feature = "liquid"))] _ => unimplemented!(), }; // Since this is a newly generated address, rescanning is not required. self.rpc.import_public_key(&child_xpub.public_key, Some(&meta.to_label()?), Some(false))?; child.set(match child.get() { bip32::ChildNumber::Normal { index, } => bip32::ChildNumber::from_normal_idx(index + 1)?, _ => unreachable!(), }); self.save_persistent_state()?; Ok(address_str) } pub fn get_receive_address(&self, _details: &Value) -> Result<Value, Error> { let address = self.next_address(&self.external_xpriv, &self.next_external_child)?; // { // "address": "2N2x4EgizS2w3DUiWYWW9pEf4sGYRfo6PAX", // "address_type": "p2wsh", // "branch": 1, // "pointer": 13, // "script": "52210338832debc5e15ce143d5cf9241147ac0019e7516d3d9569e04b0e18f3278718921025dfaa85d64963252604e1b139b40182bb859a9e2e1aa2904876c34e82158d85452ae", // "script_type": 14, // "subtype": null // } Ok(json!({ "address": address, "address_type": "p2wpkh", })) } pub fn get_fee_estimates(&self) -> Option<&Value> { // will not be available before the first "tick", which should // happen as soon as GA_connect initializes the wallet if self.cached_fees.0.is_null()
{ None }
conditional_block