use crate::Opcode;
use console::{network::prelude::*, program::Identifier};
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Position<N: Network> {
name: Identifier<N>,
}
impl<N: Network> Position<N> {
#[inline]
pub const fn opcode() -> Opcode {
Opcode::Command("position")
}
#[inline]
pub fn name(&self) -> &Identifier<N> {
&self.name
}
#[inline]
pub fn contains_external_struct(&self) -> bool {
false
}
}
impl<N: Network> Position<N> {
#[inline]
pub fn finalize(&self) -> Result<()> {
Ok(())
}
}
impl<N: Network> Parser for Position<N> {
#[inline]
fn parse(string: &str) -> ParserResult<Self> {
let (string, _) = Sanitizer::parse(string)?;
let (string, _) = tag(*Self::opcode())(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, name) = Identifier::parse(string)?;
let (string, _) = Sanitizer::parse_whitespaces(string)?;
let (string, _) = tag(";")(string)?;
Ok((string, Self { name }))
}
}
impl<N: Network> FromStr for Position<N> {
type Err = Error;
#[inline]
fn from_str(string: &str) -> Result<Self> {
match Self::parse(string) {
Ok((remainder, object)) => {
ensure!(remainder.is_empty(), "Failed to parse string. Found invalid character in: \"{remainder}\"");
Ok(object)
}
Err(error) => bail!("Failed to parse string. {error}"),
}
}
}
impl<N: Network> Debug for Position<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl<N: Network> Display for Position<N> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} ", Self::opcode())?;
write!(f, "{};", self.name)
}
}
impl<N: Network> FromBytes for Position<N> {
fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
let name = Identifier::read_le(&mut reader)?;
Ok(Self { name })
}
}
impl<N: Network> ToBytes for Position<N> {
fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
self.name.write_le(&mut writer)
}
}
#[cfg(test)]
mod tests {
use super::*;
use console::network::MainnetV0;
type CurrentNetwork = MainnetV0;
#[test]
fn test_parse() {
let (string, position) = Position::<CurrentNetwork>::parse("position exit;").unwrap();
assert!(string.is_empty(), "Parser did not consume all of the string: '{string}'");
assert_eq!(position.name, Identifier::from_str("exit").unwrap());
}
}