repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
hako/bbcli
https://github.com/hako/bbcli/blob/709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1/src/date_utils.rs
src/date_utils.rs
use chrono::{DateTime, Utc}; /// Humanizes a date string from "YYYY-MM-DD HH:MM:SS" format to relative time /// Returns strings like "just now", "5 minutes ago", "2 hours ago", "yesterday", etc. pub fn humanize_time(date_str: &str) -> String { // Try to parse the date string (format: "YYYY-MM-DD HH:MM:SS") let parsed = DateTime::parse_from_str(&format!("{} +0000", date_str), "%Y-%m-%d %H:%M:%S %z"); let date_time = match parsed { Ok(dt) => dt.with_timezone(&Utc), Err(_) => { // If parsing fails, return the original string return date_str.to_string(); } }; let now = Utc::now(); let duration = now.signed_duration_since(date_time); let seconds = duration.num_seconds(); let minutes = duration.num_minutes(); let hours = duration.num_hours(); let days = duration.num_days(); if seconds < 0 { // Future date return "just now".to_string(); } else if seconds < 60 { return "just now".to_string(); } else if minutes < 60 { if minutes == 1 { return "1 minute ago".to_string(); } else { return format!("{} minutes ago", minutes); } } else if hours < 24 { if hours == 1 { return "1 hour ago".to_string(); } else { return format!("{} hours ago", hours); } } else if days == 1 { return "yesterday".to_string(); } else if days < 7 { return format!("{} days ago", days); } else if days < 30 { let weeks = days / 7; if weeks == 1 { return "1 week ago".to_string(); } else { return format!("{} weeks ago", weeks); } } else if days < 365 { let months = days / 30; if months == 1 { return "1 month ago".to_string(); } else { return format!("{} months ago", months); } } else { let years = days / 365; if years == 1 { return "1 year ago".to_string(); } else { return format!("{} years ago", years); } } } #[cfg(test)] mod tests { use super::*; use chrono::Duration; #[test] fn test_humanize_recent() { let now = Utc::now(); // Just now let recent = (now - Duration::seconds(30)).format("%Y-%m-%d %H:%M:%S").to_string(); assert_eq!(humanize_time(&recent), "just now"); // 5 minutes ago let mins = (now - Duration::minutes(5)).format("%Y-%m-%d %H:%M:%S").to_string(); assert_eq!(humanize_time(&mins), "5 minutes ago"); } #[test] fn test_humanize_hours() { let now = Utc::now(); let hours = (now - Duration::hours(3)).format("%Y-%m-%d %H:%M:%S").to_string(); assert_eq!(humanize_time(&hours), "3 hours ago"); } #[test] fn test_humanize_days() { let now = Utc::now(); let yesterday = (now - Duration::days(1)).format("%Y-%m-%d %H:%M:%S").to_string(); assert_eq!(humanize_time(&yesterday), "yesterday"); let days = (now - Duration::days(5)).format("%Y-%m-%d %H:%M:%S").to_string(); assert_eq!(humanize_time(&days), "5 days ago"); } #[test] fn test_invalid_date() { let invalid = "invalid date"; assert_eq!(humanize_time(invalid), "invalid date"); } }
rust
MIT
709c6417c8dc4ffd4f7d5f5b42b2672c68f4c8d1
2026-01-04T20:18:31.214572Z
false
rust-embedded/rust-spidev
https://github.com/rust-embedded/rust-spidev/blob/9b2a483bc92c806112a9133c78bc2103c73d9780/src/spidevioctl.rs
src/spidevioctl.rs
// Copyright 2015, Paul Osborne <osbpau@gmail.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // macros import use super::SpiModeFlags; use nix::{ioctl_read, ioctl_write_buf, ioctl_write_ptr}; use std::io; use std::marker::PhantomData; use std::os::unix::prelude::*; fn from_nix_result<T>(res: ::nix::Result<T>) -> io::Result<T> { match res { Ok(r) => Ok(r), Err(err) => Err(err.into()), } } /// Structure that is used when performing communication /// with the kernel. /// /// From the kernel documentation: /// /// ```text /// struct spi_ioc_transfer - describes a single SPI transfer /// @tx_buf: Holds pointer to userspace buffer with transmit data, or null. /// If no data is provided, zeroes are shifted out. /// @rx_buf: Holds pointer to userspace buffer for receive data, or null. /// @len: Length of tx and rx buffers, in bytes. /// @speed_hz: Temporary override of the device's bitrate. /// @bits_per_word: Temporary override of the device's wordsize. /// @delay_usecs: If nonzero, how long to delay after the last bit transfer /// before optionally deselecting the device before the next transfer. /// @cs_change: True to deselect device before starting the next transfer. /// /// This structure is mapped directly to the kernel spi_transfer structure; /// the fields have the same meanings, except of course that the pointers /// are in a different address space (and may be of different sizes in some /// cases, such as 32-bit i386 userspace over a 64-bit x86_64 kernel). /// Zero-initialize the structure, including currently unused fields, to /// accommodate potential future updates. /// /// SPI_IOC_MESSAGE gives userspace the equivalent of kernel spi_sync(). /// Pass it an array of related transfers, they'll execute together. /// Each transfer may be half duplex (either direction) or full duplex. /// /// struct spi_ioc_transfer mesg[4]; /// ... /// status = ioctl(fd, SPI_IOC_MESSAGE(4), mesg); /// /// So for example one transfer might send a nine bit command (right aligned /// in a 16-bit word), the next could read a block of 8-bit data before /// terminating that command by temporarily deselecting the chip; the next /// could send a different nine bit command (re-selecting the chip), and the /// last transfer might write some register values. /// ``` #[allow(non_camel_case_types)] #[derive(Debug, Default)] #[repr(C)] pub struct spi_ioc_transfer<'a, 'b> { tx_buf: u64, rx_buf: u64, len: u32, // optional overrides pub speed_hz: u32, pub delay_usecs: u16, pub bits_per_word: u8, pub cs_change: u8, pub pad: u32, tx_buf_ref: PhantomData<&'a [u8]>, rx_buf_ref: PhantomData<&'b mut [u8]>, } impl<'a, 'b> spi_ioc_transfer<'a, 'b> { /// Create a read transfer pub fn read(buff: &'b mut [u8]) -> Self { spi_ioc_transfer { rx_buf: buff.as_ptr() as *const () as usize as u64, len: buff.len() as u32, ..Default::default() } } /// Create a write transfer pub fn write(buff: &'a [u8]) -> Self { spi_ioc_transfer { tx_buf: buff.as_ptr() as *const () as usize as u64, len: buff.len() as u32, ..Default::default() } } /// Create a read/write transfer. /// Note that the `tx_buf` and `rx_buf` must be the same length. pub fn read_write(tx_buf: &'a [u8], rx_buf: &'b mut [u8]) -> Self { assert_eq!(tx_buf.len(), rx_buf.len()); spi_ioc_transfer { rx_buf: rx_buf.as_ptr() as *const () as usize as u64, tx_buf: tx_buf.as_ptr() as *const () as usize as u64, len: tx_buf.len() as u32, ..Default::default() } } /// Create a read/write transfer using the same buffer for reading /// and writing (in-place transfer). pub fn read_write_in_place(buf: &'a mut [u8]) -> Self { // This is allowed according to a comment in the linux source tree: // https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/Documentation/spi/spidev.rst?id=211ddde0823f1442e4ad052a2f30f050145ccada#n191 spi_ioc_transfer { rx_buf: buf.as_ptr() as *const () as usize as u64, tx_buf: buf.as_ptr() as *const () as usize as u64, len: buf.len() as u32, ..Default::default() } } /// Create a delay transfer of a number of microseconds pub fn delay(microseconds: u16) -> Self { spi_ioc_transfer { delay_usecs: microseconds, len: 0, ..Default::default() } } } mod ioctl { use super::*; const SPI_IOC_MAGIC: u8 = b'k'; const SPI_IOC_NR_TRANSFER: u8 = 0; const SPI_IOC_NR_MODE: u8 = 1; const SPI_IOC_NR_LSB_FIRST: u8 = 2; const SPI_IOC_NR_BITS_PER_WORD: u8 = 3; const SPI_IOC_NR_MAX_SPEED_HZ: u8 = 4; const SPI_IOC_NR_MODE32: u8 = 5; ioctl_read!(get_mode_u8, SPI_IOC_MAGIC, SPI_IOC_NR_MODE, u8); ioctl_read!(get_mode_u32, SPI_IOC_MAGIC, SPI_IOC_NR_MODE32, u32); ioctl_write_ptr!(set_mode, SPI_IOC_MAGIC, SPI_IOC_NR_MODE, u8); ioctl_write_ptr!(set_mode32, SPI_IOC_MAGIC, SPI_IOC_NR_MODE32, u32); ioctl_read!(get_lsb_first, SPI_IOC_MAGIC, SPI_IOC_NR_LSB_FIRST, u8); ioctl_write_ptr!(set_lsb_first, SPI_IOC_MAGIC, SPI_IOC_NR_LSB_FIRST, u8); ioctl_read!( get_bits_per_word, SPI_IOC_MAGIC, SPI_IOC_NR_BITS_PER_WORD, u8 ); ioctl_write_ptr!( set_bits_per_word, SPI_IOC_MAGIC, SPI_IOC_NR_BITS_PER_WORD, u8 ); ioctl_read!( get_max_speed_hz, SPI_IOC_MAGIC, SPI_IOC_NR_MAX_SPEED_HZ, u32 ); ioctl_write_ptr!( set_max_speed_hz, SPI_IOC_MAGIC, SPI_IOC_NR_MAX_SPEED_HZ, u32 ); // NOTE: this macro works for single transfers but cannot properly // calculate size for multi transfer whose length we will not know // until runtime. We fallback to using the underlying ioctl for that // use case. ioctl_write_ptr!( spidev_transfer, SPI_IOC_MAGIC, SPI_IOC_NR_TRANSFER, spi_ioc_transfer ); ioctl_write_buf!( spidev_transfer_buf, SPI_IOC_MAGIC, SPI_IOC_NR_TRANSFER, spi_ioc_transfer ); } /// Representation of a spidev transfer that is shared /// with external users pub type SpidevTransfer<'a, 'b> = spi_ioc_transfer<'a, 'b>; pub fn get_mode(fd: RawFd) -> io::Result<u8> { let mut mode: u8 = 0; from_nix_result(unsafe { ioctl::get_mode_u8(fd, &mut mode) })?; Ok(mode) } pub fn get_mode_u32(fd: RawFd) -> io::Result<u32> { let mut mode: u32 = 0; from_nix_result(unsafe { ioctl::get_mode_u32(fd, &mut mode) })?; Ok(mode) } pub fn set_mode(fd: RawFd, mode: SpiModeFlags) -> io::Result<()> { // we will always use the 8-bit mode write unless bits not in // the 8-bit mask are used. This is because WR_MODE32 was not // added until later kernels. This provides a reasonable story // for forwards and backwards compatibility if (mode.bits() & 0xFFFFFF00) != 0 { from_nix_result(unsafe { ioctl::set_mode32(fd, &mode.bits()) })?; } else { let bits: u8 = mode.bits() as u8; from_nix_result(unsafe { ioctl::set_mode(fd, &bits) })?; } Ok(()) } pub fn get_lsb_first(fd: RawFd) -> io::Result<u8> { let mut lsb_first: u8 = 0; from_nix_result(unsafe { ioctl::get_lsb_first(fd, &mut lsb_first) })?; Ok(lsb_first) } pub fn set_lsb_first(fd: RawFd, lsb_first: bool) -> io::Result<()> { let lsb_first_value: u8 = if lsb_first { 1 } else { 0 }; from_nix_result(unsafe { ioctl::set_lsb_first(fd, &lsb_first_value) })?; Ok(()) } pub fn get_bits_per_word(fd: RawFd) -> io::Result<u8> { let mut bits_per_word: u8 = 0; from_nix_result(unsafe { ioctl::get_bits_per_word(fd, &mut bits_per_word) })?; Ok(bits_per_word) } pub fn set_bits_per_word(fd: RawFd, bits_per_word: u8) -> io::Result<()> { from_nix_result(unsafe { ioctl::set_bits_per_word(fd, &bits_per_word) })?; Ok(()) } pub fn get_max_speed_hz(fd: RawFd) -> io::Result<u32> { let mut max_speed_hz: u32 = 0; from_nix_result(unsafe { ioctl::get_max_speed_hz(fd, &mut max_speed_hz) })?; Ok(max_speed_hz) } pub fn set_max_speed_hz(fd: RawFd, max_speed_hz: u32) -> io::Result<()> { from_nix_result(unsafe { ioctl::set_max_speed_hz(fd, &max_speed_hz) })?; Ok(()) } pub fn transfer(fd: RawFd, transfer: &mut SpidevTransfer) -> io::Result<()> { // The kernel will directly modify the rx_buf of the SpidevTransfer // rx_buf if present, so there is no need to do any additional work from_nix_result(unsafe { ioctl::spidev_transfer(fd, transfer) })?; Ok(()) } pub fn transfer_multiple(fd: RawFd, transfers: &mut [SpidevTransfer]) -> io::Result<()> { from_nix_result(unsafe { ioctl::spidev_transfer_buf(fd, transfers) })?; Ok(()) }
rust
Apache-2.0
9b2a483bc92c806112a9133c78bc2103c73d9780
2026-01-04T20:18:19.386705Z
false
rust-embedded/rust-spidev
https://github.com/rust-embedded/rust-spidev/blob/9b2a483bc92c806112a9133c78bc2103c73d9780/src/lib.rs
src/lib.rs
// Copyright 2015, Paul Osborne <osbpau@gmail.com> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/license/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! # Spidev //! //! The `spidev` crate provides access to Linux spidev devices //! from rust. The wrapping of the interface is pretty direct //! and shouldn't cause any surprises. //! //! Additional information on the interface may be found in //! [the kernel documentation //! for spidev](https://www.kernel.org/doc/Documentation/spi/spidev). //! //! # Examples //! //! ```no_run //! extern crate spidev; //! use std::io; //! use std::io::prelude::*; //! use spidev::{Spidev, SpidevOptions, SpidevTransfer, SpiModeFlags}; //! //! fn create_spi() -> io::Result<Spidev> { //! let mut spi = Spidev::open("/dev/spidev0.0")?; //! let options = SpidevOptions::new() //! .bits_per_word(8) //! .max_speed_hz(20_000) //! .mode(SpiModeFlags::SPI_MODE_0) //! .build(); //! spi.configure(&options)?; //! Ok(spi) //! } //! //! /// perform half duplex operations using Read and Write traits //! fn half_duplex(spi: &mut Spidev) -> io::Result<()> { //! let mut rx_buf = [0_u8; 10]; //! spi.write(&[0x01, 0x02, 0x03])?; //! spi.read(&mut rx_buf)?; //! println!("{:?}", rx_buf); //! Ok(()) //! } //! //! /// Perform full duplex operations using Ioctl //! fn full_duplex(spi: &mut Spidev) -> io::Result<()> { //! // "write" transfers are also reads at the same time with //! // the read having the same length as the write //! let tx_buf = [0x01, 0x02, 0x03]; //! let mut rx_buf = [0; 3]; //! { //! let mut transfer = SpidevTransfer::read_write(&tx_buf, &mut rx_buf); //! spi.transfer(&mut transfer)?; //! } //! println!("{:?}", rx_buf); //! Ok(()) //! } //! //! fn main() { //! let mut spi = create_spi().unwrap(); //! println!("{:?}", half_duplex(&mut spi).unwrap()); //! println!("{:?}", full_duplex(&mut spi).unwrap()); //! } //! ``` pub mod spidevioctl; pub use crate::spidevioctl::SpidevTransfer; use bitflags::bitflags; use std::fs::{File, OpenOptions}; use std::io; use std::io::prelude::*; use std::os::unix::prelude::*; use std::path::Path; // Constants extracted from linux/spi/spidev.h bitflags! { #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SpiModeFlags: u32 { /// Clock Phase const SPI_CPHA = 0x01; /// Clock Polarity const SPI_CPOL = 0x02; /// Chipselect Active High? const SPI_CS_HIGH = 0x04; /// Per-word Bits On Wire const SPI_LSB_FIRST = 0x08; /// SI/SO Signals Shared const SPI_3WIRE = 0x10; /// Loopback Mode const SPI_LOOP = 0x20; /// 1 dev/bus; no chipselect const SPI_NO_CS = 0x40; /// Slave pulls low to pause const SPI_READY = 0x80; // Common Configurations const SPI_MODE_0 = 0x00; const SPI_MODE_1 = Self::SPI_CPHA.bits(); const SPI_MODE_2 = Self::SPI_CPOL.bits(); const SPI_MODE_3 = (Self::SPI_CPOL.bits() | Self::SPI_CPHA.bits()); // == Only Supported with 32-bits == /// Transmit with 2 wires const SPI_TX_DUAL = 0x100; /// Transmit with 4 wires const SPI_TX_QUAD = 0x200; /// Receive with 2 wires const SPI_RX_DUAL = 0x400; /// Receive with 4 wires const SPI_RX_QUAD = 0x800; } } /// Provide high-level access to Linux Spidev Driver #[derive(Debug)] pub struct Spidev { devfile: File, } /// Options that control defaults for communication on a device /// /// Individual settings may be overridden via parameters that /// are specified as part of any individual SpiTransfer when /// using `transfer` or `transfer_multiple`. /// /// Options that are not configured with one of the builder /// functions will not be modified in the kernel when /// `configure` is called. #[derive(Debug, Default, Clone, Copy, PartialEq)] pub struct SpidevOptions { pub bits_per_word: Option<u8>, pub max_speed_hz: Option<u32>, pub lsb_first: Option<bool>, pub spi_mode: Option<SpiModeFlags>, } impl SpidevOptions { /// Create a new, empty set of options pub fn new() -> SpidevOptions { SpidevOptions::default() } /// The number of bits in each SPI transfer word /// /// The value zero signifies eight bits. pub fn bits_per_word(&mut self, bits_per_word: u8) -> &mut Self { self.bits_per_word = Some(bits_per_word); self } /// The maximum SPI transfer speed, in Hz /// /// The controller can't necessarily assign that specific clock speed. pub fn max_speed_hz(&mut self, max_speed_hz: u32) -> &mut Self { self.max_speed_hz = Some(max_speed_hz); self } /// The bit justification used to transfer SPI words /// /// Zero indicates MSB-first; other values indicate the less common /// LSB-first encoding. In both cases the specified value is /// right-justified in each word, so that unused (TX) or undefined (RX) /// bits are in the MSBs. pub fn lsb_first(&mut self, lsb_first: bool) -> &mut Self { self.lsb_first = Some(lsb_first); self } /// Set the SPI Transfer Mode /// /// Use the constants SPI_MODE_0..SPI_MODE_3; or if you prefer /// you can combine SPI_CPOL (clock polarity, idle high iff this /// is set) or SPI_CPHA (clock phase, sample on trailing edge /// iff this is set) flags. /// /// Note that this API will always prefer to use SPI_IOC_WR_MODE /// rathern than the 32-bit one to target the greatest number of /// kernels. SPI_IOC_WR_MODE32 is only present in 3.15+ kernels. /// SPI_IOC_WR_MODE32 will be used iff bits higher than those in /// 8bits are provided (e.g. Dual/Quad Tx/Rx). pub fn mode(&mut self, mode: SpiModeFlags) -> &mut Self { self.spi_mode = Some(mode); self } /// Finalize and build the SpidevOptions pub fn build(&self) -> Self { *self } } impl Spidev { /// Wrap an already opened [`File`] for use as an spidev pub fn new(devfile: File) -> Self { Self { devfile } } /// Open the spidev device with the provided path /// /// Typically, the path will be something like `"/dev/spidev0.0"` /// where the first number if the bus and the second number /// is the chip select on that bus for the device being targeted. pub fn open<P: AsRef<Path>>(path: P) -> io::Result<Spidev> { let devfile = OpenOptions::new() .read(true) .write(true) .create(false) .open(path)?; Ok(Self::new(devfile)) } /// Get a reference to the underlying [`File`] object pub fn inner(&self) -> &File { &self.devfile } /// Consume the object and get the underlying [`File`] object pub fn into_inner(self) -> File { self.devfile } /// Write the provided configuration to this device pub fn configure(&mut self, options: &SpidevOptions) -> io::Result<()> { // write out each present option to the device. Options // that are None are left as-is, in order to reduce // overhead let fd = self.devfile.as_raw_fd(); if let Some(bpw) = options.bits_per_word { spidevioctl::set_bits_per_word(fd, bpw)?; } if let Some(speed) = options.max_speed_hz { spidevioctl::set_max_speed_hz(fd, speed)?; } if let Some(lsb_first) = options.lsb_first { spidevioctl::set_lsb_first(fd, lsb_first)?; } if let Some(spi_mode_flags) = options.spi_mode { spidevioctl::set_mode(fd, spi_mode_flags)?; } Ok(()) } /// Read the current configuration from this device pub fn query_configuration(&self) -> io::Result<SpidevOptions> { let fd = self.devfile.as_raw_fd(); let bpw = spidevioctl::get_bits_per_word(fd)?; let speed = spidevioctl::get_max_speed_hz(fd)?; let lsb_first = (spidevioctl::get_lsb_first(fd)?) != 0; // Try to get the mode as 32-bit (`RD_MODE32`). Older kernels may return // `ENOTTY` indicating 32-bit is not supported. In that case we retry in // 8-bit mode. let mode_bits = spidevioctl::get_mode_u32(fd).or_else(|err| { if err.raw_os_error() == Some(libc::ENOTTY) { spidevioctl::get_mode(fd).map(|value| value as u32) } else { Err(err) } })?; let mode = SpiModeFlags::from_bits_retain(mode_bits); let options = SpidevOptions::new() .bits_per_word(bpw) .max_speed_hz(speed) .lsb_first(lsb_first) .mode(mode) .build(); Ok(options) } /// Perform a single transfer pub fn transfer(&self, transfer: &mut SpidevTransfer) -> io::Result<()> { spidevioctl::transfer(self.devfile.as_raw_fd(), transfer) } /// Perform multiple transfers in a single system call to the kernel /// /// Chaining together multiple requests like this can reduce latency /// and be used for conveniently and efficient implementing some /// protocols without extra round trips back to userspace. pub fn transfer_multiple(&self, transfers: &mut [SpidevTransfer]) -> io::Result<()> { spidevioctl::transfer_multiple(self.devfile.as_raw_fd(), transfers) } } impl Read for Spidev { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.devfile.read(buf) } } impl Write for Spidev { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.devfile.write(buf) } fn flush(&mut self) -> io::Result<()> { self.devfile.flush() } } impl AsRawFd for Spidev { fn as_raw_fd(&self) -> RawFd { self.devfile.as_raw_fd() } } #[cfg(test)] mod test { use super::{SpiModeFlags, SpidevOptions}; #[test] fn test_spidev_options_all() { let options = SpidevOptions::new() .bits_per_word(8) .max_speed_hz(20_000) .lsb_first(false) .mode(SpiModeFlags::SPI_MODE_0) .build(); assert_eq!(options.bits_per_word, Some(8)); assert_eq!(options.max_speed_hz, Some(20_000)); assert_eq!(options.lsb_first, Some(false)); assert_eq!(options.spi_mode, Some(SpiModeFlags::SPI_MODE_0)); } #[test] fn test_spidev_options_some() { let mut options = SpidevOptions::new(); options.bits_per_word(10); options.lsb_first(true); assert_eq!(options.bits_per_word, Some(10)); assert_eq!(options.max_speed_hz, None); assert_eq!(options.lsb_first, Some(true)); assert_eq!(options.spi_mode, None); } }
rust
Apache-2.0
9b2a483bc92c806112a9133c78bc2103c73d9780
2026-01-04T20:18:19.386705Z
false
rust-embedded/rust-spidev
https://github.com/rust-embedded/rust-spidev/blob/9b2a483bc92c806112a9133c78bc2103c73d9780/examples/spidev-hello.rs
examples/spidev-hello.rs
extern crate spidev; use spidev::Spidev; use std::io::prelude::*; fn main() { let mut spidev = Spidev::open("/dev/spidev0.0").unwrap(); let wrote = spidev.write(&[0xAA, 0x00, 0x01, 0x02, 0x04]).unwrap(); let mut buf: [u8; 10] = [0; 10]; let read = spidev.read(&mut buf).unwrap(); // read 10 println!("Wrote: {}, Read: {}, Data: {:?}", wrote, read, buf); }
rust
Apache-2.0
9b2a483bc92c806112a9133c78bc2103c73d9780
2026-01-04T20:18:19.386705Z
false
rust-embedded/rust-spidev
https://github.com/rust-embedded/rust-spidev/blob/9b2a483bc92c806112a9133c78bc2103c73d9780/examples/spidev-bidir.rs
examples/spidev-bidir.rs
extern crate spidev; use spidev::spidevioctl::SpidevTransfer; use spidev::{SpiModeFlags, Spidev, SpidevOptions}; fn main() { let mut spidev = Spidev::open("/dev/spidev0.0").unwrap(); let options = SpidevOptions::new() .bits_per_word(8) .max_speed_hz(5000) .lsb_first(false) .mode(SpiModeFlags::SPI_MODE_0) .build(); spidev.configure(&options).unwrap(); println!("===== Single transfer ========="); let tx_buf = [0xaa, 0xbb, 0xcc, 0xdd, 0xee]; let mut rx_buf = [0; 5]; let mut transfer = SpidevTransfer::read_write(&tx_buf, &mut rx_buf); println!("{:?}", spidev.transfer(&mut transfer)); println!("===== Multi Transfer ========="); let mut rx_buf1 = [0; 10]; let tx_buf2 = [0x00, 0x01, 0x02, 0x03]; let delay_usecs = 10; let tx_buf3 = [0xff, 0xfe, 0xfd]; let mut rx_buf3 = [0; 3]; let result = { let mut transfers = vec![ SpidevTransfer::read(&mut rx_buf1), SpidevTransfer::write(&tx_buf2), SpidevTransfer::delay(delay_usecs), SpidevTransfer::read_write(&tx_buf3, &mut rx_buf3), ]; spidev.transfer_multiple(&mut transfers) }; match result { Ok(_) => { println!("Read {:?}", rx_buf1); println!("Wrote {:?}", tx_buf2); println!("Delayed by {} microseconds", delay_usecs); println!("Wrote {:?} and read {:?}", tx_buf3, rx_buf3); } Err(err) => println!("{:?}", err), } }
rust
Apache-2.0
9b2a483bc92c806112a9133c78bc2103c73d9780
2026-01-04T20:18:19.386705Z
false
dtolnay/dtoa
https://github.com/dtolnay/dtoa/blob/902d0d7e180457b9997b8ef3a67e68ee2e78a5b1/src/lib.rs
src/lib.rs
//! [![github]](https://github.com/dtolnay/dtoa)&ensp;[![crates-io]](https://crates.io/crates/dtoa)&ensp;[![docs-rs]](https://docs.rs/dtoa) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //! <br> //! //! This crate provides fast conversion of floating point primitives to decimal //! strings. The implementation is a straightforward Rust port of [Milo Yip]'s //! C++ implementation [dtoa.h]. The original C++ code of each function is //! included in comments. //! //! See also [`itoa`] for printing integer primitives. //! //! [Milo Yip]: https://github.com/miloyip //! [dtoa.h]: https://github.com/miloyip/rapidjson/blob/master/include/rapidjson/internal/dtoa.h //! [`itoa`]: https://github.com/dtolnay/itoa //! //! # Example //! //! ``` //! fn main() { //! let mut buffer = dtoa::Buffer::new(); //! let printed = buffer.format(2.71828f64); //! assert_eq!(printed, "2.71828"); //! } //! ``` //! //! ## Performance //! //! The [dtoa-benchmark] compares this library and other Rust floating point //! formatting implementations across a range of precisions. The vertical axis //! in this chart shows nanoseconds taken by a single execution of //! `dtoa::Buffer::new().format_finite(value)` so a lower result indicates a //! faster library. //! //! [dtoa-benchmark]: https://github.com/dtolnay/dtoa-benchmark //! //! ![performance](https://raw.githubusercontent.com/dtolnay/dtoa/master/dtoa-benchmark.png) #![doc(html_root_url = "https://docs.rs/dtoa/1.0.11")] #![no_std] #![allow( clippy::cast_lossless, clippy::cast_possible_truncation, clippy::cast_possible_wrap, clippy::cast_precision_loss, clippy::cast_sign_loss, clippy::doc_markdown, clippy::expl_impl_clone_on_copy, clippy::if_not_else, clippy::missing_errors_doc, clippy::must_use_candidate, clippy::needless_doctest_main, clippy::range_plus_one, clippy::semicolon_if_nothing_returned, // https://github.com/rust-lang/rust-clippy/issues/7768 clippy::shadow_unrelated, clippy::suspicious_else_formatting, clippy::unreadable_literal, clippy::unseparated_literal_suffix )] #[macro_use] mod diyfp; #[macro_use] mod dtoa; use core::mem::MaybeUninit; use core::slice; use core::str; #[cfg(feature = "no-panic")] use no_panic::no_panic; const NAN: &str = "NaN"; const INFINITY: &str = "inf"; const NEG_INFINITY: &str = "-inf"; /// A correctly sized stack allocation for the formatted float to be written /// into. /// /// # Example /// /// ``` /// let mut buffer = dtoa::Buffer::new(); /// let printed = buffer.format_finite(2.71828); /// assert_eq!(printed, "2.71828"); /// ``` pub struct Buffer { bytes: [MaybeUninit<u8>; 25], } impl Default for Buffer { #[inline] fn default() -> Buffer { Buffer::new() } } impl Copy for Buffer {} #[allow(clippy::non_canonical_clone_impl)] impl Clone for Buffer { #[inline] fn clone(&self) -> Self { Buffer::new() } } impl Buffer { /// This is a cheap operation; you don't need to worry about reusing buffers /// for efficiency. #[inline] #[cfg_attr(feature = "no-panic", no_panic)] pub fn new() -> Buffer { let bytes = [MaybeUninit::<u8>::uninit(); 25]; Buffer { bytes } } /// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function formats NaN as the string "NaN", positive infinity as /// "inf", and negative infinity as "-inf" to match std::fmt. /// /// If your input is known to be finite, you may get better performance by /// calling the `format_finite` method instead of `format` to avoid the /// checks for special cases. #[cfg_attr(feature = "no-panic", no_panic)] pub fn format<F: Float>(&mut self, value: F) -> &str { if value.is_nonfinite() { value.format_nonfinite() } else { self.format_finite(value) } } /// Print a floating point number into this buffer and return a reference to /// its string representation within the buffer. /// /// # Special cases /// /// This function **does not** check for NaN or infinity. If the input /// number is not a finite float, the printed representation will be some /// correctly formatted but unspecified numerical value. /// /// Please check [`is_finite`] yourself before calling this function, or /// check [`is_nan`] and [`is_infinite`] and handle those cases yourself. /// /// [`is_finite`]: f64::is_finite /// [`is_nan`]: f64::is_nan /// [`is_infinite`]: f64::is_infinite #[cfg_attr(feature = "no-panic", no_panic)] pub fn format_finite<F: Float>(&mut self, value: F) -> &str { value.write(self) } } /// A floating point number that can be written into a [`dtoa::Buffer`][Buffer]. /// /// This trait is sealed and cannot be implemented for types outside of dtoa. pub trait Float: private::Sealed {} impl Float for f32 {} impl Float for f64 {} // Seal to prevent downstream implementations of Float trait. mod private { pub trait Sealed: Copy { fn is_nonfinite(self) -> bool; fn format_nonfinite(self) -> &'static str; fn write(self, buf: &mut crate::Buffer) -> &str; } } impl private::Sealed for f32 { #[inline] #[cfg_attr(feature = "no-panic", no_panic)] fn is_nonfinite(self) -> bool { const EXP_MASK: u32 = 0x7f800000; let bits = self.to_bits(); bits & EXP_MASK == EXP_MASK } #[cold] #[cfg_attr(feature = "no-panic", no_panic)] fn format_nonfinite(self) -> &'static str { const MANTISSA_MASK: u32 = 0x007fffff; const SIGN_MASK: u32 = 0x80000000; let bits = self.to_bits(); if bits & MANTISSA_MASK != 0 { NAN } else if bits & SIGN_MASK != 0 { NEG_INFINITY } else { INFINITY } } #[inline] fn write(self, buf: &mut Buffer) -> &str { dtoa! { floating_type: f32, significand_type: u32, exponent_type: i32, diy_significand_size: 32, significand_size: 23, exponent_bias: 0x7F, mask_type: u32, exponent_mask: 0x7F800000, significand_mask: 0x007FFFFF, hidden_bit: 0x00800000, cached_powers_f: CACHED_POWERS_F_32, cached_powers_e: CACHED_POWERS_E_32, min_power: (-36), }; unsafe { dtoa(buf, self) } } } impl private::Sealed for f64 { #[inline] #[cfg_attr(feature = "no-panic", no_panic)] fn is_nonfinite(self) -> bool { const EXP_MASK: u64 = 0x7ff0000000000000; let bits = self.to_bits(); bits & EXP_MASK == EXP_MASK } #[cold] #[cfg_attr(feature = "no-panic", no_panic)] fn format_nonfinite(self) -> &'static str { const MANTISSA_MASK: u64 = 0x000fffffffffffff; const SIGN_MASK: u64 = 0x8000000000000000; let bits = self.to_bits(); if bits & MANTISSA_MASK != 0 { NAN } else if bits & SIGN_MASK != 0 { NEG_INFINITY } else { INFINITY } } #[inline] fn write(self, buf: &mut Buffer) -> &str { dtoa! { floating_type: f64, significand_type: u64, exponent_type: isize, diy_significand_size: 64, significand_size: 52, exponent_bias: 0x3FF, mask_type: u64, exponent_mask: 0x7FF0000000000000, significand_mask: 0x000FFFFFFFFFFFFF, hidden_bit: 0x0010000000000000, cached_powers_f: CACHED_POWERS_F_64, cached_powers_e: CACHED_POWERS_E_64, min_power: (-348), }; unsafe { dtoa(buf, self) } } } //////////////////////////////////////////////////////////////////////////////// const MAX_DECIMAL_PLACES: isize = 324; static DEC_DIGITS_LUT: [u8; 200] = *b"\ 0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ 6061626364656667686970717273747576777879\ 8081828384858687888990919293949596979899"; // 10^-36, 10^-28, ..., 10^52 #[rustfmt::skip] static CACHED_POWERS_F_32: [u32; 12] = [ 0xaa242499, 0xfd87b5f3, 0xbce50865, 0x8cbccc09, 0xd1b71759, 0x9c400000, 0xe8d4a510, 0xad78ebc6, 0x813f3979, 0xc097ce7c, 0x8f7e32ce, 0xd5d238a5, ]; #[rustfmt::skip] static CACHED_POWERS_E_32: [i16; 12] = [ -151, -125, -98, -71, -45, -18, 8, 35, 62, 88, 115, 141, ]; // 10^-348, 10^-340, ..., 10^340 #[rustfmt::skip] static CACHED_POWERS_F_64: [u64; 87] = [ 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76, 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df, 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c, 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5, 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57, 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7, 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e, 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996, 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126, 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053, 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f, 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b, 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06, 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb, 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000, 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984, 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068, 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8, 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758, 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85, 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d, 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25, 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2, 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a, 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410, 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129, 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85, 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841, 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b, ]; #[rustfmt::skip] static CACHED_POWERS_E_64: [i16; 87] = [ -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066, ];
rust
Apache-2.0
902d0d7e180457b9997b8ef3a67e68ee2e78a5b1
2026-01-04T20:18:53.491463Z
false
dtolnay/dtoa
https://github.com/dtolnay/dtoa/blob/902d0d7e180457b9997b8ef3a67e68ee2e78a5b1/src/diyfp.rs
src/diyfp.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // --- // // The C++ implementation preserved here in comments is licensed as follows: // // Tencent is pleased to support the open source community by making RapidJSON // available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All // rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License // at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. use core::ops::{Mul, Sub}; #[cfg(feature = "no-panic")] use no_panic::no_panic; #[derive(Copy, Clone, Debug)] pub struct DiyFp<F, E> { pub f: F, pub e: E, } impl<F, E> DiyFp<F, E> { #[cfg_attr(feature = "no-panic", no_panic)] pub fn new(f: F, e: E) -> Self { DiyFp { f, e } } } impl<F, E> Sub for DiyFp<F, E> where F: Sub<F, Output = F>, { type Output = Self; #[cfg_attr(feature = "no-panic", no_panic)] fn sub(self, rhs: Self) -> Self { DiyFp { f: self.f - rhs.f, e: self.e, } } } impl Mul for DiyFp<u32, i32> { type Output = Self; #[cfg_attr(feature = "no-panic", no_panic)] fn mul(self, rhs: Self) -> Self { let mut tmp = self.f as u64 * rhs.f as u64; tmp += 1u64 << 31; // mult_round DiyFp { f: (tmp >> 32) as u32, e: self.e + rhs.e + 32, } } } impl Mul for DiyFp<u64, isize> { type Output = Self; #[cfg_attr(feature = "no-panic", no_panic)] fn mul(self, rhs: Self) -> Self { let m32 = 0xFFFFFFFFu64; let a = self.f >> 32; let b = self.f & m32; let c = rhs.f >> 32; let d = rhs.f & m32; let ac = a * c; let bc = b * c; let ad = a * d; let bd = b * d; let mut tmp = (bd >> 32) + (ad & m32) + (bc & m32); tmp += 1u64 << 31; // mult_round DiyFp { f: ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e: self.e + rhs.e + 64, } } } macro_rules! diyfp { ( floating_type: $fty:ty, significand_type: $sigty:ty, exponent_type: $expty:ty, diy_significand_size: $diy_significand_size:expr, significand_size: $significand_size:expr, exponent_bias: $exponent_bias:expr, mask_type: $mask_type:ty, exponent_mask: $exponent_mask:expr, significand_mask: $significand_mask:expr, hidden_bit: $hidden_bit:expr, cached_powers_f: $cached_powers_f:expr, cached_powers_e: $cached_powers_e:expr, min_power: $min_power:expr, ) => { type DiyFp = diyfp::DiyFp<$sigty, $expty>; impl DiyFp { // Preconditions: // `d` must have a positive sign and must not be infinity or NaN. /* explicit DiyFp(double d) { union { double d; uint64_t u64; } u = { d }; int biased_e = static_cast<int>((u.u64 & kDpExponentMask) >> kDpSignificandSize); uint64_t significand = (u.u64 & kDpSignificandMask); if (biased_e != 0) { f = significand + kDpHiddenBit; e = biased_e - kDpExponentBias; } else { f = significand; e = kDpMinExponent + 1; } } */ #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn from(d: $fty) -> Self { let u: $mask_type = <$fty>::to_bits(d); let biased_e = ((u & $exponent_mask) >> $significand_size) as $expty; let significand = u & $significand_mask; if biased_e != 0 { DiyFp { f: significand + $hidden_bit, e: biased_e - $exponent_bias - $significand_size, } } else { DiyFp { f: significand, e: 1 - $exponent_bias - $significand_size, } } } // Normalizes so that the highest bit of the diy significand is 1. /* DiyFp Normalize() const { DiyFp res = *this; while (!(res.f & (static_cast<uint64_t>(1) << 63))) { res.f <<= 1; res.e--; } return res; } */ #[cfg_attr(feature = "no-panic", no_panic)] fn normalize(self) -> DiyFp { let mut res = self; while (res.f & (1 << ($diy_significand_size - 1))) == 0 { res.f <<= 1; res.e -= 1; } res } // Normalizes so that the highest bit of the diy significand is 1. // // Precondition: // `self.f` must be no more than 2 bits longer than the f64 significand. /* DiyFp NormalizeBoundary() const { DiyFp res = *this; while (!(res.f & (kDpHiddenBit << 1))) { res.f <<= 1; res.e--; } res.f <<= (kDiySignificandSize - kDpSignificandSize - 2); res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2); return res; } */ #[cfg_attr(feature = "no-panic", no_panic)] fn normalize_boundary(self) -> DiyFp { let mut res = self; while (res.f & $hidden_bit << 1) == 0 { res.f <<= 1; res.e -= 1; } res.f <<= $diy_significand_size - $significand_size - 2; res.e -= $diy_significand_size - $significand_size - 2; res } // Normalizes `self - e` and `self + e` where `e` is half of the least // significant digit of `self`. The plus is normalized so that the highest // bit of the diy significand is 1. The minus is normalized so that it has // the same exponent as the plus. // // Preconditions: // `self` must have been returned directly from `DiyFp::from_f64`. // `self.f` must not be zero. /* void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const { DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary(); DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1); mi.f <<= mi.e - pl.e; mi.e = pl.e; *plus = pl; *minus = mi; } */ #[cfg_attr(feature = "no-panic", no_panic)] fn normalized_boundaries(self) -> (DiyFp, DiyFp) { let pl = DiyFp::new((self.f << 1) + 1, self.e - 1).normalize_boundary(); let mut mi = if self.f == $hidden_bit { DiyFp::new((self.f << 2) - 1, self.e - 2) } else { DiyFp::new((self.f << 1) - 1, self.e - 1) }; mi.f <<= mi.e - pl.e; mi.e = pl.e; (mi, pl) } } /* inline DiyFp GetCachedPower(int e, int* K) { //int k = static_cast<int>(ceil((-61 - e) * 0.30102999566398114)) + 374; double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive int k = static_cast<int>(dk); if (dk - k > 0.0) k++; unsigned index = static_cast<unsigned>((k >> 3) + 1); *K = -(-348 + static_cast<int>(index << 3)); // decimal exponent no need lookup table return GetCachedPowerByIndex(index); } */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] fn get_cached_power(e: $expty) -> (DiyFp, isize) { let dk = (3 - $diy_significand_size - e) as f64 * 0.30102999566398114f64 - ($min_power + 1) as f64; let mut k = dk as isize; if dk - k as f64 > 0.0 { k += 1; } let index = ((k >> 3) + 1) as usize; let k = -($min_power + (index << 3) as isize); ( DiyFp::new(*unsafe { $cached_powers_f.get_unchecked(index) }, *unsafe { $cached_powers_e.get_unchecked(index) } as $expty), k, ) } }; }
rust
Apache-2.0
902d0d7e180457b9997b8ef3a67e68ee2e78a5b1
2026-01-04T20:18:53.491463Z
false
dtolnay/dtoa
https://github.com/dtolnay/dtoa/blob/902d0d7e180457b9997b8ef3a67e68ee2e78a5b1/src/dtoa.rs
src/dtoa.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // --- // // The C++ implementation preserved here in comments is licensed as follows: // // Tencent is pleased to support the open source community by making RapidJSON // available. // // Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All // rights reserved. // // Licensed under the MIT License (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License // at // // http://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. use core::ptr; #[cfg(feature = "no-panic")] use no_panic::no_panic; /* inline unsigned CountDecimalDigit32(uint32_t n) { // Simple pure C++ implementation was faster than __builtin_clz version in this situation. if (n < 10) return 1; if (n < 100) return 2; if (n < 1000) return 3; if (n < 10000) return 4; if (n < 100000) return 5; if (n < 1000000) return 6; if (n < 10000000) return 7; if (n < 100000000) return 8; // Will not reach 10 digits in DigitGen() //if (n < 1000000000) return 9; //return 10; return 9; } */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] pub fn count_decimal_digit32(n: u32) -> usize { if n < 10 { 1 } else if n < 100 { 2 } else if n < 1000 { 3 } else if n < 10000 { 4 } else if n < 100000 { 5 } else if n < 1000000 { 6 } else if n < 10000000 { 7 } else if n < 100000000 { 8 } // Will not reach 10 digits in digit_gen() else { 9 } } /* inline char* WriteExponent(int K, char* buffer) { if (K < 0) { *buffer++ = '-'; K = -K; } if (K >= 100) { *buffer++ = static_cast<char>('0' + static_cast<char>(K / 100)); K %= 100; const char* d = GetDigitsLut() + K * 2; *buffer++ = d[0]; *buffer++ = d[1]; } else if (K >= 10) { const char* d = GetDigitsLut() + K * 2; *buffer++ = d[0]; *buffer++ = d[1]; } else *buffer++ = static_cast<char>('0' + static_cast<char>(K)); return buffer; } */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn write_exponent(mut k: isize, mut buffer: *mut u8) -> *mut u8 { if k < 0 { *buffer = b'-'; buffer = buffer.add(1); k = -k; } if k >= 100 { *buffer = b'0' + (k / 100) as u8; k %= 100; let d = crate::DEC_DIGITS_LUT.as_ptr().offset(k * 2); ptr::copy_nonoverlapping(d, buffer.add(1), 2); buffer.add(3) } else if k >= 10 { let d = crate::DEC_DIGITS_LUT.as_ptr().offset(k * 2); ptr::copy_nonoverlapping(d, buffer, 2); buffer.add(2) } else { *buffer = b'0' + k as u8; buffer.add(1) } } /* inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) { const int kk = length + k; // 10^(kk-1) <= v < 10^kk */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] pub unsafe fn prettify(buffer: *mut u8, length: isize, k: isize) -> *mut u8 { let kk = length + k; // 10^(kk-1) <= v < 10^kk /* if (0 <= k && kk <= 21) { // 1234e7 -> 12340000000 for (int i = length; i < kk; i++) buffer[i] = '0'; buffer[kk] = '.'; buffer[kk + 1] = '0'; return &buffer[kk + 2]; } */ if 0 <= k && kk <= 21 { // 1234e7 -> 12340000000 for i in length..kk { *buffer.offset(i) = b'0'; } *buffer.offset(kk) = b'.'; *buffer.offset(kk + 1) = b'0'; buffer.offset(kk + 2) } /* else if (0 < kk && kk <= 21) { // 1234e-2 -> 12.34 std::memmove(&buffer[kk + 1], &buffer[kk], static_cast<size_t>(length - kk)); buffer[kk] = '.'; if (0 > k + maxDecimalPlaces) { // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1 // Remove extra trailing zeros (at least one) after truncation. for (int i = kk + maxDecimalPlaces; i > kk + 1; i--) if (buffer[i] != '0') return &buffer[i + 1]; return &buffer[kk + 2]; // Reserve one zero } else return &buffer[length + 1]; } */ else if 0 < kk && kk <= 21 { // 1234e-2 -> 12.34 ptr::copy( buffer.offset(kk), buffer.offset(kk + 1), (length - kk) as usize, ); *buffer.offset(kk) = b'.'; if 0 > k + crate::MAX_DECIMAL_PLACES { // When MAX_DECIMAL_PLACES = 2, 1.2345 -> 1.23, 1.102 -> 1.1 // Remove extra trailing zeros (at least one) after truncation. for i in (kk + 2..kk + crate::MAX_DECIMAL_PLACES + 1).rev() { if *buffer.offset(i) != b'0' { return buffer.offset(i + 1); } } buffer.offset(kk + 2) // Reserve one zero } else { buffer.offset(length + 1) } } /* else if (-6 < kk && kk <= 0) { // 1234e-6 -> 0.001234 const int offset = 2 - kk; std::memmove(&buffer[offset], &buffer[0], static_cast<size_t>(length)); buffer[0] = '0'; buffer[1] = '.'; for (int i = 2; i < offset; i++) buffer[i] = '0'; if (length - kk > maxDecimalPlaces) { // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1 // Remove extra trailing zeros (at least one) after truncation. for (int i = maxDecimalPlaces + 1; i > 2; i--) if (buffer[i] != '0') return &buffer[i + 1]; return &buffer[3]; // Reserve one zero } else return &buffer[length + offset]; } */ else if -6 < kk && kk <= 0 { // 1234e-6 -> 0.001234 let offset = 2 - kk; ptr::copy(buffer, buffer.offset(offset), length as usize); *buffer = b'0'; *buffer.add(1) = b'.'; for i in 2..offset { *buffer.offset(i) = b'0'; } if length - kk > crate::MAX_DECIMAL_PLACES { // When MAX_DECIMAL_PLACES = 2, 0.123 -> 0.12, 0.102 -> 0.1 // Remove extra trailing zeros (at least one) after truncation. for i in (3..crate::MAX_DECIMAL_PLACES + 2).rev() { if *buffer.offset(i) != b'0' { return buffer.offset(i + 1); } } buffer.add(3) // Reserve one zero } else { buffer.offset(length + offset) } } /* else if (kk < -maxDecimalPlaces) { // Truncate to zero buffer[0] = '0'; buffer[1] = '.'; buffer[2] = '0'; return &buffer[3]; } */ else if kk < -crate::MAX_DECIMAL_PLACES { *buffer = b'0'; *buffer.add(1) = b'.'; *buffer.add(2) = b'0'; buffer.add(3) } /* else if (length == 1) { // 1e30 buffer[1] = 'e'; return WriteExponent(kk - 1, &buffer[2]); } */ else if length == 1 { // 1e30 *buffer.add(1) = b'e'; write_exponent(kk - 1, buffer.add(2)) } /* else { // 1234e30 -> 1.234e33 std::memmove(&buffer[2], &buffer[1], static_cast<size_t>(length - 1)); buffer[1] = '.'; buffer[length + 1] = 'e'; return WriteExponent(kk - 1, &buffer[0 + length + 2]); } */ else { // 1234e30 -> 1.234e33 ptr::copy(buffer.add(1), buffer.add(2), (length - 1) as usize); *buffer.add(1) = b'.'; *buffer.offset(length + 1) = b'e'; write_exponent(kk - 1, buffer.offset(length + 2)) } } macro_rules! dtoa { ( floating_type: $fty:ty, significand_type: $sigty:ty, exponent_type: $expty:ty, $($diyfp_param:ident: $diyfp_value:tt,)* ) => { diyfp! { floating_type: $fty, significand_type: $sigty, exponent_type: $expty, $($diyfp_param: $diyfp_value,)* }; /* inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) { while (rest < wp_w && delta - rest >= ten_kappa && (rest + ten_kappa < wp_w || /// closer wp_w - rest > rest + ten_kappa - wp_w)) { buffer[len - 1]--; rest += ten_kappa; } } */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn grisu_round(buffer: *mut u8, len: isize, delta: $sigty, mut rest: $sigty, ten_kappa: $sigty, wp_w: $sigty) { while rest < wp_w && delta - rest >= ten_kappa && (rest + ten_kappa < wp_w || // closer wp_w - rest > rest + ten_kappa - wp_w) { *buffer.offset(len - 1) -= 1; rest += ten_kappa; } } /* inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) { static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; const DiyFp one(uint64_t(1) << -Mp.e, Mp.e); const DiyFp wp_w = Mp - W; uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e); uint64_t p2 = Mp.f & (one.f - 1); unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9] *len = 0; */ // Returns length and k. #[inline] #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn digit_gen(w: DiyFp, mp: DiyFp, mut delta: $sigty, buffer: *mut u8, mut k: isize) -> (isize, isize) { static POW10: [$sigty; 10] = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 ]; let one = DiyFp::new(1 << -mp.e, mp.e); let wp_w = mp - w; let mut p1 = (mp.f >> -one.e) as u32; let mut p2 = mp.f & (one.f - 1); let mut kappa = dtoa::count_decimal_digit32(p1); // kappa in [0, 9] let mut len = 0; /* while (kappa > 0) { uint32_t d = 0; switch (kappa) { case 9: d = p1 / 100000000; p1 %= 100000000; break; case 8: d = p1 / 10000000; p1 %= 10000000; break; case 7: d = p1 / 1000000; p1 %= 1000000; break; case 6: d = p1 / 100000; p1 %= 100000; break; case 5: d = p1 / 10000; p1 %= 10000; break; case 4: d = p1 / 1000; p1 %= 1000; break; case 3: d = p1 / 100; p1 %= 100; break; case 2: d = p1 / 10; p1 %= 10; break; case 1: d = p1; p1 = 0; break; default:; } if (d || *len) buffer[(*len)++] = static_cast<char>('0' + static_cast<char>(d)); kappa--; uint64_t tmp = (static_cast<uint64_t>(p1) << -one.e) + p2; if (tmp <= delta) { *K += kappa; GrisuRound(buffer, *len, delta, tmp, static_cast<uint64_t>(kPow10[kappa]) << -one.e, wp_w.f); return; } } */ while kappa > 0 { let mut d = 0u32; match kappa { 9 => { d = p1 / 100000000; p1 %= 100000000; } 8 => { d = p1 / 10000000; p1 %= 10000000; } 7 => { d = p1 / 1000000; p1 %= 1000000; } 6 => { d = p1 / 100000; p1 %= 100000; } 5 => { d = p1 / 10000; p1 %= 10000; } 4 => { d = p1 / 1000; p1 %= 1000; } 3 => { d = p1 / 100; p1 %= 100; } 2 => { d = p1 / 10; p1 %= 10; } 1 => { d = p1; p1 = 0; } _ => {} } if d != 0 || len != 0 { *buffer.offset(len) = b'0' + d as u8; len += 1; } kappa -= 1; let tmp = ((p1 as $sigty) << -one.e) + p2; if tmp <= delta { k += kappa as isize; grisu_round(buffer, len, delta, tmp, *POW10.get_unchecked(kappa) << -one.e, wp_w.f); return (len, k); } } // kappa = 0 /* for (;;) { p2 *= 10; delta *= 10; char d = static_cast<char>(p2 >> -one.e); if (d || *len) buffer[(*len)++] = static_cast<char>('0' + d); p2 &= one.f - 1; kappa--; if (p2 < delta) { *K += kappa; int index = -static_cast<int>(kappa); GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast<int>(kappa)] : 0)); return; } } */ loop { p2 *= 10; delta *= 10; let d = (p2 >> -one.e) as u8; if d != 0 || len != 0 { *buffer.offset(len) = b'0' + d; len += 1; } p2 &= one.f - 1; kappa = kappa.wrapping_sub(1); if p2 < delta { k += kappa as isize; let index = -(kappa as isize); grisu_round( buffer, len, delta, p2, one.f, wp_w.f * if index < 9 { *POW10.get_unchecked(-(kappa as isize) as usize) } else { 0 }, ); return (len, k); } } } /* inline void Grisu2(double value, char* buffer, int* length, int* K) { const DiyFp v(value); DiyFp w_m, w_p; v.NormalizedBoundaries(&w_m, &w_p); const DiyFp c_mk = GetCachedPower(w_p.e, K); const DiyFp W = v.Normalize() * c_mk; DiyFp Wp = w_p * c_mk; DiyFp Wm = w_m * c_mk; Wm.f++; Wp.f--; DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K); } */ // Returns length and k. #[inline] #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn grisu2(value: $fty, buffer: *mut u8) -> (isize, isize) { let v = DiyFp::from(value); let (w_m, w_p) = v.normalized_boundaries(); let (c_mk, k) = get_cached_power(w_p.e); let w = v.normalize() * c_mk; let mut wp = w_p * c_mk; let mut wm = w_m * c_mk; wm.f += 1; wp.f -= 1; digit_gen(w, wp, wp.f - wm.f, buffer, k) } /* inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) { RAPIDJSON_ASSERT(maxDecimalPlaces >= 1); Double d(value); if (d.IsZero()) { if (d.Sign()) *buffer++ = '-'; // -0.0, Issue #289 buffer[0] = '0'; buffer[1] = '.'; buffer[2] = '0'; return &buffer[3]; } else { if (value < 0) { *buffer++ = '-'; value = -value; } int length, K; Grisu2(value, buffer, &length, &K); return Prettify(buffer, length, K, maxDecimalPlaces); } } */ #[inline] #[cfg_attr(feature = "no-panic", no_panic)] unsafe fn dtoa(buf: &mut Buffer, mut value: $fty) -> &str { if value == 0.0 { if value.is_sign_negative() { "-0.0" } else { "0.0" } } else { let start = buf.bytes.as_mut_ptr().cast::<u8>(); let mut buf_ptr = start; if value < 0.0 { *buf_ptr = b'-'; buf_ptr = buf_ptr.add(1); value = -value; } let (length, k) = grisu2(value, buf_ptr); let end = dtoa::prettify(buf_ptr, length, k); let len = end as usize - start as usize; str::from_utf8_unchecked(slice::from_raw_parts(start, len)) } } }; }
rust
Apache-2.0
902d0d7e180457b9997b8ef3a67e68ee2e78a5b1
2026-01-04T20:18:53.491463Z
false
dtolnay/dtoa
https://github.com/dtolnay/dtoa/blob/902d0d7e180457b9997b8ef3a67e68ee2e78a5b1/tests/test.rs
tests/test.rs
#![allow( clippy::approx_constant, clippy::unreadable_literal, clippy::unseparated_literal_suffix )] use std::{f32, f64}; #[test] fn test_f64() { test_write(1.234e20f64, "123400000000000000000.0"); test_write(1.234e21f64, "1.234e21"); test_write(2.71828f64, "2.71828"); test_write(0.0f64, "0.0"); test_write(-0.0f64, "-0.0"); test_write(1.1e128f64, "1.1e128"); test_write(1.1e-64f64, "1.1e-64"); test_write(2.718281828459045f64, "2.718281828459045"); test_write(5e-324f64, "5e-324"); test_write(f64::MAX, "1.7976931348623157e308"); test_write(f64::MIN, "-1.7976931348623157e308"); } #[test] fn test_f32() { test_write(1.234e20f32, "123400000000000000000.0"); test_write(1.234e21f32, "1.234e21"); test_write(2.71828f32, "2.71828"); test_write(0.0f32, "0.0"); test_write(-0.0f32, "-0.0"); test_write(1.1e32f32, "1.1e32"); test_write(1.1e-32f32, "1.1e-32"); test_write(2.7182817f32, "2.7182817"); test_write(1e-45f32, "1e-45"); test_write(f32::MAX, "3.4028235e38"); test_write(f32::MIN, "-3.4028235e38"); } fn test_write<F: dtoa::Float>(value: F, expected: &'static str) { let mut buffer = dtoa::Buffer::new(); let string = buffer.format(value); assert_eq!(string, expected); }
rust
Apache-2.0
902d0d7e180457b9997b8ef3a67e68ee2e78a5b1
2026-01-04T20:18:53.491463Z
false
dtolnay/dtoa
https://github.com/dtolnay/dtoa/blob/902d0d7e180457b9997b8ef3a67e68ee2e78a5b1/benches/bench.rs
benches/bench.rs
use criterion::{criterion_group, criterion_main, Criterion}; use std::fmt::Display; use std::hint; use std::io::Write; use std::{f32, f64}; fn do_bench(c: &mut Criterion, group_name: &str, float: impl dtoa::Float + Display) { let mut group = c.benchmark_group(group_name); group.bench_function("dtoa", |b| { let mut buf = dtoa::Buffer::new(); b.iter(move || { let float = hint::black_box(float); let formatted = buf.format_finite(float); hint::black_box(formatted); }); }); group.bench_function("std::fmt", |b| { let mut buf = Vec::with_capacity(20); b.iter(|| { buf.clear(); let float = hint::black_box(float); write!(&mut buf, "{float}").unwrap(); hint::black_box(buf.as_slice()); }); }); group.finish(); } fn bench(c: &mut Criterion) { do_bench(c, "f64[0]", 0f64); do_bench(c, "f64[short]", 0.1234f64); do_bench(c, "f64[e]", f64::consts::E); do_bench(c, "f64[max]", f64::MAX); do_bench(c, "f32[0]", 0f32); do_bench(c, "f32[short]", 0.1234f32); do_bench(c, "f32[e]", f32::consts::E); do_bench(c, "f32[max]", f32::MAX); } criterion_group!(benches, bench); criterion_main!(benches);
rust
Apache-2.0
902d0d7e180457b9997b8ef3a67e68ee2e78a5b1
2026-01-04T20:18:53.491463Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/consul.rs
src/consul.rs
use std::{collections::HashSet, future::Future, time::Duration}; use anyhow::{anyhow, bail, Context, Result}; use base64::prelude::{Engine as _, BASE64_STANDARD}; use futures::future::join_all; use reqwest::{ header::{HeaderMap, HeaderName, HeaderValue}, StatusCode, Url, }; use serde::{Deserialize, Serialize}; use tokio::{ task::{JoinError, JoinHandle}, time::interval, }; use tokio_util::sync::CancellationToken; use tracing::{error, info, trace, warn}; use uuid::Uuid; use wireguard_keys::Pubkey; use crate::{wireguard::WgPeer, CONSUL_TTL}; /// Allows for gracefully telling a background task to shut down and to then join it. #[must_use] pub struct TaskCancellator { join_handle: Option<JoinHandle<()>>, token: CancellationToken, } impl TaskCancellator { pub fn new(join_handle: JoinHandle<()>, token: CancellationToken) -> Self { Self { join_handle: Some(join_handle), token, } } #[tracing::instrument(skip(self))] pub async fn cancel(mut self) -> Result<(), JoinError> { // Tell the task to shut down. self.token.cancel(); // Awaiting the join handle consumes the future and thereby moves it out of `Self`. It's // not allowed to move out of types which implement `Drop` and so to work around this we // wrap the future in `Option`. if let Some(join_handle) = self.join_handle.take() { return join_handle.await; } Ok(()) } } /// Ensure that the managed task shuts down if `Self` is dropped. /// /// This ensures that we don't keep tasks running in the background if the main tasks's inner loop /// performs an early return. impl Drop for TaskCancellator { fn drop(&mut self) { self.token.cancel(); } } #[derive(Clone, Debug)] pub struct ConsulClient { pub http_client: reqwest::Client, api_base_url: Url, pub kv_api_base_url: Url, } #[derive(Debug, Eq, PartialEq, Hash, Deserialize)] #[serde(rename_all = "PascalCase")] pub struct ConsulKvGet { pub create_index: u64, pub flags: u64, pub key: String, pub lock_index: u64, pub modify_index: u64, pub value: String, } #[derive(Serialize)] #[serde(rename_all = "lowercase")] enum SessionInvalidationBehavior { /// Delete the keys corresponding to the locks held by this session when the session is /// invalidated. Delete, } #[derive(Copy, Clone)] enum SessionDuration { Seconds(u32), } impl TryFrom<Duration> for SessionDuration { type Error = anyhow::Error; fn try_from(value: Duration) -> Result<Self> { // Consul only supports durations of up to 86400 seconds. let secs = value.as_secs(); if secs > 86400 { bail!("Tried to convert a duration longer than 24 hours into SessionDuration"); } Ok(SessionDuration::Seconds(secs as u32)) } } impl Serialize for SessionDuration { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(&match self { Self::Seconds(s) => format!("{s}s"), }) } } #[derive(Serialize)] #[serde(rename_all = "PascalCase")] struct CreateSession { name: String, behavior: SessionInvalidationBehavior, /// How long the session will survive without being renewed. #[serde(rename = "TTL")] ttl: SessionDuration, } #[derive(Deserialize)] struct CreateSessionResponse { #[serde(rename = "ID")] id: Uuid, } impl ConsulClient { pub fn new( consul_address: Url, consul_prefix: &str, consul_token: Option<&str>, ) -> Result<ConsulClient> { // Make sure the consul prefix ends with a /. let consul_prefix = if consul_prefix.ends_with('/') { consul_prefix.to_string() } else { format!("{}/", consul_prefix) }; let kv_api_base_url = consul_address .join("v1/")? .join("kv/")? .join(&consul_prefix)?; let client_builder = reqwest::Client::builder(); let client_builder = if let Some(secret_token) = consul_token { let mut headers = HeaderMap::new(); headers.insert( HeaderName::from_static("X-Consul-Token"), HeaderValue::from_str(secret_token)?, ); client_builder.default_headers(headers) } else { client_builder }; let client = client_builder.build()?; Ok(ConsulClient { http_client: client, api_base_url: consul_address, kv_api_base_url, }) } /// # Read all peer configs /// /// This reads the WireGuard peer configs from all available Consul DCs and merges the sets /// together. #[tracing::instrument(skip(self))] pub async fn get_peers(&self) -> Result<HashSet<WgPeer>> { let dcs = self .http_client .get(self.api_base_url.join("v1/catalog/datacenters")?) .send() .await? .error_for_status()? .json::<Vec<String>>() .await?; let mut peers = HashSet::new(); for dc_peers in join_all(dcs.iter().map(|dc| self.get_peers_for_dc(dc))).await { let dc_peers = dc_peers?; peers.extend(dc_peers); } Ok(peers) } /// # Read peers for a single DC /// /// This will read the all of the WireGuard peers from a given Consul DC. This should only be /// called by [`Self::get_peers`]. #[tracing::instrument(skip(self))] async fn get_peers_for_dc(&self, dc: &str) -> Result<HashSet<WgPeer>> { // When the Consul server which is the Raft leader is restarted all KV reads by default // return 500 errors until a new Raft leader is elected. For our usecase it's fine if the // read value is a bit stale though, so prevent spurious errors by always performing stale // reads. let mut peers_url = self.kv_api_base_url.join("peers/")?; peers_url .query_pairs_mut() .append_pair("recurse", "true") .append_pair("dc", dc) .append_pair("stale", "1"); let resp = self .http_client .get(peers_url) .send() .await? .error_for_status(); match resp { Ok(resp) => { let kv_get: HashSet<ConsulKvGet> = resp.json().await?; let wgpeers: HashSet<_> = kv_get .into_iter() .map(|x| { let decoded = &BASE64_STANDARD .decode(x.value) .expect("Can't decode base64"); serde_json::from_slice(decoded) .expect("Can't interpret JSON out of decoded base64") }) .collect(); Ok(wgpeers) } Err(resp) => { if resp.status() == Some(StatusCode::NOT_FOUND) { return Ok(HashSet::new()); } Err(anyhow!(resp)) } } } /// # Create a Consul session /// /// This starts a background task which renews the session based on the given session TTL. If /// renewing the session fails, the passed in cancellation token is cancelled. On cancellation /// the keys that locks are held for are deleted. /// /// See [`ConsulSession`] for more information. #[tracing::instrument(skip(self, parent_token))] pub async fn create_session( &self, public_key: Pubkey, parent_token: CancellationToken, ) -> Result<ConsulSession> { let url = self.api_base_url.join("v1/session/create")?; let res = self .http_client .put(url) .json(&CreateSession { name: format!("wiresmith-{}", public_key.to_base64_urlsafe()), behavior: SessionInvalidationBehavior::Delete, ttl: CONSUL_TTL.try_into()?, }) .send() .await? .error_for_status()? .json::<CreateSessionResponse>() .await?; let session_token = CancellationToken::new(); let join_handle = tokio::spawn( session_handler(self.clone(), session_token.clone(), parent_token, res.id) .context("failed to create Consul session handler")?, ); trace!("Created Consul session with id {}", res.id); Ok(ConsulSession { client: self.clone(), id: res.id, cancellator: TaskCancellator::new(join_handle, session_token), }) } } /// # Create a background task maintaining a Consul session /// /// This function returns a future which will renew the given Consul session according to the /// hardcoded session TTL (currently 15 seconds). The returned future is expected to be spawned as /// a Tokio task. /// /// The future will continue maintaining the session until either the `session_token` /// [`CancellationToken`] is cancelled, in which case we will explicitly invalidate the session, or /// until the session is invalidated by a third party, in which case the `parent_token` will be /// cancelled to let the rest of the application know that the session is no longer valid. fn session_handler( client: ConsulClient, session_token: CancellationToken, parent_token: CancellationToken, session_id: Uuid, ) -> Result<impl Future<Output = ()> + Send> { // We construct the URLs first so we can return an error before the task is even spawned. let session_id = session_id.to_string(); let renewal_url = client .api_base_url .join("v1/session/renew/") .context("failed to build session renewal URL")? .join(&session_id) .context("failed to build session renewal URL")?; let destroy_url = client .api_base_url .join("v1/session/destroy/") .context("failed to build session destroy URL")? .join(&session_id) .context("failed to build session destroy URL")?; Ok(async move { // Renew the session at 2 times the TTL. let mut interval = interval(CONSUL_TTL / 2); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { // Wait for either cancellation or an interval tick to have passed. tokio::select! { _ = session_token.cancelled() => { trace!("Consul session handler was cancelled"); break; }, _ = interval.tick() => {}, }; trace!("Renewing Consul session"); let res = client .http_client .put(renewal_url.clone()) .send() .await .and_then(|res| res.error_for_status()); if let Err(err) = res { error!("Renewing Consul session failed, aborting: {err:?}"); parent_token.cancel(); return; } } trace!("Destroying Consul session"); let res = client .http_client .put(destroy_url) .send() .await .and_then(|res| res.error_for_status()); if let Err(err) = res { warn!("Destroying Consul session failed: {err:?}"); } }) } /// # An active Consul session /// /// Sessions are a mechanism provided by Consul to allow for implementing distributed locks and /// TTL'd keys in the Consul key/value store. /// /// When a session is created you specify a TTL that the session is valid for unless it's renewed. /// The session ID can then be used to acquire locks in the key/value store that belongs to that /// session. If the session is either explicitly invalidated or is not renewed within the given TTL /// the lock is invalidated and depending on the how the session was created the keys for which /// locks are held are deleted. /// /// [`ConsulClient::create_session`] creates a session with a given TTL, using the deletion /// invalidation behavior, and accepts a parent [`CancellationToken`] which will be cancelled if /// the session is invalidated. /// /// This struct represents a Consul session which is actively being renewed by a spawned background /// task. If renewing the session fails for any reason (either because the session was invalidated /// by some other mechanism or because we can no longer access the Consul API) the background task /// cancels the [`CancellationToken`] that it was passed in to prevent any further work from being /// done with the session no longer being valid. pub struct ConsulSession { client: ConsulClient, id: Uuid, cancellator: TaskCancellator, } impl ConsulSession { /// # Cancel the session /// /// This will cause the background task maintaining the session to exit its loop and invalidate /// the session, thus invalidating all locks belonging to it. #[tracing::instrument(skip(self))] pub async fn cancel(self) -> Result<(), JoinError> { // The background task being cancelled here is defined in `session_handler`. self.cancellator.cancel().await } /// # Add own WireGuard peer config /// /// This locks the key with this session's ID to ensure that the key is deleted if the session /// is invalidated. /// /// A background task is spawned that ensures that the key continues existing. If it cannot be /// fetched the parent [`CancellationToken`] is cancelled. #[tracing::instrument(skip(self, wgpeer, parent_token))] pub async fn put_config( &self, wgpeer: &WgPeer, parent_token: CancellationToken, ) -> Result<TaskCancellator> { let peer_url = self .client .kv_api_base_url .join("peers/")? .join(&wgpeer.public_key.to_base64_urlsafe())?; let mut put_url = peer_url.clone(); put_url .query_pairs_mut() .append_pair("acquire", &self.id.to_string()); // KV PUT requests return a boolean saying whether the upsert attempt was successful. If // another session already holds the lock this request will fail. let got_lock = self .client .http_client .put(put_url) .json(wgpeer) .send() .await? .error_for_status() .context("failed to put node config into Consul")? .json::<bool>() .await .context("Failed to parse Consul KV put response")?; if !got_lock { bail!("Did not get Consul lock for node config"); } info!("Wrote node config into Consul"); let client = self.client.clone(); let config_token = CancellationToken::new(); let join_handle = tokio::spawn(config_handler( client, self.id, peer_url, config_token.clone(), parent_token, )); Ok(TaskCancellator::new(join_handle, config_token)) } } /// # Background task ensuring own config key exists /// /// Makes sure that the config key we created still exists by long polling. If getting it fails for /// whatever reason we trigger the parent [`CancellationToken`] to cancel since we can no longer be /// sure that we have a valid locked session. If the key exists but locked by the wrong session we /// also trigger a cancellation. async fn config_handler( client: ConsulClient, session_id: Uuid, peer_url: Url, config_token: CancellationToken, parent_token: CancellationToken, ) { // Consul documents that stale results are generally consistent within 50 ms, so let's sleep // for that amount of time before we start checking to try to prevent spurious errors returned. // // We still perform 5 retries at 1 second intervals since the maximum delay is theoretically // unbounded. tokio::time::sleep(Duration::from_millis(50)).await; let mut failed_fetches = 0; let mut index = None; let mut interval = interval(Duration::from_secs(1)); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { // Wait for an interval tick to have passed to prevent us from hammering the server with // requests. tokio::select! { _ = config_token.cancelled() => { trace!("Consul config handler was cancelled"); break; }, _ = interval.tick() => {}, }; let res = tokio::select! { _ = config_token.cancelled() => { trace!("Consul config handler was cancelled"); break; }, res = ensure_config_exists(&client, peer_url.clone(), &mut index) => res, }; match res { Ok(owner_id) => { // Reset the failure counter on any successful response. failed_fetches = 0; // Check that the key is actually locked by us and not some other session. // Otherwise it means that something else invalidated the lock and we need to // cancel the parent task. if owner_id != session_id { error!( "Consul key is locked by {owner_id}, expected it to be us ({session_id})" ); parent_token.cancel(); break; } } Err(err) => { // Allow up to 5 API failures before we cancel the parent task and exit to deal // with spurious Consul API error when e.g. the cluster leader goes down. failed_fetches += 1; if failed_fetches >= 5 { error!("Failed to fetch own node config {failed_fetches} times, cancelling"); parent_token.cancel(); break; } error!("Could not get own node config from Consul ({failed_fetches} failed fetches): {err:?}"); continue; } }; trace!("Successfully fetched own node config from Consul"); } } /// # Consul KV store read response /// /// The Consul KV store Read Key API returns a list of objects corresponding to this struct. This /// is currently only used by `ensure_config_exists` to ensure that the key is locked by the /// expected session ID. #[derive(Deserialize)] #[serde(rename_all = "PascalCase")] struct ReadKeyResponse { session: Option<Uuid>, } /// # Ensure that a given WireGuard peer config exists /// /// The `index` parameter is used to store the Consul index which is used to allow for blocking /// reads. Consul will only respond to the request if the current index is different from the /// passed in one, or the request timed out. Users are expected to pass in a mutable reference to a /// value that defaults to `None`, and pass in references to the same value whenever the function /// is called with the same URL. /// /// Returns the session ID that holds the config locked. #[tracing::instrument(skip(client))] async fn ensure_config_exists( client: &ConsulClient, peer_url: Url, index: &mut Option<String>, ) -> Result<Uuid> { let query: &[_] = if let Some(index) = index { &[("index", index)] } else { &[] }; let res = client .http_client .get(peer_url) .query(query) .send() .await? .error_for_status()?; if let Some(new_index) = res.headers().get("X-Consul-Index") { let new_index = new_index .to_str() .context("Failed to convert new Consul index to String")? .to_string(); index.replace(new_index); }; let res = res .json::<Vec<ReadKeyResponse>>() .await .context("Failed to parse KV response")?; res.first() .context("Consul unexpectedly returned an empty array")? .session .ok_or_else(|| anyhow!("Key was not locked by any session")) }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/lib.rs
src/lib.rs
use std::time::Duration; pub mod consul; pub mod networkd; pub mod wireguard; pub const CONSUL_TTL: Duration = Duration::from_secs(15);
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/wireguard.rs
src/wireguard.rs
use std::{fmt, net::IpAddr}; use ipnet::IpNet; use serde::{Deserialize, Serialize}; use wireguard_keys::Pubkey; #[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] pub struct WgPeer { pub public_key: Pubkey, pub endpoint: String, /// The WireGuard internal IP of the peer. /// /// It should be provided with the most specific netmask as it's meant to for only that peer. /// So for IPv4, use /32 and for IPv6, use /128. pub address: IpNet, } impl WgPeer { pub fn new(public_key: Pubkey, endpoint: &str, address: IpAddr) -> Self { Self { public_key, endpoint: endpoint.to_string(), address: address.into(), } } } impl fmt::Debug for WgPeer { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("WgPeer") .field("public_key", &self.public_key.to_base64_urlsafe()) .field("endpoint", &self.endpoint) .field("address", &self.address) .finish() } }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/args.rs
src/args.rs
use std::{net::IpAddr, path::PathBuf, time::Duration}; use clap::{Parser, ValueEnum}; use ipnet::IpNet; use pnet::datalink::{self, NetworkInterface}; use reqwest::Url; #[derive(Copy, Clone, ValueEnum)] pub enum NetworkBackend { Networkd, // Wgquick } #[derive(Parser)] #[command(name = "wiresmith", author, about, version)] pub struct CliArgs { /// Consul backend socket address #[arg(long, default_value = "http://127.0.0.1:8500")] pub consul_address: Url, /// Consul secret token #[arg(long)] pub consul_token: Option<String>, /// Consul KV prefix #[arg(long, default_value = "wiresmith")] pub consul_prefix: String, /// Update period - how often to check for peer updates #[arg(short, long, default_value = "10s", value_parser = humantime::parse_duration)] pub update_period: Duration, /// WireGuard interface name #[arg(short = 'i', long, default_value = "wg0")] pub wg_interface: String, /// WireGuard UDP listen port #[arg(short = 'p', long, default_value = "51820")] pub wg_port: u16, /// Set persistent keepalive option for wireguard /// /// Set to 0 in order to disable. #[arg(short = 'k', long, default_value = "25s", value_parser = keep_alive)] pub keepalive: u64, /// Public endpoint interface name /// /// You need to provide either this or --endpoint-address. #[arg(long, required_unless_present = "endpoint_address", conflicts_with = "endpoint_address", value_parser = network_interface )] pub endpoint_interface: Option<NetworkInterface>, /// Public endpoint address /// /// Can be a hostname or IP address. /// You need to provide either this or --endpoint-interface. #[arg( long, required_unless_present = "endpoint_interface", conflicts_with = "endpoint_interface" )] pub endpoint_address: Option<String>, /// Network configuration backend #[arg(long, default_value = "networkd")] pub network_backend: NetworkBackend, /// Directory in which to place the generated networkd configuration #[arg(long, default_value = "/etc/systemd/network/")] pub networkd_dir: PathBuf, /// Address to allocate /// /// If not provided, will allocate available address from the subnet. /// For instance 10.0.0.4 or fc00::4 #[arg(short, long)] pub address: Option<IpAddr>, /// Network to use /// /// Must be the same for all clients. /// For instance 10.0.0.0/24 or fc00::/64 #[arg(short, long)] pub network: IpNet, /// Be verbose /// /// Provide twice for very verbose. #[arg(short, long, action = clap::ArgAction::Count, value_parser = clap::value_parser!(u8).range(0..=2))] pub verbose: u8, } fn network_interface(s: &str) -> Result<NetworkInterface, String> { let interfaces = datalink::interfaces(); let interface = interfaces .iter() .find(|e| e.is_up() && !e.is_loopback() && !e.ips.is_empty() && e.name == s); match interface { Some(i) => Ok(i.clone()), None => Err(format!("No usable interface found for '{}'", s)), } } fn keep_alive(s: &str) -> Result<u64, humantime::DurationError> { let duration = humantime::parse_duration(s)?; Ok(duration.as_secs()) }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/main.rs
src/main.rs
mod args; use std::{collections::HashSet, time::Duration}; use anyhow::{bail, ensure, Context, Result}; use args::CliArgs; use clap::Parser; use tokio::time::{interval, sleep}; use tokio_util::sync::CancellationToken; use tracing::{debug, error, info, trace}; use wiresmith::{ consul::ConsulClient, networkd::NetworkdConfiguration, wireguard::WgPeer, CONSUL_TTL, }; #[tokio::main] async fn main() -> Result<()> { // Spawn a task to cancel us if we receive a SIGINT. let top_level_token = CancellationToken::new(); tokio::spawn({ let token = top_level_token.clone(); async move { tokio::signal::ctrl_c() .await .expect("failed to listen for SIGINT"); info!("Received SIGINT, triggering shutdown"); token.cancel(); } }); let args = args::CliArgs::parse(); if args.verbose == 2 { tracing_subscriber::fmt() .with_env_filter("wiresmith=trace") .init(); } else if args.verbose == 1 { tracing_subscriber::fmt() .with_env_filter("wiresmith=debug") .init(); } else { tracing_subscriber::fmt() .with_env_filter("wiresmith=info") .init(); }; if let Some(address) = args.address { ensure!( args.network.contains(&address), "Address {address} is not part of network {}", args.network ); } let consul_client = ConsulClient::new( args.consul_address.clone(), &args.consul_prefix, args.consul_token.as_deref(), )?; let endpoint_address = if let Some(endpoint_address) = &args.endpoint_address { endpoint_address.clone() } else if let Some(endpoint_interface) = &args.endpoint_interface { // Find suitable IP on provided interface. endpoint_interface .ips .first() .context("No IPs on interface")? .ip() .to_string() } else { unreachable!("Should have been handled by arg parsing"); }; info!("Getting existing peers from Consul"); let peers = consul_client.get_peers().await?; if peers.is_empty() { info!("No existing peers found in Consul"); } else { info!("Found {} existing peer(s) in Consul", peers.len()); debug!("Existing peers:\n{:#?}", peers); } // Check whether we can find and parse an existing config. let networkd_config = if let Ok(config) = NetworkdConfiguration::from_config(&args.networkd_dir, &args.wg_interface).await { info!("Successfully loading existing systemd-networkd config"); config } else { info!("No existing WireGuard configuration found on system, creating a new one"); // If we can't find or parse an existing config, we'll just generate a new one. let networkd_config = NetworkdConfiguration::new( args.address, args.network, args.wg_port, &args.wg_interface, peers, )?; networkd_config .write_config(&args.networkd_dir, args.keepalive) .await?; info!("Our new config is:\n{:#?}", networkd_config); networkd_config }; info!("Restarting systemd-networkd"); NetworkdConfiguration::restart().await?; let mut interval = interval(Duration::from_secs(5)); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { // Wait a bit between each attempt at starting the main loop. // // If we don't have any kind of delay here we would be hammering the server with constant // requests if e.g. the Consul leader goes down and until a new leader is elected, since // creating a new session during that time fails with a 500 error. tokio::select! { _ = top_level_token.cancelled() => { trace!("Top level task cancelled, exiting"); break; }, _ = interval.tick() => {}, }; if let Err(err) = inner_loop( &consul_client, &endpoint_address, &networkd_config, &args, top_level_token.child_token(), ) .await { error!("Inner loop exited with an error: {err:?}"); } if top_level_token.is_cancelled() { trace!("Top level task cancelled, exiting"); break; } else { info!("Restarting wiresmith main loop"); } } Ok(()) } #[tracing::instrument(skip_all)] async fn inner_loop( consul_client: &ConsulClient, endpoint_address: &str, networkd_config: &NetworkdConfiguration, args: &CliArgs, token: CancellationToken, ) -> Result<()> { // Create a Consul session to hold the config KV lock under. let consul_session = consul_client .create_session(networkd_config.public_key, token.clone()) .await?; let own_wg_peer = WgPeer::new( networkd_config.public_key, &format!("{endpoint_address}:{}", args.wg_port), networkd_config.wg_address.addr(), ); info!( "Submitting own WireGuard peer config to Consul:\n{:#?}", own_wg_peer ); // Try to put our WireGuard peer config into Consul. On failures, which could have occurred due // to a session not yet having timed out, we retry 5 times before failing fully. let config_checker = 'cc: { let mut failures = 0; // We sleep for the TTL*2 between each attempt since after this amount of time any previously // held session should have expired. This corresponds to one period of the TTL and one // period of the default Consul session `LockDelay` which is also 15 seconds. let mut interval = interval(CONSUL_TTL * 2); interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { interval.tick().await; match consul_session.put_config(&own_wg_peer, token.clone()).await { Ok(config_checker) => break 'cc config_checker, Err(err) => { failures += 1; if failures >= 5 { bail!("Failed to put node config {failures} times, exiting inner loop"); } error!( "Failed to put own node config into Consul ({failures} failed attempts): {err:?}" ); } }; } }; info!("Wrote own WireGuard peer config to Consul"); // Enter main loop which periodically checks for updates to the list of WireGuard peers. loop { trace!("Checking Consul for peer updates"); let peers = consul_client .get_peers() .await .context("Can't fetch existing peers from Consul")?; let mut networkd_config = NetworkdConfiguration::from_config(&args.networkd_dir, &args.wg_interface) .await .context("Couldn't load existing NetworkdConfiguration from disk")?; // Exclude own peer config. let peers_without_own_config = peers .iter() .filter(|&x| x.public_key != networkd_config.public_key) .cloned() .collect::<HashSet<WgPeer>>(); // If there is a mismatch, write a new networkd configuration. let additional_peers = peers_without_own_config .difference(&networkd_config.peers) .collect::<Vec<_>>(); let deleted_peers = networkd_config .peers .difference(&peers_without_own_config) .collect::<Vec<_>>(); if !additional_peers.is_empty() { info!("Found {} new peer(s) in Consul", additional_peers.len()); debug!("New peers: {:#?}", additional_peers); } if !deleted_peers.is_empty() { info!("Found {} deleted peer(s) in Consul", deleted_peers.len()); debug!("Deleted peers: {:#?}", deleted_peers); } if !additional_peers.is_empty() || !deleted_peers.is_empty() { networkd_config.peers = peers_without_own_config; networkd_config .write_config(&args.networkd_dir, args.keepalive) .await .context("Couldn't write new NetworkdConfiguration")?; info!("Restarting systemd-networkd to apply new config"); NetworkdConfiguration::restart() .await .context("Error restarting systemd-networkd")?; } // Wait until we've either been told to shut down or until we've slept for the update // period. // // TODO: Use long polling instead of periodic checks. tokio::select! { _ = token.cancelled() => { trace!("Main loop cancelled, exiting"); break; }, _ = sleep(args.update_period) => continue, }; } // Cancel the config checker first so we don't get spurious errors if the session is destroyed // first. trace!("Cancelling config checker"); config_checker .cancel() .await .context("Failed to join Consul config checker task")?; // Wait for the Consul session handler to destroy our session and exit. It was cancelled by the // same `CancellationToken` that cancelled us. trace!("Cancelling session handler"); consul_session .cancel() .await .context("Failed to join Consul session handler task")?; Ok(()) }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/src/networkd.rs
src/networkd.rs
use std::{ collections::HashSet, fmt, fs::Permissions, net::IpAddr, os::unix::prelude::PermissionsExt, path::Path, }; use anyhow::{anyhow, Context, Result}; use file_owner::set_group; use ipnet::IpNet; use tokio::{fs, process::Command}; use wireguard_keys::{Privkey, Pubkey}; use crate::wireguard::WgPeer; /// Find a free address in a network given a list of occupied addresses. /// /// Returns `None` if there are no free addresses. #[tracing::instrument] fn get_free_address(network: &IpNet, peers: &HashSet<WgPeer>) -> Option<IpAddr> { let occupied_addresses = peers .iter() .map(|x| x.address.addr()) .collect::<HashSet<_>>(); for host in network.hosts() { if !occupied_addresses.contains(&host) { return Some(host); } } None } pub struct NetworkdConfiguration { pub wg_address: IpNet, pub wg_interface: String, pub wg_port: u16, pub peers: HashSet<WgPeer>, pub private_key: Privkey, pub public_key: Pubkey, } impl fmt::Debug for NetworkdConfiguration { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("NetworkdConfiguration") .field("wg_address", &self.wg_address) .field("wg_interface", &self.wg_interface) .field("wg_port", &self.wg_port) .field("peers", &self.peers) .field("private_key", &"[REDACTED]") .field("public_key", &self.public_key.to_base64_urlsafe()) .finish() } } impl NetworkdConfiguration { /// Build a new config #[tracing::instrument] pub fn new( address: Option<IpAddr>, network: IpNet, port: u16, wg_interface: &str, peers: HashSet<WgPeer>, ) -> Result<Self> { let address = if let Some(address) = address { address } else { get_free_address(&network, &peers).context("Couldn't find usable address")? }; let wg_address = IpNet::new(address, network.prefix_len())?; let private_key = wireguard_keys::Privkey::generate(); Ok(Self { wg_address, wg_interface: wg_interface.to_string(), wg_port: port, peers, private_key, public_key: private_key.pubkey(), }) } /// Read and parse existing config from existing location on disk #[tracing::instrument] pub async fn from_config(networkd_dir: &Path, wg_interface: &str) -> Result<Self> { // Get the list of peers in networkd. let netdev_path = networkd_dir.join(wg_interface).with_extension("netdev"); let netdev_ini = ini::Ini::load_from_file(netdev_path)?; let wg_port = netdev_ini .section(Some("WireGuard")) .context("Couldn't find [WireGuard] section")? .get("ListenPort") .context("Couldn't find ListenPort in [WireGuard] section")? .parse()?; let private_key: Privkey = netdev_ini .section(Some("WireGuard")) .context("Couldn't find [WireGuard] section")? .get("PrivateKey") .context("Couldn't find PrivateKey in [WireGuard] section")? .parse()?; let public_key = private_key.pubkey(); let mut peers = HashSet::new(); for peer in netdev_ini.section_all(Some("WireGuardPeer")) { let public_key = peer .get("PublicKey") .context("No PublicKey attribute on WireGuardPeer")?; let endpoint = peer .get("Endpoint") .context("No Endpoint attribute on WireGuardPeer")?; let allowed_ips = peer .get("AllowedIPs") .context("No AllowedIPs attribute on WireGuardPeer")?; peers.insert(WgPeer { public_key: Pubkey::from_base64(public_key)?, endpoint: endpoint.parse()?, address: allowed_ips.parse()?, }); } let network_path = networkd_dir.join(wg_interface).with_extension("network"); let network_ini = ini::Ini::load_from_file(network_path)?; let wg_address = network_ini .section(Some("Network")) .context("Couldn't find [Network] section")? .get("Address") .context("Couldn't find Address in [Network] section")? .parse()?; Ok(Self { wg_interface: wg_interface.to_string(), wg_address, wg_port, peers, private_key, public_key, }) } /// Generate and write systemd-networkd config #[tracing::instrument] pub async fn write_config(&self, networkd_dir: &Path, persistent_keepalive: u64) -> Result<()> { let network_file = format!( "\ [Match] Name={} [Network] Address={}\n", self.wg_interface, self.wg_address ); let mut netdev_file = format!( "\ [NetDev] Name={} Kind=wireguard Description=WireGuard client MTUBytes=1280 [WireGuard] ListenPort={} PrivateKey={}\n", self.wg_interface, self.wg_port, self.private_key ); for peer in &self.peers { let peer_str = format!( "\n [WireGuardPeer] PublicKey={} Endpoint={} AllowedIPs={} PersistentKeepalive={}", peer.public_key, peer.endpoint, peer.address, persistent_keepalive ); netdev_file.push_str(&peer_str); } let network_path = networkd_dir .join(&self.wg_interface) .with_extension("network"); let netdev_path = networkd_dir .join(&self.wg_interface) .with_extension("netdev"); fs::write(&network_path, network_file) .await .context(format!("Couldn't write config to {network_path:?}"))?; fs::write(&netdev_path, netdev_file) .await .context(format!("Couldn't write config to {netdev_path:?}"))?; fs::set_permissions(&netdev_path, Permissions::from_mode(0o640)).await?; set_group(netdev_path, "systemd-network")?; Ok(()) } /// Restart systemd-networkd #[tracing::instrument] pub async fn restart() -> Result<()> { let restart_output = Command::new("systemctl") .arg("restart") .arg("systemd-networkd") .output() .await?; if !restart_output.status.success() { let stderr = String::from_utf8_lossy(&restart_output.stderr); let journalctl_output = Command::new("journalctl") .arg("-u") .arg("systemd-networkd") .output() .await?; let journalctl_stdout = String::from_utf8_lossy(&journalctl_output.stdout); return Err(anyhow!("Failed to restart systemd-networkd: {stderr}\njournalctl -xeu systemd-networkd: {journalctl_stdout}")); } Ok(()) } }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/tests/integration.rs
tests/integration.rs
mod fixtures; mod utils; use std::{collections::HashSet, time::Duration}; use anyhow::{ensure, Result}; use assert_fs::TempDir; use configparser::ini::Ini; use fixtures::{consul, federated_consul_cluster, tmpdir, ConsulContainer}; use pretty_assertions::assert_eq; use rand::seq::SliceRandom; use rstest::rstest; use tokio::{process::Command, time::sleep}; use wireguard_keys::Privkey; use wiresmith::{networkd::NetworkdConfiguration, wireguard::WgPeer, CONSUL_TTL}; use crate::{utils::wait_for_files, utils::WiresmithContainer}; /// If the address is provided explicitly, it needs to be contained within network. #[rstest] #[case("10.0.0.0/24", "10.0.0.1", true)] #[case("10.0.0.0/24", "10.0.1.1", false)] #[tokio::test] async fn address_contained_within_network( #[case] network: &str, #[case] address: &str, #[case] success: bool, ) -> Result<()> { let output = assert_cmd::Command::cargo_bin("wiresmith")? .arg("--network") .arg(network) .arg("--address") .arg(address) .arg("--endpoint-address") .arg("dontcare") .output()?; if !success { assert_eq!( String::from_utf8_lossy(&output.stderr), format!("Error: Address {address} is not part of network {network}\n") ); } Ok(()) } /// An initial configuration with a single peer is created in case no existing peers are found. /// The address of the peer is not explicitly provided. Instead, the first free address inside the /// network is used. #[rstest] #[tokio::test] async fn initial_configuration(#[future] consul: ConsulContainer, tmpdir: TempDir) -> Result<()> { let consul = consul.await; let wiresmith = WiresmithContainer::new( "initial", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, &[], &tmpdir, ) .await; let network_file = tmpdir.join("wg0.network"); let netdev_file = tmpdir.join("wg0.netdev"); wait_for_files(vec![network_file.as_path(), netdev_file.as_path()]).await; // Check the networkd files. let network_ini = ini::Ini::load_from_file(network_file)?; assert_eq!( network_ini .section(Some("Match")) .unwrap() .get("Name") .unwrap(), "wg0" ); assert_eq!( network_ini .section(Some("Network")) .unwrap() .get("Address") .unwrap(), "10.0.0.1/24" ); let netdev_ini = ini::Ini::load_from_file(netdev_file)?; assert_eq!( netdev_ini .section(Some("NetDev")) .unwrap() .get("Name") .unwrap(), "wg0" ); assert_eq!( netdev_ini .section(Some("NetDev")) .unwrap() .get("Kind") .unwrap(), "wireguard" ); assert_eq!( netdev_ini .section(Some("NetDev")) .unwrap() .get("Description") .unwrap(), "WireGuard client" ); assert_eq!( netdev_ini .section(Some("NetDev")) .unwrap() .get("MTUBytes") .unwrap(), "1280" ); // The private key is generated automatically but we should verify it's valid. let private_key = Privkey::from_base64( netdev_ini .section(Some("WireGuard")) .unwrap() .get("PrivateKey") .unwrap(), )?; // Check whether the interface was configured correctly. let networkctl_output = Command::new("podman") .arg("exec") .arg(&wiresmith.container_name) .arg("networkctl") .arg("status") .arg("wg0") .output() .await?; ensure!( networkctl_output.stderr.is_empty(), "Error running networkctl: {}", String::from_utf8_lossy(&networkctl_output.stderr) ); let wg_showconf_output = Command::new("podman") .arg("exec") .arg(&wiresmith.container_name) .arg("wg") .arg("showconf") .arg("wg0") .output() .await?; ensure!( wg_showconf_output.stderr.is_empty(), "Error running wg showconf: {}", String::from_utf8_lossy(&wg_showconf_output.stderr) ); dbg!(String::from_utf8_lossy(&wg_showconf_output.stdout)); let mut wg_config = Ini::new(); wg_config .read(String::from_utf8_lossy(&wg_showconf_output.stdout).to_string()) .expect("Couldn't parse WireGuard config"); assert_eq!(wg_config.get("Interface", "ListenPort").unwrap(), "51820"); assert_eq!( wg_config.get("Interface", "PrivateKey").unwrap(), private_key.to_base64() ); // There should be no peers here yet. assert!(!wg_config.sections().contains(&"Peer".to_string())); // Check the config put into Consul. let peers = consul.client.get_peers().await?; let mut expected_peers = HashSet::new(); expected_peers.insert(WgPeer { public_key: private_key.pubkey(), endpoint: format!("initial-{}:51820", consul.http_port), address: "10.0.0.1/32".parse().unwrap(), }); // Now there should be peers. assert_eq!(peers, expected_peers); Ok(()) } /// A second peer is joining the network after the first one has created the initial configuration. /// This should cause the first peer to generate a new network config with the new peer. The second /// peer should generate a network config containing the first peer. /// Afterwards, a third peers joins and the previous two nodes should be notified of that. #[rstest] #[tokio::test] async fn join_network( #[future] consul: ConsulContainer, #[from(tmpdir)] tmpdir_a: TempDir, #[from(tmpdir)] tmpdir_b: TempDir, #[from(tmpdir)] tmpdir_c: TempDir, ) -> Result<()> { let consul = consul.await; let _wiresmith_a = WiresmithContainer::new( "a", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, &["--update-period", "1s"], &tmpdir_a, ) .await; let network_file_a = tmpdir_a.join("wg0.network"); let netdev_file_a = tmpdir_a.join("wg0.netdev"); wait_for_files(vec![network_file_a.as_path(), netdev_file_a.as_path()]).await; // We should now have some initial configuration with an empty list of peers. let networkd_config_a = NetworkdConfiguration::from_config(&tmpdir_a, "wg0").await?; assert_eq!(networkd_config_a.wg_address, "10.0.0.1/24".parse()?); assert!(networkd_config_a.peers.is_empty()); // Start the second peer after the first one has generated its files so we don't run into race // conditions with address allocation. let _wiresmith_b = WiresmithContainer::new( "b", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, &["--update-period", "1s"], &tmpdir_b, ) .await; let network_file_b = tmpdir_b.join("wg0.network"); let netdev_file_b = tmpdir_b.join("wg0.netdev"); wait_for_files(vec![network_file_b.as_path(), netdev_file_b.as_path()]).await; // Wait until the first client has had a chance to pick up the changes and generate a new // config. If this is flaky, increase this number slightly. sleep(Duration::from_secs(2)).await; let networkd_config_a = NetworkdConfiguration::from_config(&tmpdir_a, "wg0").await?; let networkd_config_b = NetworkdConfiguration::from_config(&tmpdir_b, "wg0").await?; assert_eq!(networkd_config_a.wg_address, "10.0.0.1/24".parse()?); assert_eq!(networkd_config_b.wg_address, "10.0.0.2/24".parse()?); // We don't expect to see ourselves in the list of peers as we don't want to peer with // ourselves. let mut expected_peers_a = HashSet::new(); expected_peers_a.insert(WgPeer { public_key: networkd_config_b.public_key, endpoint: format!("b-{}:51820", consul.http_port), address: "10.0.0.2/32".parse().unwrap(), }); let mut expected_peers_b = HashSet::new(); expected_peers_b.insert(WgPeer { public_key: networkd_config_a.public_key, endpoint: format!("a-{}:51820", consul.http_port), address: "10.0.0.1/32".parse().unwrap(), }); assert_eq!(networkd_config_a.peers, expected_peers_a); assert_eq!(networkd_config_b.peers, expected_peers_b); // Peers in Consul should be union the other peer lists. let consul_peers = consul.client.get_peers().await?; let expected_peers = networkd_config_a .peers .union(&networkd_config_b.peers) .cloned() .collect::<HashSet<_>>(); assert_eq!(consul_peers, expected_peers); // The third peer now joins. let _wiresmith_c = WiresmithContainer::new( "c", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, &["--update-period", "1s"], &tmpdir_c, ) .await; let network_file_c = tmpdir_c.join("wg0.network"); let netdev_file_c = tmpdir_c.join("wg0.netdev"); wait_for_files(vec![network_file_c.as_path(), netdev_file_c.as_path()]).await; // Wait again for clients to pick up changes. sleep(Duration::from_secs(2)).await; let networkd_config_a = NetworkdConfiguration::from_config(&tmpdir_a, "wg0").await?; let networkd_config_b = NetworkdConfiguration::from_config(&tmpdir_b, "wg0").await?; let networkd_config_c = NetworkdConfiguration::from_config(&tmpdir_c, "wg0").await?; assert_eq!(networkd_config_a.wg_address, "10.0.0.1/24".parse()?); assert_eq!(networkd_config_b.wg_address, "10.0.0.2/24".parse()?); assert_eq!(networkd_config_c.wg_address, "10.0.0.3/24".parse()?); // We recheck that now everyone has everyone else but not themselves. let mut expected_peers_a = HashSet::new(); expected_peers_a.insert(WgPeer { public_key: networkd_config_b.public_key, endpoint: format!("b-{}:51820", consul.http_port), address: "10.0.0.2/32".parse().unwrap(), }); expected_peers_a.insert(WgPeer { public_key: networkd_config_c.public_key, endpoint: format!("c-{}:51820", consul.http_port), address: "10.0.0.3/32".parse().unwrap(), }); let mut expected_peers_b = HashSet::new(); expected_peers_b.insert(WgPeer { public_key: networkd_config_a.public_key, endpoint: format!("a-{}:51820", consul.http_port), address: "10.0.0.1/32".parse().unwrap(), }); expected_peers_b.insert(WgPeer { public_key: networkd_config_c.public_key, endpoint: format!("c-{}:51820", consul.http_port), address: "10.0.0.3/32".parse().unwrap(), }); let mut expected_peers_c = HashSet::new(); expected_peers_c.insert(WgPeer { public_key: networkd_config_a.public_key, endpoint: format!("a-{}:51820", consul.http_port), address: "10.0.0.1/32".parse().unwrap(), }); expected_peers_c.insert(WgPeer { public_key: networkd_config_b.public_key, endpoint: format!("b-{}:51820", consul.http_port), address: "10.0.0.2/32".parse().unwrap(), }); assert_eq!(networkd_config_a.peers, expected_peers_a); assert_eq!(networkd_config_b.peers, expected_peers_b); assert_eq!(networkd_config_c.peers, expected_peers_c); // Peers in Consul should be union the other peer lists. let consul_peers = consul.client.get_peers().await?; let expected_peers = networkd_config_a .peers .union(&networkd_config_b.peers) .cloned() .collect::<HashSet<_>>() .union(&networkd_config_c.peers) .cloned() .collect::<HashSet<_>>(); assert_eq!(consul_peers, expected_peers); Ok(()) } /// A peer is added to the first Consul server in dc1 which is federated to a second Consul server /// in dc2. Afterwards, a second peer joins on the second Consul server. #[rstest] #[tokio::test] async fn join_network_federated_cluster( #[future] federated_consul_cluster: (ConsulContainer, ConsulContainer), #[from(tmpdir)] tmpdir_a: TempDir, #[from(tmpdir)] tmpdir_b: TempDir, ) -> Result<()> { let (consul_dc1, consul_dc2) = federated_consul_cluster.await; let _wiresmith_a = WiresmithContainer::new( "a", "10.0.0.0/24", &format!("wiresmith-{}", consul_dc1.http_port), consul_dc1.http_port, // This Wiresmith instance is already implicitly connected to dc1. We're just making this // explicit here. &["--update-period", "1s"], &tmpdir_a, ) .await; let network_file_a = tmpdir_a.join("wg0.network"); let netdev_file_a = tmpdir_a.join("wg0.netdev"); wait_for_files(vec![network_file_a.as_path(), netdev_file_a.as_path()]).await; // Start the second peer after the first one has generated its files so we don't run into race // conditions with address allocation. let _wiresmith_b = WiresmithContainer::new( "b", "10.0.0.0/24", &format!("wiresmith-{}", consul_dc1.http_port), consul_dc2.http_port, // This Wiresmith instance is connected to the Consul in dc2. However, we'll make it use // the Consul KV in dc1 so that we have a consistent view of peers as Consul doesn't // replicate its KV to federated clusters. &["--update-period", "1s"], &tmpdir_b, ) .await; let network_file_b = tmpdir_b.join("wg0.network"); let netdev_file_b = tmpdir_b.join("wg0.netdev"); wait_for_files(vec![network_file_b.as_path(), netdev_file_b.as_path()]).await; // Wait until the first client has had a chance to pick up the changes and generate a new // config. If this is flaky, increase this number slightly. sleep(Duration::from_secs(2)).await; let networkd_config_a = NetworkdConfiguration::from_config(&tmpdir_a, "wg0").await?; let networkd_config_b = NetworkdConfiguration::from_config(&tmpdir_b, "wg0").await?; let mut expected_peers = HashSet::new(); expected_peers.insert(WgPeer { public_key: networkd_config_a.public_key, endpoint: format!("a-{}:51820", consul_dc1.http_port), address: "10.0.0.1/32".parse().unwrap(), }); expected_peers.insert(WgPeer { public_key: networkd_config_b.public_key, endpoint: format!("b-{}:51820", consul_dc2.http_port), address: "10.0.0.2/32".parse().unwrap(), }); // Peers in Consul should be union the other peer lists. let consul_peers_dc1 = consul_dc1.client.get_peers().await?; assert_eq!(consul_peers_dc1, expected_peers); // dc2 should have the same peers as we do in dc1. let consul_peers_dc2 = consul_dc2.client.get_peers().await?; assert_eq!(consul_peers_dc2, consul_peers_dc1); Ok(()) } /// Three peers join the network. A randomly stopped peer should be removed by /// consul after the defined timeout. #[rstest] #[tokio::test] async fn deletes_peer_on_timeout( #[future] consul: ConsulContainer, #[from(tmpdir)] tmpdir_a: TempDir, #[from(tmpdir)] tmpdir_b: TempDir, #[from(tmpdir)] tmpdir_c: TempDir, ) -> Result<()> { let consul = consul.await; let mut peers: Vec<(WiresmithContainer, WgPeer)> = vec![]; let args = &["--keepalive", "1s", "--update-period", "5s"]; let wiresmith_a = WiresmithContainer::new( "a", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, args, &tmpdir_a, ) .await; let network_file_a = tmpdir_a.join("wg0.network"); let netdev_file_a = tmpdir_a.join("wg0.netdev"); wait_for_files(vec![network_file_a.as_path(), netdev_file_a.as_path()]).await; let networkd_config_a = NetworkdConfiguration::from_config(&tmpdir_a, "wg0").await?; peers.push(( wiresmith_a, WgPeer { public_key: networkd_config_a.public_key, endpoint: format!("a-{}:51820", consul.http_port), address: "10.0.0.1/32".parse().unwrap(), }, )); let wiresmith_b = WiresmithContainer::new( "b", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, args, &tmpdir_b, ) .await; let network_file_b = tmpdir_b.join("wg0.network"); let netdev_file_b = tmpdir_b.join("wg0.netdev"); wait_for_files(vec![network_file_b.as_path(), netdev_file_b.as_path()]).await; let networkd_config_b = NetworkdConfiguration::from_config(&tmpdir_b, "wg0").await?; peers.push(( wiresmith_b, WgPeer { public_key: networkd_config_b.public_key, endpoint: format!("b-{}:51820", consul.http_port), address: "10.0.0.2/32".parse().unwrap(), }, )); let wiresmith_c = WiresmithContainer::new( "c", "10.0.0.0/24", &format!("wiresmith-{}", consul.http_port), consul.http_port, args, &tmpdir_c, ) .await; let network_file_c = tmpdir_c.join("wg0.network"); let netdev_file_c = tmpdir_c.join("wg0.netdev"); wait_for_files(vec![network_file_c.as_path(), netdev_file_c.as_path()]).await; let networkd_config_c = NetworkdConfiguration::from_config(&tmpdir_c, "wg0").await?; peers.push(( wiresmith_c, WgPeer { public_key: networkd_config_c.public_key, endpoint: format!("c-{}:51820", consul.http_port), address: "10.0.0.3/32".parse().unwrap(), }, )); // Wait for consul to pickup changes. sleep(Duration::from_secs(1)).await; let consul_peers = consul.client.get_peers().await?; assert_eq!(consul_peers.len(), peers.len()); // Kill a random peer. let mut rng = rand::rng(); peers.shuffle(&mut rng); let (random_peer, remaining_peers) = peers.split_first().expect("Peers are empty."); Command::new("podman") .arg("kill") .arg(&random_peer.0.container_name) .output() .await .unwrap_or_else(|_| { panic!( "Error trying to run podman kill {}", &random_peer.0.container_name ) }); // Wait for a little more than the Consul session `TTL + LockDelay` to trigger the timeout. sleep((CONSUL_TTL * 2) + Duration::from_secs(5)).await; let expected_peers = HashSet::from_iter(remaining_peers.into_iter().map(|peer| peer.1.clone())); let consul_peers = consul.client.get_peers().await?; assert_eq!(consul_peers, expected_peers); Ok(()) }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/tests/fixtures/mod.rs
tests/fixtures/mod.rs
use std::{ process::{Command, Stdio}, time::{Duration, Instant}, }; use anyhow::Result; use assert_fs::fixture::TempDir; use port_check::free_local_port; use rstest::fixture; use tokio::time::sleep; use wiresmith::consul::ConsulClient; /// Get a free port. #[fixture] pub fn port() -> u16 { free_local_port().expect("Couldn't find a free local port") } /// Test fixture which creates a temporary directory #[fixture] pub fn tmpdir() -> TempDir { assert_fs::TempDir::new().expect("Couldn't create a temp dir for tests") } /// Wait for a few seconds for the port to become available async fn wait_for_api(consul: &ConsulContainer) -> Result<()> { let start_wait = Instant::now(); loop { let req = consul .client .http_client .get(consul.client.kv_api_base_url.join("/v1/status/leader")?); if let Ok(resp) = req.send().await { if resp.status().is_success() { return Ok(()); } } sleep(Duration::from_millis(100)).await; if start_wait.elapsed().as_secs() > 15 { panic!( "Timeout waiting for Consul API at {}", consul.client.kv_api_base_url ); } } } pub struct ConsulContainer { pub http_port: u16, pub client: ConsulClient, } impl ConsulContainer { fn new(port: u16) -> Self { let client = ConsulClient::new( format!("http://localhost:{port}").parse().unwrap(), "wiresmith", None, ) .unwrap(); Self { http_port: port, client, } } } impl Drop for ConsulContainer { fn drop(&mut self) { let container_name = format!("consul-{}", self.http_port); // Using podman, stop all containers with the same testport label. Command::new("podman") .arg("kill") .arg(&container_name) .output() .unwrap_or_else(|_| panic!("Error trying to run podman kill {}", container_name)); // Remove test container network. Command::new("podman") .arg("network") .arg("rm") // Remove wiresmith container as well, if still present. .arg("-f") .arg(format!("wiresmith-{}", self.http_port)) .stdout(Stdio::null()) .spawn() .expect("Couldn't remove test container network"); } } /// Run Consul in dev mode /// /// Start with a free port and some optional arguments then wait for a while for the server setup /// to complete. #[fixture] pub async fn consul<I>(#[default(&[] as &[&str])] args: I) -> ConsulContainer where I: IntoIterator + Clone, I::Item: AsRef<std::ffi::OsStr>, { let start_time = Instant::now(); let http_port = port(); // Create a dedicated container network for each test using // this fixture. Command::new("podman") .arg("network") .arg("create") .arg(format!("wiresmith-{http_port}")) .stdout(Stdio::null()) .spawn() .expect("Couldn't create test container network"); // Wait for podman to setup the network. sleep(Duration::from_millis(100)).await; Command::new("podman") .arg("run") .args(["--name", &format!("consul-{http_port}")]) .arg("--replace") .arg("--rm") .args(["--label", "testcontainer"]) .args(["--label", &format!("testport={http_port}")]) .args(["--network", &format!("wiresmith-{http_port}")]) .args(["-p", &format!("{http_port}:{http_port}")]) .arg("docker.io/hashicorp/consul") .arg("agent") .arg("-dev") .args(["-bind", "{{ GetInterfaceIP \"eth0\" }}"]) .args(["-client", "0.0.0.0"]) .args(["-http-port", &http_port.to_string()]) .args(["-grpc-port", "0"]) .args(["-grpc-tls-port", "0"]) .args(["-dns-port", "0"]) .args(["-serf-lan-port", &port().to_string()]) .args(["-server-port", &port().to_string()]) .args(args.clone()) .stdout(Stdio::null()) .spawn() .expect("Couldn't run Consul binary"); let consul = ConsulContainer::new(http_port); wait_for_api(&consul) .await .expect("Error while waiting for Consul API"); println!( "Started Consul after {:?} on HTTP port {http_port}", start_time.elapsed() ); consul } /// Run a federated Consul cluster with two datacenters /// /// Start with a free port and some optional arguments then wait for a while for the server setup /// to complete. #[fixture] pub async fn federated_consul_cluster<I>( #[default(&[] as &[&str])] args: I, ) -> (ConsulContainer, ConsulContainer) where I: IntoIterator + Clone, I::Item: AsRef<std::ffi::OsStr>, { let start_time = Instant::now(); let http_port_dc1 = port(); // Create a dedicated container network for each test using // this fixture. Command::new("podman") .arg("network") .arg("create") .arg(format!("wiresmith-{http_port_dc1}")) .stdout(Stdio::null()) .spawn() .expect("Couldn't create test container network"); // Wait for podman to setup the network. sleep(Duration::from_millis(100)).await; Command::new("podman") .arg("run") .args(["--name", &format!("consul-{http_port_dc1}")]) .arg("--replace") .arg("--rm") .args(["--label", "testcontainer"]) .args(["--label", &format!("testport={http_port_dc1}")]) .args(["--network", &format!("wiresmith-{http_port_dc1}")]) .args(["-p", &format!("{http_port_dc1}:{http_port_dc1}")]) .arg("docker.io/hashicorp/consul") .arg("agent") .arg("-dev") .args(["-datacenter", "dc1"]) .args(["-bind", "{{ GetInterfaceIP \"eth0\" }}"]) .args(["-client", "0.0.0.0"]) .args(["-http-port", &http_port_dc1.to_string()]) .args(["-grpc-port", "0"]) .args(["-grpc-tls-port", "0"]) .args(["-dns-port", "0"]) .args(["-serf-lan-port", &port().to_string()]) .args(["-server-port", &port().to_string()]) .args(args.clone()) .stdout(Stdio::null()) .spawn() .expect("Couldn't run Consul binary"); let consul_dc1 = ConsulContainer::new(http_port_dc1); wait_for_api(&consul_dc1) .await .expect("Error while waiting for Consul API"); println!( "Started Consul in dc1 after {:?} on HTTP port {http_port_dc1}", start_time.elapsed() ); let http_port_dc2 = port(); Command::new("podman") .arg("run") .args(["--name", &format!("consul-{http_port_dc2}")]) .arg("--replace") .arg("--rm") .args(["--label", "testcontainer"]) .args(["--label", &format!("testport={http_port_dc2}")]) .args(["--network", &format!("wiresmith-{http_port_dc1}")]) .args(["-p", &format!("{http_port_dc2}:{http_port_dc2}")]) .arg("docker.io/hashicorp/consul") .arg("agent") .arg("-dev") .args(["--datacenter", "dc2"]) // This is the part that makes this a federated cluster. .args(["-retry-join-wan", &format!("consul-{http_port_dc1}")]) .args(["-bind", "{{ GetInterfaceIP \"eth0\" }}"]) .args(["-client", "0.0.0.0"]) .args(["-http-port", &http_port_dc2.to_string()]) .args(["-grpc-port", "0"]) .args(["-grpc-tls-port", "0"]) .args(["-dns-port", "0"]) .args(["-serf-lan-port", &port().to_string()]) .args(["-server-port", &port().to_string()]) .args(args.clone()) .stdout(Stdio::null()) .spawn() .expect("Couldn't run Consul binary"); let consul_dc2 = ConsulContainer::new(http_port_dc2); wait_for_api(&consul_dc1) .await .expect("Error while waiting for Consul API"); println!( "Started Consul in dc2 after {:?} on HTTP port {http_port_dc2}", start_time.elapsed() ); (consul_dc1, consul_dc2) }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
svenstaro/wiresmith
https://github.com/svenstaro/wiresmith/blob/2060e98f5d3eb79ea85ad4b6720464ed7f19d100/tests/utils/mod.rs
tests/utils/mod.rs
use std::{ path::Path, process::Stdio, time::{Duration, Instant}, }; use anyhow::Result; use tokio::{process::Command, time::sleep}; /// Wait a few seconds for the files to become available pub async fn wait_for_files(files: Vec<&Path>) { let start_time = Instant::now(); while !files.iter().all(|x| x.exists()) { sleep(Duration::from_millis(100)).await; if start_time.elapsed().as_secs() > 3 { panic!("Timeout waiting {files:?} to exist"); } } println!( "Files available after waiting for {:?}", start_time.elapsed() ); } #[derive(PartialEq)] pub struct WiresmithContainer { /// Full unique container_name /// /// This is built using {name}-{consul-port}. pub container_name: String, } impl WiresmithContainer { /// Launch an instance of wiresmith in a podman container with systemd. pub async fn new( name: &str, network: &str, container_network: &str, consul_port: u16, args: &[&str], dir: &Path, ) -> Self { let container_name = format!("{name}-{consul_port}"); // Launch archlinux container with systemd inside. Command::new("podman") .arg("run") .args(["--name", &container_name]) .arg("--replace") .arg("--rm") .args(["--label", "testcontainer"]) // SYS_ADMIN could be removed when https://github.com/systemd/systemd/pull/26478 is released .args(["--cap-add", "SYS_ADMIN,NET_ADMIN"]) .args(["--network", container_network]) .args([ "-v", concat!(env!("CARGO_BIN_EXE_wiresmith"), ":/usr/bin/wiresmith"), ]) .args([ "-v", &format!("{}:/etc/systemd/network", dir.to_string_lossy()), ]) .args(["--tz", "UTC"]) .arg("wiresmith-testing") .stdout(Stdio::null()) .spawn() .expect("Couldn't run systemd in podman"); wait_for_systemd(&container_name) .await .expect("Error while waiting for systemd container"); // Lastly, start wiresmith itself. Command::new("podman") .arg("exec") .arg(&container_name) .arg("wiresmith") .args([ "--consul-address", &format!("http://consul-{consul_port}:{consul_port}"), ]) .args(["--network", network]) .args(["--endpoint-address", &container_name]) .args(args) // To diagnose issues, it's sometimes helpful to comment out the following line so that // we can see log output from the wiresmith instances inside the containers. .stdout(Stdio::null()) .spawn() .expect("Couldn't run systemd in podman"); Self { container_name } } } impl Drop for WiresmithContainer { fn drop(&mut self) { // We can't use async here as drop isn't async so we just run this command blocking. use std::process::Command; // Using podman, stop all containers with the same testport label. Command::new("podman") .arg("kill") .arg(&self.container_name) .output() .unwrap_or_else(|_| panic!("Error trying to run podman kill {}", self.container_name)); } } /// Wait a few seconds for systemd to boot async fn wait_for_systemd(container_name: &str) -> Result<()> { let start_time = Instant::now(); loop { let output = Command::new("podman") .arg("exec") .arg(container_name) .arg("systemctl") .arg("is-system-running") .output() .await?; // "degraded" is good enough for us, it just means that at least one unit has failed to // start but we don't usually care about that. if output.stdout.starts_with(b"degraded") || output.stdout.starts_with(b"running") { println!( "Test container '{container_name}' took {:?} to start", start_time.elapsed() ); return Ok(()); } sleep(Duration::from_millis(100)).await; if start_time.elapsed().as_secs() > 10 { dbg!(output); panic!("Timeout waiting for systemd container {container_name}",); } } }
rust
MIT
2060e98f5d3eb79ea85ad4b6720464ed7f19d100
2026-01-04T20:18:52.192476Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/lib.rs
src/lib.rs
#![crate_name="keepass"] #![crate_type = "dylib"] #![crate_type = "rlib"] extern crate libc; extern crate openssl; extern crate rustc_serialize; extern crate chrono; extern crate rand; extern crate uuid; pub mod sec_str; pub mod kpdb; pub mod common;
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/tests_v1kpdb.rs
src/kpdb/tests_v1kpdb.rs
use chrono::{Timelike, Local, TimeZone, Datelike}; use kpdb::v1kpdb::V1Kpdb; use kpdb::v1error::V1KpdbError; #[test] fn test_new() { // No keyfile and password should give error as result let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), None, None); match result { Ok(_) => assert!(false), Err(e) => assert_eq!(e, V1KpdbError::PassErr), }; // Test load at all and parameters result = V1Kpdb::new("test/test_both.kdb".to_string(), Some("test".to_string()), Some("test/test_key".to_string())); assert!(result.is_ok()); let mut db = result.ok().unwrap(); assert_eq!(db.load().is_ok(), true); assert_eq!(db.path, "test/test_both.kdb"); // Test fail of load with wrong password result = V1Kpdb::new("test/test_password.kdb".to_string(), Some("tes".to_string()), None); assert!(result.is_ok()); db = result.ok().unwrap(); match db.load() { Ok(_) => assert!(false), Err(e) => assert_eq!(e, V1KpdbError::DecryptErr), }; } #[test] fn test_save() { // if this test fails one has to copy test_password.kdb to test_save.kdb let mut result = V1Kpdb::new("test/test_save.kdb".to_string(), Some("test".to_string()), None); assert!(result.is_ok()); let mut db = result.ok().unwrap(); assert!(db.load().is_ok()); assert!(db.save(None, None, None).is_ok()); assert!(db.load().is_ok()); assert!(db.save(Some("test/new_path.kdb".to_string()), None, None).is_ok()); result = V1Kpdb::new("test/new_path.kdb".to_string(), Some("test".to_string()), None); db = result.ok().unwrap(); assert!(db.load().is_ok()); assert!(db.save(Some("test/new_pass.kdb".to_string()), Some("new".to_string()), None).is_ok()); result = V1Kpdb::new("test/new_pass.kdb".to_string(), Some("new".to_string()), None); db = result.ok().unwrap(); assert!(db.load().is_ok()); assert!(db.save(Some("test/new_keyfile.kdb".to_string()), None, Some("test/64Bkey".to_string())).is_ok()); result = V1Kpdb::new("test/new_keyfile.kdb".to_string(), Some("new".to_string()), Some("test/64Bkey".to_string())); db = result.ok().unwrap(); assert!(db.load().is_ok()); } #[test] fn test_create_group_w_title_only() { let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let num_groups_before = db.header.num_groups; assert_eq!(db.create_group("test".to_string(), None, None, None).is_ok(), true); let mut new_group = db.groups[db.groups.len() - 1].borrow_mut(); assert_eq!(new_group.title, "test"); assert_eq!((new_group.expire.year(), new_group.expire.month(), new_group.expire.day()), (2999, 12, 28)); assert_eq!((new_group.expire.hour(), new_group.expire.minute(), new_group.expire.second()), (23, 59, 59)); assert_eq!(new_group.image, 0); let parent = new_group.parent.as_mut().unwrap(); assert_eq!(parent.borrow().id, 0); assert_eq!(db.header.num_groups, num_groups_before + 1); } #[test] fn test_create_group_w_everything() { let mut result = V1Kpdb::new("test/test_parsing.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let num_groups_before = db.header.num_groups; let expire = Local.ymd(2015, 2, 28).and_hms(10, 10, 10); let parent = db.groups[1].clone(); let image = 2; assert_eq!(db.create_group("test".to_string(), Some(expire), Some(image), Some(parent)) .is_ok(), true); let mut new_group = db.groups[2].borrow_mut(); assert_eq!(new_group.title, "test"); assert_eq!((new_group.expire.year(), new_group.expire.month(), new_group.expire.day()), (2015, 2, 28)); assert_eq!(new_group.image, 2); let parent = new_group.parent.as_mut().unwrap(); assert_eq!(parent.borrow().title, "12"); assert_eq!(db.header.num_groups, num_groups_before + 1); } #[test] fn test_create_entry() { let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let num_entries_before = db.header.num_entries; let group = db.groups[0].clone(); let expire = Local.ymd(2015, 2, 28).and_hms(10, 10, 10); db.create_entry(group, "test".to_string(), Some(expire), Some(5), Some("http://foo".to_string()), Some("foo".to_string()), Some("bar".to_string()), Some("foobar".to_string())); let mut new_entry = db.entries[db.entries.len() - 1].borrow_mut(); new_entry.username.as_mut().unwrap().unlock(); new_entry.password.as_mut().unwrap().unlock(); assert_eq!(new_entry.title, "test"); assert_eq!((new_entry.expire.year(), new_entry.expire.month(), new_entry.expire.day()), (2015, 2, 28)); assert_eq!((new_entry.expire.hour(), new_entry.expire.minute(), new_entry.expire.second()), (10, 10, 10)); assert_eq!(new_entry.image, 5); assert_eq!(new_entry.url.as_ref().unwrap(), "http://foo"); assert_eq!(new_entry.comment.as_ref().unwrap(), "foo"); assert_eq!(new_entry.username.as_ref().unwrap().string, "bar"); assert_eq!(new_entry.password.as_ref().unwrap().string, "foobar"); assert_eq!(db.header.num_entries, num_entries_before + 1); } #[test] fn test_remove_group() { let mut result = V1Kpdb::new("test/test_parsing.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let group = db.groups[2].clone(); let num_groups_before = db.header.num_groups; let num_groups_in_root = db.groups[0].borrow().children.len(); let num_entries_before = db.header.num_entries; let num_entries_in_db = db.entries.len(); assert_eq!(db.remove_group(group).is_ok(), true); assert_eq!(db.groups.len() as u32, num_groups_before - 5); assert_eq!(db.header.num_groups, num_groups_before - 5); assert_eq!(db.groups[0].borrow().children.len(), num_groups_in_root - 1); assert_eq!(db.header.num_entries, num_entries_before - 3); assert_eq!(db.entries.len(), num_entries_in_db - 3); } #[test] fn test_remove_group_easy() { let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let num_groups_before = db.header.num_groups; let num_groups_in_root = db.root_group.borrow().children.len(); let num_entries_before = db.header.num_entries; let num_entries_in_db = db.entries.len(); let group = db.groups[0].clone(); assert_eq!(db.remove_group(group).is_ok(), true); assert_eq!(db.groups.len() as u32, num_groups_before - 1); assert_eq!(db.header.num_groups, num_groups_before - 1); assert_eq!(db.root_group.borrow().children.len(), num_groups_in_root - 1); assert_eq!(db.header.num_entries, num_entries_before - 1); assert_eq!(db.entries.len(), num_entries_in_db - 1); } #[test] fn test_remove_entry() { let mut result = V1Kpdb::new("test/test_password.kdb".to_string(), Some("test".to_string()), None); match result { Ok(ref mut e) => assert_eq!(e.load().is_ok(), true), Err(_) => assert!(false), }; let mut db = result.unwrap(); let entry = db.entries[0].clone(); let num_entries_before = db.header.num_entries; let num_entries_in_db = db.entries.len(); let num_entries_in_group = db.groups[0].borrow().entries.len(); assert_eq!(db.remove_entry(entry).is_ok(), true); assert_eq!(db.header.num_entries, num_entries_before - 1); assert_eq!(db.entries.len(), num_entries_in_db - 1); assert_eq!(db.groups[0].borrow().entries.len(), num_entries_in_group - 1); }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/parser.rs
src/kpdb/parser.rs
use libc::{c_void, munlock, size_t}; use std::cell::{RefCell, RefMut}; use std::rc::Rc; use std::str; use chrono::{DateTime, Local, TimeZone, Datelike, Timelike}; use rustc_serialize::hex::FromHex; use uuid::Uuid; use kpdb::v1entry::V1Entry; use kpdb::v1group::V1Group; use kpdb::v1header::V1Header; use kpdb::v1kpdb::V1Kpdb; use kpdb::v1error::V1KpdbError; use sec_str::SecureString; use common::common::{slice_to_u16, slice_to_u32, u16_to_vec_u8, u32_to_vec_u8, write_array_volatile}; pub struct HeaderLoadParser { header: Vec<u8>, } impl HeaderLoadParser { pub fn new(header: Vec<u8>) -> HeaderLoadParser { HeaderLoadParser { header: header, } } pub fn parse_header(&self) -> Result<V1Header, V1KpdbError> { // A static method to parse a KeePass v1.x header let mut final_randomseed: Vec<u8> = vec![]; let mut iv: Vec<u8> = vec![]; let mut content_hash: Vec<u8> = vec![]; let mut transf_randomseed: Vec<u8> = vec![]; let signature1 = try!(slice_to_u32(&self.header[0..4]).map_err(|_| V1KpdbError::ConvertErr)); let signature2 = try!(slice_to_u32(&self.header[4..8]).map_err(|_| V1KpdbError::ConvertErr)); let enc_flag = try!(slice_to_u32(&self.header[8..12]).map_err(|_| V1KpdbError::ConvertErr)); let version = try!(slice_to_u32(&self.header[12..16]).map_err(|_| V1KpdbError::ConvertErr)); final_randomseed.extend(&self.header[16..32]); iv.extend(&self.header[32..48]); let num_groups = try!(slice_to_u32(&self.header[48..52]).map_err(|_| V1KpdbError::ConvertErr)); let num_entries = try!(slice_to_u32(&self.header[52..56]).map_err(|_| V1KpdbError::ConvertErr)); content_hash.extend(&self.header[56..88]); transf_randomseed.extend(&self.header[88..120]); let key_transf_rounds = try!(slice_to_u32(&self.header[120..124]).map_err(|_| V1KpdbError::ConvertErr)); Ok(V1Header { signature1: signature1, signature2: signature2, enc_flag: enc_flag, version: version, final_randomseed: final_randomseed, iv: iv, num_groups: num_groups, num_entries: num_entries, content_hash: content_hash, transf_randomseed: transf_randomseed, key_transf_rounds: key_transf_rounds, }) } } pub struct HeaderSaveParser { header: V1Header } impl HeaderSaveParser { pub fn new(header: V1Header) -> HeaderSaveParser { HeaderSaveParser { header: header } } pub fn parse_header(&mut self) -> Vec<u8> { let mut header_raw: Vec<u8> = vec![]; header_raw.append(&mut u32_to_vec_u8(self.header.signature1)); header_raw.append(&mut u32_to_vec_u8(self.header.signature2)); header_raw.append(&mut u32_to_vec_u8(self.header.enc_flag)); header_raw.append(&mut u32_to_vec_u8(self.header.version)); header_raw.append(&mut self.header.final_randomseed); header_raw.append(&mut self.header.iv); header_raw.append(&mut u32_to_vec_u8(self.header.num_groups)); header_raw.append(&mut u32_to_vec_u8(self.header.num_entries)); header_raw.append(&mut self.header.content_hash); header_raw.append(&mut self.header.transf_randomseed); header_raw.append(&mut u32_to_vec_u8(self.header.key_transf_rounds)); header_raw } } // Implements a parser to load a KeePass DB pub struct LoadParser { pos: usize, decrypted_database: Vec<u8>, num_groups: u32, num_entries: u32, } impl LoadParser { pub fn new(decrypted_database: Vec<u8>, num_groups: u32, num_entries: u32) -> LoadParser { LoadParser { pos: 0usize, decrypted_database: decrypted_database, num_groups: num_groups, num_entries: num_entries, } } // Parse the groups and put them into a vector pub fn parse_groups(&mut self) -> Result<(Vec<Rc<RefCell<V1Group>>>, Vec<u16>), V1KpdbError> { let mut group_number: u32 = 0; let mut levels: Vec<u16> = vec![]; let mut cur_group = Rc::new(RefCell::new(V1Group::new())); let mut groups: Vec<Rc<RefCell<V1Group>>> = vec![]; let mut field_type: u16; let mut field_size: u32; while group_number < self.num_groups { field_type = try!(slice_to_u16(&self.decrypted_database[self.pos..self.pos + 2]).map_err(|_| V1KpdbError::ConvertErr)); self.pos += 2; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } field_size = try!(slice_to_u32(&self.decrypted_database[self.pos..self.pos + 4]).map_err(|_| V1KpdbError::ConvertErr)); self.pos += 4; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } let _ = self.read_group_field(cur_group.borrow_mut(), field_type, field_size); if field_type == 0x0008 { levels.push(cur_group.borrow().level); } else if field_type == 0xFFFF { groups.push(cur_group); group_number += 1; if group_number == self.num_groups { break; }; cur_group = Rc::new(RefCell::new(V1Group::new())); } self.pos += field_size as usize; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } } Ok((groups, levels)) } // Parse the entries and put them into a vector pub fn parse_entries(&mut self) -> Result<Vec<Rc<RefCell<V1Entry>>>, V1KpdbError> { let mut entry_number: u32 = 0; let mut cur_entry = Rc::new(RefCell::new(V1Entry::new())); let mut entries: Vec<Rc<RefCell<V1Entry>>> = vec![]; let mut field_type: u16; let mut field_size: u32; while entry_number < self.num_entries { field_type = try!(slice_to_u16(&self.decrypted_database[self.pos..self.pos + 2]).map_err(|_| V1KpdbError::ConvertErr)); self.pos += 2; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } field_size = try!(slice_to_u32(&self.decrypted_database[self.pos..self.pos + 4]).map_err(|_| V1KpdbError::ConvertErr)); self.pos += 4; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } let _ = self.read_entry_field(cur_entry.borrow_mut(), field_type, field_size); if field_type == 0xFFFF { entries.push(cur_entry); entry_number += 1; if entry_number == self.num_entries { break; }; cur_entry = Rc::new(RefCell::new(V1Entry::new())); } self.pos += field_size as usize; if self.pos > self.decrypted_database.len() { return Err(V1KpdbError::OffsetErr); } } Ok(entries) } // Read a group field from the raw data by it's field type fn read_group_field(&mut self, mut group: RefMut<V1Group>, field_type: u16, field_size: u32) -> Result<(), V1KpdbError> { let db_slice = if field_type == 0x0002 { &self.decrypted_database[self.pos..self.pos + (field_size - 1) as usize] } else { &self.decrypted_database[self.pos..self.pos + field_size as usize] }; match field_type { 0x0001 => group.id = try!(slice_to_u32(db_slice).map_err(|_| V1KpdbError::ConvertErr)), 0x0002 => { group.title = str::from_utf8(db_slice) .unwrap_or("") .to_string() } 0x0003 => group.creation = LoadParser::get_date(db_slice), 0x0004 => group.last_mod = LoadParser::get_date(db_slice), 0x0005 => group.last_access = LoadParser::get_date(db_slice), 0x0006 => group.expire = LoadParser::get_date(db_slice), 0x0007 => group.image = try!(slice_to_u32(db_slice).map_err(|_| V1KpdbError::ConvertErr)), 0x0008 => group.level = try!(slice_to_u16(db_slice).map_err(|_| V1KpdbError::ConvertErr)), 0x0009 => group.flags = try!(slice_to_u32(db_slice).map_err(|_| V1KpdbError::ConvertErr)), _ => (), } Ok(()) } // Read an entry field from the raw data by it's field type fn read_entry_field(&mut self, mut entry: RefMut<V1Entry>, field_type: u16, field_size: u32) -> Result<(), V1KpdbError> { let db_slice = match field_type { 0x0004...0x0008 | 0x000D => { &self.decrypted_database[self.pos..self.pos + (field_size - 1) as usize] } _ => &self.decrypted_database[self.pos..self.pos + field_size as usize], }; match field_type { 0x0001 => entry.uuid = Uuid::from_bytes(db_slice).unwrap(), 0x0002 => entry.group_id = try!(slice_to_u32(db_slice).map_err(|_| V1KpdbError::ConvertErr)), 0x0003 => entry.image = try!(slice_to_u32(db_slice).map_err(|_| V1KpdbError::ConvertErr)), 0x0004 => { entry.title = str::from_utf8(db_slice) .unwrap_or("") .to_string() } 0x0005 => { entry.url = Some(str::from_utf8(db_slice) .unwrap_or("") .to_string()) } 0x0006 => { entry.username = Some(SecureString::new(str::from_utf8(db_slice) .unwrap() .to_string())) } 0x0007 => { entry.password = Some(SecureString::new(str::from_utf8(db_slice) .unwrap() .to_string())) } 0x0008 => entry.comment = Some(str::from_utf8(db_slice).unwrap_or("").to_string()), 0x0009 => entry.creation = LoadParser::get_date(db_slice), 0x000A => entry.last_mod = LoadParser::get_date(db_slice), 0x000B => entry.last_access = LoadParser::get_date(db_slice), 0x000C => entry.expire = LoadParser::get_date(db_slice), 0x000D => { entry.binary_desc = Some(str::from_utf8(db_slice) .unwrap_or("") .to_string()) } 0x000E => { entry.binary = Some((0..field_size as usize) .map(|i| db_slice[i]) .collect()) } _ => (), } Ok(()) } // Parse a date. Taken from original KeePass-code fn get_date(date_bytes: &[u8]) -> DateTime<Local> { let dw1 = date_bytes[0] as i32; let dw2 = date_bytes[1] as i32; let dw3 = date_bytes[2] as i32; let dw4 = date_bytes[3] as i32; let dw5 = date_bytes[4] as i32; let year = (dw1 << 6) | (dw2 >> 2); let month = (((dw2 & 0x03) << 2) | (dw3 >> 6)) as u32; let day = ((dw3 >> 1) & 0x1F) as u32; let hour = (((dw3 & 0x01) << 4) | (dw4 >> 4)) as u32; let minute = (((dw4 & 0x0F) << 2) | (dw5 >> 6)) as u32; let second = (dw5 & 0x3F) as u32; Local.ymd(year, month, day).and_hms(hour, minute, second) } // Create the group tree from the level data pub fn create_group_tree(db: &mut V1Kpdb, levels: Vec<u16>) -> Result<(), V1KpdbError> { if levels[0] != 0 { return Err(V1KpdbError::TreeErr); } for i in 0..db.groups.len() { // level 0 means that the group is not a sub group. Hence add it as a children // of the root if levels[i] == 0 { db.groups[i].borrow_mut().parent = Some(db.root_group.clone()); db.root_group .borrow_mut() .children .push(Rc::downgrade(&(db.groups[i].clone()))); continue; } let mut j = i - 1; loop { // Find the first group with a lower level than the current. // That's the parent if levels[j] < levels[i] { if levels[i] - levels[j] != 1 { return Err(V1KpdbError::TreeErr); } db.groups[i].borrow_mut().parent = Some(db.groups[j].clone()); db.groups[j] .borrow_mut() .children .push(Rc::downgrade(&(db.groups[i].clone()))); break; } // It's not possible that a group which comes after another // has a lower level. Hence all following groups which have not // level 0 are a subgroup of another. if j == 0 { return Err(V1KpdbError::TreeErr); } j -= 1; } } // Sort entries to their groups // iter is secure as it is just obfuscated // pointer arithmetic to the entries vector for e in db.entries.iter() { for g in db.groups.iter() { if e.borrow().group_id == g.borrow().id { g.borrow_mut().entries.push(Rc::downgrade(&e.clone())); e.borrow_mut().group = Some(g.clone()); } } } Ok(()) } pub fn delete_decrypted_content(&mut self) { // Zero out raw data as it's not needed anymore unsafe { write_array_volatile(self.decrypted_database.as_ptr() as *mut u8, 0u8, self.decrypted_database.len()); munlock(self.decrypted_database.as_ptr() as *const c_void, self.decrypted_database.len() as size_t); } } } impl Drop for LoadParser { fn drop(&mut self) { self.delete_decrypted_content(); } } // Implements a parser to save a KeePass DB pub struct SaveParser { pub database: Vec<u8>, } impl SaveParser { pub fn new() -> SaveParser { SaveParser { database: vec![], } } pub fn prepare(&mut self, database: &V1Kpdb) { self.save_groups(database); self.save_entries(database); } fn save_groups(&mut self, database: &V1Kpdb) { let mut ret: Vec<u8>; let mut ret_len: u32; for group in &database.groups { for field_type in 1..10 as u16 { ret = SaveParser::save_group_field(group.clone(), field_type); ret_len = ret.len() as u32; if ret_len > 0 { self.database.append(&mut u16_to_vec_u8(field_type)); self.database.append(&mut u32_to_vec_u8(ret_len)); self.database.append(&mut ret); } } self.database.append(&mut vec![0xFFu8, 0xFFu8]); self.database.append(&mut vec![0u8, 0u8, 0u8, 0u8]); } } fn save_entries(&mut self, database: &V1Kpdb) { let mut ret: Vec<u8>; let mut ret_len: u32; for entry in &database.entries { for field_type in 1..15 as u16 { ret = SaveParser::save_entry_field(entry.clone(), field_type); ret_len = ret.len() as u32; if ret_len > 0 { self.database.append(&mut u16_to_vec_u8(field_type)); self.database.append(&mut u32_to_vec_u8(ret_len)); self.database.append(&mut ret); } } self.database.append(&mut vec![0xFFu8, 0xFFu8]); self.database.append(&mut vec![0u8, 0u8, 0u8, 0u8]); } } fn save_group_field(group: Rc<RefCell<V1Group>>, field_type: u16) -> Vec<u8> { match field_type { 0x0001 => return u32_to_vec_u8(group.borrow().id), 0x0002 => { let mut title = group.borrow().title.clone().into_bytes(); title.push(0); return title; }, 0x0003 => return SaveParser::pack_date(&group.borrow().creation), 0x0004 => return SaveParser::pack_date(&group.borrow().last_mod), 0x0005 => return SaveParser::pack_date(&group.borrow().last_access), 0x0006 => return SaveParser::pack_date(&group.borrow().expire), 0x0007 => return u32_to_vec_u8(group.borrow().image), 0x0008 => return u16_to_vec_u8(group.borrow().level), 0x0009 => return u32_to_vec_u8(group.borrow().flags), _ => (), } return vec![]; } fn save_entry_field(entry: Rc<RefCell<V1Entry>>, field_type: u16) -> Vec<u8> { match field_type { 0x0001 => return (&entry.borrow().uuid.simple().to_string()[..]).from_hex().unwrap(), //Should never fail 0x0002 => return u32_to_vec_u8(entry.borrow().group_id), 0x0003 => return u32_to_vec_u8(entry.borrow().image), 0x0004 => { let mut ret = entry.borrow().title.clone().into_bytes(); ret.push(0); return ret; }, 0x0005 => { if let Some(ref url) = entry.borrow().url { let mut ret = url.clone().into_bytes(); ret.push(0); return ret; } }, 0x0006 => { if let Some(ref mut username) = entry.borrow_mut().username { username.unlock(); let mut ret = username.string.clone().into_bytes(); ret.push(0); return ret; } }, 0x0007 => { if let Some(ref mut password) = entry.borrow_mut().password { password.unlock(); let mut ret = password.string.clone().into_bytes(); ret.push(0); return ret; } }, 0x0008 => { if let Some(ref comment) = entry.borrow().comment { let mut ret = comment.clone().into_bytes(); ret.push(0); return ret; } }, 0x0009 => return SaveParser::pack_date(&entry.borrow().creation), 0x000A => return SaveParser::pack_date(&entry.borrow().last_mod), 0x000B => return SaveParser::pack_date(&entry.borrow().last_access), 0x000C => return SaveParser::pack_date(&entry.borrow().expire), 0x000D => { if let Some(ref binary_desc) = entry.borrow().binary_desc { let mut ret = binary_desc.clone().into_bytes(); ret.push(0); return ret; } }, 0x000E => { if let Some(ref binary) = entry.borrow().binary { return binary.clone(); } }, _ => (), } return vec![]; } fn pack_date(date: &DateTime<Local>) -> Vec<u8> { let year = date.year() as i32; let month = date.month() as i32; let day = date.day() as i32; let hour = date.hour() as i32; let minute = date.minute() as i32; let second = date.second() as i32; let dw1 = (0x0000FFFF & ((year>>6) & 0x0000003F)) as u8; let dw2 = (0x0000FFFF & ((year & 0x0000003F)<<2 | ((month>>2) & 0x00000003))) as u8; let dw3 = (0x0000FFFF & (((month & 0x0000003)<<6) | ((day & 0x0000001F)<<1) | ((hour>>4) & 0x00000001))) as u8; let dw4 = (0x0000FFFF & (((hour & 0x0000000F)<<4) | ((minute>>2) & 0x0000000F))) as u8; let dw5 = (0x0000FFFF & (((minute & 0x00000003)<<6) | (second & 0x0000003F))) as u8; vec![dw1, dw2, dw3, dw4, dw5] } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/v1group.rs
src/kpdb/v1group.rs
use std::cell::RefCell; use std::rc::{Rc, Weak}; use chrono::{DateTime, Local, TimeZone}; use kpdb::GetIndex; use kpdb::v1entry::V1Entry; use kpdb::v1error::V1KpdbError; #[doc = " Implements a group of a KeePass v1.x database "] pub struct V1Group { /// Group id unique in the database pub id: u32, /// Title of the group pub title: String, /// Number to specify a icon for the group pub image: u32, /// Level in group tree pub level: u16, /// Date of creation pub creation: DateTime<Local>, /// Date of last modification pub last_mod: DateTime<Local>, /// Date of last access pub last_access: DateTime<Local>, /// Expiration date for the whole group pub expire: DateTime<Local>, /// ?? pub flags: u32, /// Pointer to the parent group pub parent: Option<Rc<RefCell<V1Group>>>, /// Array of weak references to the children pub children: Vec<Weak<RefCell<V1Group>>>, /// Array of weak references to the entries pub entries: Vec<Weak<RefCell<V1Entry>>>, // db: Box<Option<V1Kpdb>>, } impl V1Group { /// Don't use this to create an empty group. /// Normally you want to use the API /// of V1Kpdb to do this. pub fn new() -> V1Group { V1Group { id: 0, title: "".to_string(), image: 0, level: 0, creation: Local::now(), last_mod: Local::now(), last_access: Local::now(), expire: Local.ymd(2999, 12, 28).and_hms(23, 59, 59), flags: 0, parent: None, children: vec![], entries: vec![], // db: box None, } } pub fn drop_weak_child_reference(&mut self, child: &Rc<RefCell<V1Group>>) -> Result<(), V1KpdbError> { let index = try!(self.children.get_index(child)); let weak_group_reference = self.children.remove(index); drop(weak_group_reference); Ok(()) } pub fn drop_weak_entry_reference(&mut self, entry: &Rc<RefCell<V1Entry>>) -> Result<(), V1KpdbError> { let index = try!(self.entries.get_index(entry)); let weak_entry_reference = self.entries.remove(index); drop(weak_entry_reference); Ok(()) } } impl PartialEq for V1Group { fn eq(&self, other: &V1Group) -> bool { self.id == other.id } } impl Eq for V1Group {}
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/v1header.rs
src/kpdb/v1header.rs
use kpdb::v1error::V1KpdbError; // Todo: // * Drop for critical data // * Parsing into LoadParser #[doc = " V1Header implements the header of a KeePass v1.x database. Normally you don't need to mess with this yourself. "] #[derive(Clone)] pub struct V1Header { /// File signature pub signature1: u32, /// File signature pub signature2: u32, /// Describes which encryption algorithm was used. /// 0b10 is for AES, 0b1000 is for Twofish (not /// supported, yet) pub enc_flag: u32, /// Version of the database. 0x00030002 is for v1.x pub version: u32, /// A seed used to create the final key pub final_randomseed: Vec<u8>, /// IV for AEC_CBC to de-/encrypt the database pub iv: Vec<u8>, /// Total number of groups in database pub num_groups: u32, /// Total number of entries in database pub num_entries: u32, /// Hash of the encrypted content to check success /// of decryption pub content_hash: Vec<u8>, /// A seed used to create the final key pub transf_randomseed: Vec<u8>, /// Specifies number of rounds of AES_ECB to create /// the final key pub key_transf_rounds: u32, } impl V1Header { /// Use this to create a new empty header pub fn new() -> V1Header { V1Header { signature1: 0, signature2: 0, enc_flag: 0, version: 0, final_randomseed: vec![], iv: vec![], num_groups: 0, num_entries: 0, content_hash: vec![], transf_randomseed: vec![], key_transf_rounds: 0, } } // Checks file signatures pub fn check_signatures(&self) -> Result<(), V1KpdbError> { if self.signature1 != 0x9AA2D903u32 || self.signature2 != 0xB54BFB65u32 { return Err(V1KpdbError::SignatureErr); } Ok(()) } // Checks encryption flag pub fn check_enc_flag(&self) -> Result<(), V1KpdbError> { if self.enc_flag & 2 != 2 { return Err(V1KpdbError::EncFlagErr); } Ok(()) } // Checks database version pub fn check_version(&self) -> Result<(), V1KpdbError> { if self.version != 0x00030002u32 { return Err(V1KpdbError::VersionErr); } Ok(()) } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/v1error.rs
src/kpdb/v1error.rs
use std::fmt; use std::error; pub use self::V1KpdbError::*; #[doc = " Use this for catching various errors that can happen when using V1Kpdb. "] #[derive(Debug, Clone, PartialEq, Eq, Copy)] pub enum V1KpdbError { /// E.g. Couldn't open a file or file is to /// small. FileErr, /// Something went wrong while the database is /// readed in ReadErr, /// Something went wrong while the database was written WriteErr, /// The file signature in the header is wrong SignatureErr, /// Not supported encryption used EncFlagErr, /// Wrong database version VersionErr, /// Some error in encryption EncryptErr, /// Some error in decryption DecryptErr, /// Hash of decrypted content is wrong. /// Probably the wrong password and/or keyfile /// was used HashErr, /// Some error in parsing ConvertErr, /// Some error in parsing. Probably corrupted database OffsetErr, /// Group tree is corrupted TreeErr, /// Password and/or keyfile needed but at least one of both PassErr, /// Can't find item in Vec IndexErr, /// Tried upgrade of weak reference without strong one WeakErr, } impl fmt::Display for V1KpdbError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(error::Error::description(self)) } } impl error::Error for V1KpdbError { fn description(&self) -> &str { match *self { FileErr => "Couldn't open file or database is too small", ReadErr => "Couldn't read file", WriteErr => "Couldn't write file", SignatureErr => "File signature in header is wrong", EncFlagErr => "Encryption algorithm not supported", VersionErr => "Wrong database version", EncryptErr => "Something went wrong during encryption", DecryptErr => "Something went wrong during decryption", HashErr => "Content's hash is wrong, probably wrong password", ConvertErr => "Some error while parsing the database", OffsetErr => "Some error while parsing the database. Probably a corrupted file", TreeErr => "Group tree is corrupted", PassErr => "Password and/or keyfile needed but at least one of both", IndexErr => "Can't find item in Vec", WeakErr => "Tried upgrade of weak reference without strong one", } } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/v1entry.rs
src/kpdb/v1entry.rs
use std::cell::RefCell; use std::rc::Rc; use chrono::{DateTime, Local, TimeZone}; use uuid::Uuid; use super::v1group::V1Group; use super::super::sec_str::SecureString; #[doc = " Implements an entry in a KeePass v1.x database. "] pub struct V1Entry { /// UUID of the entry pub uuid: Uuid, /// ID of the group holding the entry pub group_id: u32, /// Reference to the group holding the entry pub group: Option<Rc<RefCell<V1Group>>>, /// Used to specify an icon for the entry pub image: u32, /// Title of the entry pub title: String, /// URL for the login pub url: Option<String>, /// Username for the login pub username: Option<SecureString>, /// Password for the login pub password: Option<SecureString>, /// Some comment about the entry pub comment: Option<String>, /// Descripton of the binary content pub binary_desc: Option<String>, /// ??? pub binary: Option<Vec<u8>>, /// Date of creation pub creation: DateTime<Local>, /// Date of last modification pub last_mod: DateTime<Local>, /// Date of last access pub last_access: DateTime<Local>, /// Expiration date pub expire: DateTime<Local>, } impl V1Entry { /// Don't use this to create an empty entry. /// Normally you want to use the API /// of V1Kpdb to do this pub fn new() -> V1Entry { V1Entry { uuid: Uuid::new_v4(), group_id: 0, group: None, image: 0, title: "".to_string(), url: None, username: None, password: None, comment: None, binary_desc: None, binary: None, creation: Local::now(), last_mod: Local::now(), last_access: Local::now(), expire: Local.ymd(2999, 12, 28).and_hms(23, 59, 59), } } } impl PartialEq for V1Entry { fn eq(&self, other: &V1Entry) -> bool { self.uuid == other.uuid } } impl Eq for V1Entry {}
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/tests_parser.rs
src/kpdb/tests_parser.rs
#![allow(dead_code, unused_imports)] use std::io::{Seek, SeekFrom, Read, Write}; use std::fs::File; use chrono::Datelike; use uuid::Uuid; use kpdb::crypter::Crypter; use kpdb::parser::{HeaderLoadParser, LoadParser,SaveParser}; use kpdb::v1header::V1Header; use kpdb::v1kpdb::V1Kpdb; use super::super::sec_str::SecureString; fn setup(path: String, password: Option<String>, keyfile: Option<String>) -> LoadParser { let mut file = File::open(path.clone()).unwrap(); let mut raw: Vec<u8> = vec![]; let _ = file.read_to_end(&mut raw); let encrypted_database = raw.split_off(124); let header_parser = HeaderLoadParser::new(raw); let header = header_parser.parse_header().unwrap(); let mut crypter = Crypter::new(password, keyfile).unwrap(); let mut decrypted_database: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => { decrypted_database = e; } Err(_) => assert!(false), }; LoadParser::new(decrypted_database, header.num_groups, header.num_entries) } #[test] fn test_parse_groups() { let mut parser = setup("test/test_password.kdb".to_string(), Some("test".to_string()), None); let mut groups = vec![]; match parser.parse_groups() { Ok((e, _)) => { groups = e; } Err(_) => assert!(false), } assert_eq!(groups[0].borrow().id, 1); assert_eq!(groups[0].borrow().title, "Internet"); assert_eq!(groups[0].borrow().image, 1); assert_eq!(groups[0].borrow().level, 0); assert_eq!(groups[1].borrow().id, 2); assert_eq!(groups[1].borrow().title, "test"); assert_eq!(groups[1].borrow().image, 1); assert_eq!(groups[1].borrow().level, 0); assert_eq!(groups[1].borrow().creation.year(), 2014); assert_eq!(groups[1].borrow().creation.month(), 2); assert_eq!(groups[1].borrow().creation.day(), 26); } #[test] fn test_parse_entries() { let uuid = Uuid::from_bytes(&[0x0c, 0x31, 0xac, 0x94, 0x23, 0x47, 0x66, 0x36, 0xb8, 0xc0, 0x42, 0x81, 0x5e, 0x5a, 0x14, 0x60]) .unwrap(); let mut parser = setup("test/test_password.kdb".to_string(), Some("test".to_string()), None); match parser.parse_groups() { Ok((_, _)) => {} Err(_) => assert!(false), }; let mut entries = vec![]; match parser.parse_entries() { Ok(e) => { entries = e; } Err(_) => assert!(false), } entries[0].borrow_mut().username.as_mut().unwrap().unlock(); entries[0].borrow_mut().password.as_mut().unwrap().unlock(); assert_eq!(entries[0].borrow().uuid, uuid); assert_eq!(entries[0].borrow().title, "foo"); assert_eq!(entries[0].borrow().url, Some("foo".to_string())); assert_eq!(entries[0].borrow().username.as_ref().unwrap().string, "foo"); assert_eq!(entries[0].borrow().password.as_ref().unwrap().string, "DLE\"H<JZ|E"); assert_eq!(entries[0].borrow().image, 1); assert_eq!(entries[0].borrow().group_id, 1); assert_eq!(entries[0].borrow().creation.year(), 2014); assert_eq!(entries[0].borrow().creation.month(), 2); assert_eq!(entries[0].borrow().creation.day(), 26); } fn get_parent_title(index: usize, db: &V1Kpdb) -> String { let mut group = db.groups[index].borrow_mut(); let parent = group.parent.as_mut().unwrap().borrow(); parent.title.clone() } fn get_children_title(parent_index: usize, children_index: usize, db: &V1Kpdb) -> String { let group = db.groups[parent_index].borrow_mut(); let children_ref = group.children[children_index].upgrade().unwrap(); let children = children_ref.borrow(); children.title.clone() } fn get_entry_parent_title(index: usize, db: &V1Kpdb) -> String { let mut entry = db.entries[index].borrow_mut(); let group = entry.group.as_mut().unwrap().borrow(); group.title.clone() } #[test] fn test_create_group_tree() { let mut db = V1Kpdb::new("test/test_parsing.kdb".to_string(), Some("test".to_string()), None) .ok() .unwrap(); assert_eq!(db.load().is_ok(), true); assert_eq!(get_parent_title(1, &db), "Internet"); assert_eq!(get_parent_title(2, &db), "Internet"); assert_eq!(get_children_title(2, 0, &db), "22"); assert_eq!(get_children_title(2, 1, &db), "21"); assert_eq!(get_parent_title(3, &db), "11"); assert_eq!(get_parent_title(4, &db), "11"); assert_eq!(get_children_title(4, 0, &db), "32"); assert_eq!(get_children_title(4, 1, &db), "31"); assert_eq!(get_parent_title(5, &db), "21"); assert_eq!(get_parent_title(6, &db), "21"); assert_eq!(get_entry_parent_title(0, &db), "Internet"); assert_eq!(get_entry_parent_title(1, &db), "11"); assert_eq!(get_entry_parent_title(2, &db), "12"); assert_eq!(get_entry_parent_title(3, &db), "21"); assert_eq!(get_entry_parent_title(4, &db), "22"); } #[test] fn test_read_header() { let mut file = File::open("test/test_password.kdb".to_string()).unwrap(); let mut raw: Vec<u8> = vec![]; let _ = file.read_to_end(&mut raw); let _ = raw.split_off(124); let header_parser = HeaderLoadParser::new(raw); let mut header = V1Header::new(); match header_parser.parse_header() { Ok(h) => { header = h; } Err(_) => assert!(false), } assert_eq!(header.signature1, 0x9AA2D903u32); assert_eq!(header.signature2, 0xB54BFB65u32); assert_eq!(header.enc_flag & 2, 2); assert_eq!(header.version, 0x00030002u32); assert_eq!(header.num_groups, 2); assert_eq!(header.num_entries, 1); assert_eq!(header.key_transf_rounds, 150000); assert_eq!(header.final_randomseed[0], 0xB0u8); assert_eq!(header.final_randomseed[15], 0xE1u8); assert_eq!(header.iv[0], 0x15u8); assert_eq!(header.iv[15], 0xE5u8); assert_eq!(header.content_hash[0], 0xCBu8); assert_eq!(header.content_hash[15], 0x4Eu8); assert_eq!(header.transf_randomseed[0], 0x69u8); assert_eq!(header.transf_randomseed[15], 0x9Fu8); } #[test] fn test_prepare_save() { let test_1 = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x00, 0x03, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1f, 0x80, 0xae, 0xf4, 0x64, ]; let test_2 = vec![0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, ]; let test_3 = vec![0x05, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1f, 0x79, 0x09, 0x71, 0x08, 0x06, 0x00, 0x05, 0x00, 0x00, 0x00, 0x2e, 0xdf, 0x39, 0x7e, 0xfb, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, ]; let test_4 = vec![0x31, 0x31, 0x00, 0x03, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1f, 0x79, 0x09, 0x71, 0x04, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1f, 0x79, 0x09, 0x71, 0x0e, 0x05, 0x00, 0x05, 0x00, 0x00, 0x00, 0x1f, 0x79, 0x09, 0x71, 0x04, ]; let mut db = V1Kpdb::new("test/test_save.kdb".to_string(), Some("test".to_string()), None) .ok() .unwrap(); assert_eq!(db.load().is_ok(), true); let mut parser = SaveParser::new(); parser.prepare(&db); println!("{:?}", parser.database); assert_eq!(test_1[..], parser.database[0..36]); assert_eq!(test_2[..], parser.database[72..108]); assert_eq!(test_3[..], parser.database[144..180]); assert_eq!(test_4[..], parser.database[216..252]); }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/mod.rs
src/kpdb/mod.rs
pub mod v1kpdb; pub mod v1error; pub mod v1group; pub mod v1entry; pub mod v1header; mod crypter; mod parser; #[cfg(test)] mod tests_v1kpdb; mod tests_parser; mod tests_crypter; use std::rc::Weak; use self::v1error::V1KpdbError; trait GetIndex<T> { fn get_index(&self, item: &T) -> Result<usize, V1KpdbError>; } impl<T: Eq> GetIndex<T> for Vec<T> { fn get_index(&self, item: &T) -> Result<usize, V1KpdbError> { for index in 0..self.len() { if self[index] == *item { return Ok(index); } } Err(V1KpdbError::IndexErr) } } impl<T: Eq> GetIndex<T> for Vec<Weak<T>> { fn get_index(&self, item: &T) -> Result<usize, V1KpdbError> { for index in 0..self.len() { if let Some(cmp_item) = self[index].upgrade() { if *cmp_item == *item { return Ok(index); } } else { return Err(V1KpdbError::WeakErr); } } Err(V1KpdbError::IndexErr) } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/crypter.rs
src/kpdb/crypter.rs
use libc::{c_void, mlock, munlock, size_t}; use std::fs::File; use std::io::{Seek, SeekFrom, Read, Write}; use openssl::hash; use openssl::symm; use rustc_serialize::hex::FromHex; use sec_str::SecureString; use common::common::write_array_volatile; use kpdb::v1error::V1KpdbError; use kpdb::v1header::V1Header; // implements a crypter to de- and encrypt a KeePass DB pub struct Crypter { password: Option<SecureString>, keyfile: Option<SecureString>, } // Sensitive data in Crypter overall // * finalkey: created in transform_key, zeroed out in en-/decrypt_raw // * masterkey: created in get_finalkey, lock depends on method, zeroed out in transform_key // * decrypted_database: // ** decryption: created in decrypt_raw, moved out of Crypted // ** encryption: created and locked outside of Crypter, zeroed out in encrypt_raw // * passwordkey: created in get_passwordkey, zeroed out in get_finalkey // * keyfilekey: created in get_keyfilekey, zeroed out in get_finalkey // * masterkey_tmp: created in get_finalkey, moved into masterkey // * password: is a reference to a SecureString and is handled correctly in get_passwordkey // * password_string: is a reference to password.string // * keyfile: is a reference to a SecureString and is handled correctly in get_keyfilekey // * key: created in get_keyfilekey, moved into keyfilekey or is zeroed out in get_keyfile_key // * decoded_key: created in get_keyfilekey, moved into keyfilekey // * buf: created and zeroed out in get_keyfilekey impl Crypter { // Decrypt the database and return the raw data as Vec<u8> // Sensitive data in this function: // // * password // * keyfile // // Both are moved out of new into SecureString pub fn new(password: Option<String>, keyfile: Option<String>) -> Result<Crypter, V1KpdbError> { match (password, keyfile) { (Some(p), None) => Ok(Crypter { password: Some(SecureString::new(p)), keyfile: None, }), (None, Some(k)) => Ok(Crypter { password: None, keyfile: Some(SecureString::new(k)), }), (Some(p), Some(k)) => Ok(Crypter { password: Some(SecureString::new(p)), keyfile: Some(SecureString::new(k)), }), (None, None) => Err(V1KpdbError::PassErr), } } // Sensitive data in this function: // // * password moved out of function // // Old password's SecureString is deleted through Drop pub fn change_password(&mut self, password: Option<String>) -> Result<(), V1KpdbError> { // Weird construct because self.keyfile in second match // creates compiler errors due to invalid borrowing let keyfile_option = match self.keyfile { Some(_) => Some(()), None => None, }; match (password, keyfile_option) { (None, None) => return Err(V1KpdbError::PassErr), (None, Some(())) => self.password = None, (Some(p), _) => self.password = Some(SecureString::new(p)), }; Ok(()) } // Sensitive data in this function: // // * keyfile moved out of function // // Old keyfiles's SecureString is deleted through Drop pub fn change_keyfile(&mut self, keyfile: Option<String>) -> Result<(), V1KpdbError> { // Weird construct because self.password in second match // creates compiler errors due to invalid borrowing let password_option = match self.password { Some(_) => Some(()), None => None, }; match (password_option, keyfile) { (None, None) => return Err(V1KpdbError::PassErr), (Some(()), None) => self.keyfile = None, (_, Some(k)) => self.keyfile = Some(SecureString::new(k)), }; Ok(()) } // Sensitive data in this function: // * finalkey (locked: transform_key) // * decrypted_database (locked: decrypt_raw) // // At the end of this function: // * decrypted database moved out of function // * finalkey has moved to decrypt_raw // // decrypted database is locked through decrypt_raw pub fn decrypt_database(&mut self, header: &V1Header, encrypted_database: Vec<u8>) -> Result<Vec<u8>, V1KpdbError> { let finalkey = try!(self.get_finalkey(header)); let decrypted_database = try!(Crypter::decrypt_raw(header, encrypted_database, finalkey)); try!(Crypter::check_decryption_success(header, &decrypted_database)); try!(Crypter::check_content_hash(header, &decrypted_database)); Ok(decrypted_database) } // Sensitive data in this function: // * finalkey (locked: transform_key) // * decrypted_database // // At the end of this function: // * decrypted database has moved to encrypt_raw // * finalkey has moved to encrypt_raw pub fn encrypt_database(&mut self, header: &V1Header, decrypted_database: Vec<u8>) -> Result<Vec<u8>, V1KpdbError> { let finalkey = try!(self.get_finalkey(header)); Crypter::encrypt_raw(header, decrypted_database, finalkey) } // Sensitive data in this function: // * masterkey // * passwordkey (locked: get_passwordkey) // * keyfilekey (locked: get_keyfilekey) // * finalkey (locked: transform_key) // * masterkey_tmp // // At the end of this function: // * masterkey has moved to transform_key and is locked // * passwordkey is zeroed out // * keyfilekey is zeroed out // * finalkey moved out of function // * masterkey_tmp is locked and moved into masterkey // // passwordkey and keyfilekey are locked until procession // p and k are locked through SecureString fn get_finalkey(&mut self, header: &V1Header) -> Result<Vec<u8>, V1KpdbError> { let masterkey = match (&mut self.password, &mut self.keyfile) { // Only password provided (&mut Some(ref mut p), &mut None) => try!(Crypter::get_passwordkey(p)), // Only keyfile provided (&mut None, &mut Some(ref mut k)) => try!(Crypter::get_keyfilekey(k)), // Both provided (&mut Some(ref mut p), &mut Some(ref mut k)) => { // Get hashed keys... let passwordkey = try!(Crypter::get_passwordkey(p)); let keyfilekey = try!(Crypter::get_keyfilekey(k)); // ...and hash them together let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Can't hash passwords!?"); try!(hasher.write_all(&passwordkey) .map_err(|_| V1KpdbError::DecryptErr)); try!(hasher.write_all(&keyfilekey) .map_err(|_| V1KpdbError::DecryptErr)); let masterkey_tmp = hasher.finish2().expect("Can't hash masterkey"); // Zero out unneeded keys and lock masterkey unsafe { write_array_volatile(passwordkey.as_ptr() as *mut u8, 0u8, passwordkey.len()); write_array_volatile(keyfilekey.as_ptr() as *mut u8, 0u8, keyfilekey.len()); munlock(passwordkey.as_ptr() as *const c_void, passwordkey.len() as size_t); munlock(keyfilekey.as_ptr() as *const c_void, keyfilekey.len() as size_t); mlock(masterkey_tmp.as_ptr() as *const c_void, masterkey_tmp.len() as size_t); } masterkey_tmp.to_vec() } (&mut None, &mut None) => return Err(V1KpdbError::PassErr), }; let finalkey = try!(Crypter::transform_key(masterkey, header)); Ok(finalkey) } // Hash the password string to create a decryption key from that // Sensitive data in this function: // * password // * password_string // * passwordkey // // At the end of this function: // * password is zeroed out // * password_string is deleted (is a reference to password.string) // * passwordkey is moved out of function and locked fn get_passwordkey(password: &mut SecureString) -> Result<Vec<u8>, V1KpdbError> { password.unlock(); let password_string = password.string.as_bytes(); let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Can't creater hasher!?"); try!(hasher.write_all(password_string) .map_err(|_| V1KpdbError::DecryptErr)); password.delete(); // hasher.finish() is a move and therefore secure let passwordkey = hasher.finish2().expect("Can't hash password!?"); unsafe { mlock(passwordkey.as_ptr() as *const c_void, passwordkey.len() as size_t); } Ok(passwordkey.to_vec()) } // Get key from keyfile // Sensitive data in this function: // * keyfile // * key // * decoded_key // * buf // * file // // At the end of this function: // * keyfile is deleted // * key has moved out of function and is locked or is deleted (file_size==64) // * decoded_key has moved out of function and is locked // * buf is deleted // * file ... TODO // // buf and key are locked during procession fn get_keyfilekey(keyfile: &mut SecureString) -> Result<Vec<u8>, V1KpdbError> { keyfile.unlock(); let mut file = try!(File::open(&keyfile.string).map_err(|_| V1KpdbError::FileErr)); // unsafe { // mlock(file.as_ptr() as *const c_void, // file.len() as size_t); // } keyfile.delete(); let file_size = try!(file.seek(SeekFrom::End(0i64)) .map_err(|_| V1KpdbError::FileErr)); try!(file.seek(SeekFrom::Start(0u64)) .map_err(|_| V1KpdbError::FileErr)); if file_size == 32 { let mut key: Vec<u8> = vec![]; try!(file.read_to_end(&mut key).map_err(|_| V1KpdbError::ReadErr)); unsafe { mlock(key.as_ptr() as *const c_void, key.len() as size_t); // intrinsics::volatile_set_memory(&file as *mut c_void, // 0u8, // mem::size_of::<File>()); } return Ok(key); } else if file_size == 64 { // interpret characters as encoded hex if possible (e.g. "FF" => 0xff) let mut key: String = "".to_string(); unsafe { mlock(key.as_ptr() as *const c_void, key.len() as size_t); } match file.read_to_string(&mut key) { Ok(_) => { match (&key[..]).from_hex() { Ok(decoded_key) => { unsafe { // intrinsics::volatile_set_memory(&file as *mut c_void, // 0u8, // mem::size_of::<File>()); mlock(decoded_key.as_ptr() as *const c_void, decoded_key.len() as size_t); write_array_volatile(key.as_ptr() as *mut u8, 0u8, key.len()); munlock(key.as_ptr() as *const c_void, key.len() as size_t); } return Ok(decoded_key) }, Err(_) => {} } } Err(_) => { unsafe { write_array_volatile(key.as_ptr() as *mut u8, 0u8, key.len()); munlock(key.as_ptr() as *const c_void, key.len() as size_t); } try!(file.seek(SeekFrom::Start(0u64)) .map_err(|_| V1KpdbError::FileErr)); } } } // Read up to 2048 bytes and hash them let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Can't create hasher!?"); let mut buf: Vec<u8> = vec![]; unsafe { mlock(buf.as_ptr() as *const c_void, buf.len() as size_t); } loop { buf = vec![0; 2048]; match file.read(&mut buf[..]) { Ok(n) => { if n == 0 { break; }; buf.truncate(n); try!(hasher.write_all(&buf[..]) .map_err(|_| V1KpdbError::DecryptErr)); unsafe { write_array_volatile(buf.as_ptr() as *mut u8, 0u8, buf.len()) }; } Err(_) => { return Err(V1KpdbError::ReadErr); } } } let key = hasher.finish2().expect("Can't hash key!?"); unsafe { // intrinsics::volatile_set_memory(&file as *mut c_void, // 0u8, // mem::size_of::<File>()); munlock(buf.as_ptr() as *const c_void, buf.len() as size_t); mlock(key.as_ptr() as *const c_void, key.len() as size_t); } Ok(key.to_vec()) } // Create the finalkey from the masterkey by encrypting it with some // random seeds from the database header and AES_ECB // // Sensitive data in this function: // * masterkey (locked: get_finalkey) // * finalkey // // At the end of this function: // * masterkey is zeroed out // * finalkey is locked and moved out of function fn transform_key(mut masterkey: Vec<u8>, header: &V1Header) -> Result<Vec<u8>, V1KpdbError> { let mut crypter = symm::Crypter::new(symm::Cipher::aes_256_ecb(), symm::Mode::Encrypt, &header.transf_randomseed, None).expect("Can't create crypter!?"); let mut transformed_key = vec![0; masterkey.len() + symm::Cipher::aes_256_cbc().block_size()]; for _ in 0..header.key_transf_rounds { let _ = crypter.update(&masterkey, &mut transformed_key); transformed_key.truncate(masterkey.len()); masterkey = transformed_key.clone(); transformed_key = vec![0; masterkey.len() + symm::Cipher::aes_256_cbc().block_size()]; } // Because rust-openssl needs a vector length of masterkey.len() + block_size let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Could not create Hasher!?"); try!(hasher.write_all(&masterkey) .map_err(|_| V1KpdbError::DecryptErr)); masterkey = hasher.finish2().expect("Could not hash masterkey!?").to_vec(); let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Could not create Hasher!?"); try!(hasher.write_all(&header.final_randomseed) .map_err(|_| V1KpdbError::DecryptErr)); try!(hasher.write_all(&masterkey) .map_err(|_| V1KpdbError::DecryptErr)); let finalkey = hasher.finish2().expect("Could not hash finalkey!?"); // Zero out masterkey as it is not needed anymore unsafe { write_array_volatile(masterkey.as_ptr() as *mut u8, 0u8, masterkey.len()); munlock(masterkey.as_ptr() as *const c_void, masterkey.len() as size_t); mlock(finalkey.as_ptr() as *const c_void, finalkey.len() as size_t); } Ok(finalkey.to_vec()) } // Decrypt the raw data and return it // // Sensitive data in this function: // * finalkey (locked: transform_key) // * decrypted_database // // At the end of this function: // * finalkey is deleted // * decrypted_database is locked and moved out of function // // finalkey is locked through transform_key fn decrypt_raw(header: &V1Header, encrypted_database: Vec<u8>, finalkey: Vec<u8>) -> Result<Vec<u8>, V1KpdbError> { let mut decrypted_database = try!(symm::decrypt(symm::Cipher::aes_256_cbc(), &finalkey, Some(header.iv.as_slice()), &encrypted_database).map_err(|_| V1KpdbError::DecryptErr)); // Zero out finalkey as it is not needed anymore unsafe { write_array_volatile(finalkey.as_ptr() as *mut u8, 0u8, finalkey.len()); munlock(finalkey.as_ptr() as *const c_void, finalkey.len() as size_t); } // Delete padding from decrypted data let padding = decrypted_database[decrypted_database.len() - 1] as usize; let length = decrypted_database.len(); // resize() is safe as just padding is dropped decrypted_database.resize(length - padding, 0); unsafe { mlock(decrypted_database.as_ptr() as *const c_void, decrypted_database.len() as size_t); } Ok(decrypted_database) } fn encrypt_raw(header: &V1Header, decrypted_database: Vec<u8>, finalkey: Vec<u8>) -> Result<Vec<u8>, V1KpdbError> { let encrypted_database = try!(symm::encrypt(symm::Cipher::aes_256_cbc(), &finalkey, Some(header.iv.as_slice()), &decrypted_database).map_err(|_| V1KpdbError::EncryptErr)); // Zero out finalkey as it is not needed anymore unsafe { write_array_volatile(finalkey.as_ptr() as *mut u8, 0u8, finalkey.len()); munlock(finalkey.as_ptr() as *const c_void, finalkey.len() as size_t); write_array_volatile(decrypted_database.as_ptr() as *mut u8, 0u8, decrypted_database.len()); munlock(decrypted_database.as_ptr() as *const c_void, decrypted_database.len() as size_t); } Ok(encrypted_database) } // Check some conditions // Sensitive data in this function // * decrypted_content (locked: decrypt_raw) // // At the end of the function: // * decrypted_content hasn't changed (it's a reference) fn check_decryption_success(header: &V1Header, decrypted_content: &Vec<u8>) -> Result<(), V1KpdbError> { if (decrypted_content.len() > 2147483446) || (decrypted_content.len() == 0 && header.num_groups > 0) { return Err(V1KpdbError::DecryptErr); } Ok(()) } // Sensitive data in this function // * decrypted_content (locked: decrypt_raw or ...) // // At the end of the function: // * decrypted_content hasn't changed (it's a reference) pub fn get_content_hash(decrypted_content: &Vec<u8>) -> Result<Vec<u8>, V1KpdbError> { let mut hasher = hash::Hasher::new(hash::MessageDigest::sha256()).expect("Could not create hasher!?"); try!(hasher.write_all(&decrypted_content) .map_err(|_| V1KpdbError::DecryptErr)); Ok(hasher.finish2().expect("Can't hash decrypted concent!?").to_vec()) } // Check some more conditions // Sensitive data in this function // * decrypted_content (locked: decrypt_raw) // // At the end of the function: // * decrypted_content hasn't changed (it's a reference) fn check_content_hash(header: &V1Header, decrypted_content: &Vec<u8>) -> Result<(), V1KpdbError> { let content_hash = try!(Crypter::get_content_hash(decrypted_content)); if content_hash != header.content_hash { return Err(V1KpdbError::HashErr); } Ok(()) } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/v1kpdb.rs
src/kpdb/v1kpdb.rs
use std::cell::RefCell; use std::rc::Rc; use std::io::{Read, Write}; use std::fs::File; use chrono::{DateTime, Local}; use rand; use kpdb::GetIndex; use kpdb::crypter::Crypter; use kpdb::parser::{HeaderLoadParser, HeaderSaveParser, LoadParser, SaveParser}; use kpdb::v1error::V1KpdbError; use kpdb::v1group::V1Group; use kpdb::v1entry::V1Entry; use kpdb::v1header::V1Header; use super::super::sec_str::SecureString; #[doc = " V1Kpdb implements a KeePass v1.x database. Some notes on the file format: * Database is encrypted with AES (Twofish currently not supported by this module) with a password and/or a keyfile. * Database holds entries which describes the credentials (username, password URL...) and are sorted in groups * The groups themselves can hold subgroups * Entries have titles for better identification by the user and expiration dates to remind that the password should be changed after some period TODO: * saving * editing * use more pattern matching * usage examples * use mlock in proper places (editing) "] pub struct V1Kpdb { /// Filepath of the database pub path: String, /// Holds the header. Normally you don't need /// to manipulate this yourself pub header: V1Header, /// The groups which hold the entries pub groups: Vec<Rc<RefCell<V1Group>>>, /// The entries of the whole database pub entries: Vec<Rc<RefCell<V1Entry>>>, /// A group which holds all groups of level 0 /// as a subgroup (all groups which are not a /// subgroup of another group ) pub root_group: Rc<RefCell<V1Group>>, // Used to de- and encrypt the database crypter: Crypter, } impl V1Kpdb { /// Call this to create a new database instance. You have to call load /// to start decrypting and parsing of an existing database! /// path is the filepath of the database, password is the database password /// and keyfile is the filepath to the keyfile. /// password should already lie on the heap as a String type and not &str /// as it will be encrypted automatically and otherwise the plaintext /// would lie in the memory though pub fn new(path: String, password: Option<String>, keyfile: Option<String>) -> Result<V1Kpdb, V1KpdbError> { Ok(V1Kpdb { path: path, header: V1Header::new(), groups: vec![], entries: vec![], root_group: Rc::new(RefCell::new(V1Group::new())), crypter: try!(Crypter::new(password, keyfile)), }) } /// Decrypt and parse the database. pub fn load(&mut self) -> Result<(), V1KpdbError> { let (header, encrypted_database) = try!(self.read_in_file()); // First read header and decrypt the database let header_parser = HeaderLoadParser::new(header); self.header = try!(header_parser.parse_header()); try!(self.check_header()); let decrypted_database = try!(self.crypter .decrypt_database(&self.header, encrypted_database)); // Next parse groups and entries. // pos is needed to remember position after group parsing let mut parser = LoadParser::new(decrypted_database, self.header.num_groups, self.header.num_entries); let (groups, levels) = try!(parser.parse_groups()); self.groups = groups; self.entries = try!(parser.parse_entries()); parser.delete_decrypted_content(); // Now create the group tree and sort the entries to their groups try!(LoadParser::create_group_tree(self, levels)); Ok(()) } fn read_in_file(&self) -> Result<(Vec<u8>, Vec<u8>), V1KpdbError> { let mut file = try!(File::open(&self.path).map_err(|_| V1KpdbError::FileErr)); let mut raw: Vec<u8> = vec![]; try!(file.read_to_end(&mut raw).map_err(|_| V1KpdbError::ReadErr)); let encrypted_database = raw.split_off(124); Ok((raw, encrypted_database)) } fn check_header(&self) -> Result<(), V1KpdbError> { try!(self.header.check_signatures()); try!(self.header.check_enc_flag()); try!(self.header.check_version()); Ok(()) } pub fn save(&mut self, path: Option<String>, password: Option<String>, keyfile: Option<String>) -> Result<(), V1KpdbError> { let mut parser = SaveParser::new(); parser.prepare(self); let mut header = self.header.clone(); header.final_randomseed = (0..16).map(|_| rand::random::<u8>()).collect(); header.iv = (0..16).map(|_| rand::random::<u8>()).collect(); header.content_hash = try!(Crypter::get_content_hash(&parser.database)); if let Some(new_password) = password { if new_password == "".to_string() { self.crypter.change_password(None); } else { self.crypter.change_password(Some(new_password)); } } if let Some(new_keyfile) = keyfile { if new_keyfile == "".to_string() { self.crypter.change_keyfile(None); } else { self.crypter.change_keyfile(Some(new_keyfile)); } } let encrypted_database = try!(self.crypter.encrypt_database(&header, parser.database)); let mut header_parser = HeaderSaveParser::new(header); let header_raw = header_parser.parse_header(); if let Some(new_path) = path { self.path = new_path } let mut file = try!(File::create(&self.path).map_err(|_| V1KpdbError::FileErr)); try!(file.write_all(&header_raw).map_err(|_| V1KpdbError::WriteErr)); try!(file.write_all(&encrypted_database).map_err(|_| V1KpdbError::WriteErr)); try!(file.flush().map_err(|_| V1KpdbError::WriteErr)); Ok(()) } /// Create a new group /// /// * title: title of the new group /// /// * expire: expiration date of the group /// None means that the group expires never which itself /// corresponds to the date 28-12-2999 23:59:59 /// /// * image: an image number, used in KeePass and KeePassX for the group /// icon. None means 0 /// /// * parent: a group inside the groups vector which should be the parent in /// the group tree. None means that the root group is the parent pub fn create_group(&mut self, title: String, expire: Option<DateTime<Local>>, image: Option<u32>, parent: Option<Rc<RefCell<V1Group>>>) -> Result<(), V1KpdbError> { let mut new_id: u32 = 1; for group in self.groups.iter() { let id = group.borrow().id; if id >= new_id { new_id = id + 1; } } let new_group = Rc::new(RefCell::new(V1Group::new())); new_group.borrow_mut().id = new_id; new_group.borrow_mut().title = title; new_group.borrow_mut().creation = Local::now(); new_group.borrow_mut().last_mod = Local::now(); new_group.borrow_mut().last_access = Local::now(); match expire { Some(s) => new_group.borrow_mut().expire = s, None => {} // is 12-28-2999 23:59:59 through V1Group::new } match image { Some(s) => new_group.borrow_mut().image = s, None => {} // is 0 through V1Group::new } match parent { Some(s) => { let index = try!(self.groups.get_index(&s)); new_group.borrow_mut().parent = Some(s.clone()); s.borrow_mut().children.push(Rc::downgrade(&new_group.clone())); self.groups.insert(index + 1, new_group); } None => { new_group.borrow_mut().parent = Some(self.root_group .clone()); self.root_group.borrow_mut().children.push(Rc::downgrade(&new_group.clone())); self.groups.push(new_group); } } self.header.num_groups += 1; Ok(()) } /// Create a new entry /// /// * group: group which should hold the entry /// /// * title: title of the new entry /// /// * expire: expiration date of the group /// None means that the group expires never which itself /// corresponds to the date 28-12-2999 23:59:59 /// /// * image: an image number, used in KeePass and KeePassX for the group /// icon. None means 0 /// /// * url: URL from where the credentials are /// /// * comment: some free-text-comment about the entry /// /// * username: username for the URL /// /// * password: password for the URL /// /// Note: username and password should be of type String at creation. If you have a /// &str which you convert into a String with to_string() the plaintext will remain /// in memory as the new created String is a copy of the original &str. If you use /// String this function call is a move so that the String remains where it was /// created. /// pub fn create_entry(&mut self, group: Rc<RefCell<V1Group>>, title: String, expire: Option<DateTime<Local>>, image: Option<u32>, url: Option<String>, comment: Option<String>, username: Option<String>, password: Option<String>) { // Automatically creates a UUID for the entry let new_entry = Rc::new(RefCell::new(V1Entry::new())); new_entry.borrow_mut().title = title; new_entry.borrow_mut().group = Some(group.clone()); group.borrow_mut().entries.push(Rc::downgrade(&new_entry.clone())); new_entry.borrow_mut().group_id = group.borrow().id; new_entry.borrow_mut().creation = Local::now(); new_entry.borrow_mut().last_mod = Local::now(); new_entry.borrow_mut().last_access = Local::now(); match expire { Some(s) => new_entry.borrow_mut().expire = s, None => {} // is 12-28-2999 23:59:59 through V1Entry::new() }; match image { Some(s) => new_entry.borrow_mut().image = s, None => {} // is 0 through V1Entry::new() } new_entry.borrow_mut().url = url; new_entry.borrow_mut().comment = comment; match username { Some(s) => new_entry.borrow_mut().username = Some(SecureString::new(s)), None => {} }; match password { Some(s) => new_entry.borrow_mut().password = Some(SecureString::new(s)), None => {} }; self.entries.push(new_entry); self.header.num_entries += 1; } /// Remove a group /// /// * group: The group to remove /// /// Note: Entries and children of the group are deleted, too. /// /// The group should be given to the function as a move. If this is done, the rc counter /// is 0 at the end of the function and therefore sensitive data is deleted correctly. pub fn remove_group(&mut self, group: Rc<RefCell<V1Group>>) -> Result<(), V1KpdbError> { // Sensitive data (e.g. SecureString) is automatically dropped at the end of this // function as Rc is 0 then try!(self.remove_group_from_db(&group)); try!(self.remove_entries(&group)); if let Some(ref parent) = group.borrow().parent { try!(parent.borrow_mut().drop_weak_child_reference(&group)); drop(parent); } try!(self.remove_children(&group)); Ok(()) } fn remove_group_from_db(&mut self, group: &Rc<RefCell<V1Group>>) -> Result<(), V1KpdbError> { let index = try!(self.groups.get_index(group)); let db_reference = self.groups.remove(index); drop(db_reference); self.header.num_groups -= 1; Ok(()) } fn remove_entry_from_db(&mut self, entry: &Rc<RefCell<V1Entry>>) -> Result<(), V1KpdbError> { let index = try!(self.entries.get_index(entry)); let db_reference = self.entries.remove(index); drop(db_reference); self.header.num_entries -= 1; Ok(()) } fn remove_entries(&mut self, group: &Rc<RefCell<V1Group>>) -> Result<(), V1KpdbError> { // Clone needed to prevent thread panning through borrowing let entries = group.borrow().entries.clone(); for entry in entries { if let Some(entry_strong) = entry.upgrade() { try!(self.remove_entry(entry_strong)); } else { return Err(V1KpdbError::WeakErr); } } Ok(()) } fn remove_children(&mut self, group: &Rc<RefCell<V1Group>>) -> Result<(), V1KpdbError> { // Clone needed to prevent thread panning through borrowing let children = group.borrow().children.clone(); for child in children { if let Some(child_strong) = child.upgrade() { try!(self.remove_group(child_strong)); } else { return Err(V1KpdbError::WeakErr); } } Ok(()) } /// Remove a group /// /// * entry: The entry to remove. /// /// Note: The entry should be given to the function as a move. If this is done, the rc counter /// is 0 at the end of the function and therefore sensitive data is deleted correctly. pub fn remove_entry(&mut self, entry: Rc<RefCell<V1Entry>>) -> Result<(), V1KpdbError> { // Sensitive data (e.g. SecureString) is automatically dropped at the end of this // function as Rc is 0 then try!(self.remove_entry_from_db(&entry)); if let Some(ref group) = entry.borrow().group { try!(group.borrow_mut().drop_weak_entry_reference(&entry)); drop(group); } Ok(()) } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/kpdb/tests_crypter.rs
src/kpdb/tests_crypter.rs
#![allow(dead_code)] use std::fs::File; use std::io::Read; use kpdb::parser::HeaderLoadParser; use kpdb::crypter::Crypter; use kpdb::v1header::V1Header; use super::super::sec_str::SecureString; fn setup(path: String, password: Option<String>, keyfile: Option<String>) -> (Crypter, V1Header, Vec<u8>) { let mut file = File::open(path.clone()).unwrap(); let mut raw: Vec<u8> = vec![]; let _ = file.read_to_end(&mut raw); let encrypted_database = raw.split_off(124); let header_parser = HeaderLoadParser::new(raw); let header = header_parser.parse_header().unwrap(); let crypter = Crypter::new(password, keyfile).unwrap(); (crypter, header, encrypted_database) } #[test] fn test_decrypt_it_w_pass() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_password.kdb".to_string(), Some("test".to_string()), None); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_32_b_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_32B_key.kdb".to_string(), None, Some("test/32Bkey".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_64_b_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_64B_key.kdb".to_string(), None, Some("test/64Bkey".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_64_b_alt_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_64B_alt_key.kdb".to_string(), None, Some("test/64Bkey_alt".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_128_b_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_128B_key.kdb".to_string(), None, Some("test/128Bkey".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_2048_b_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_2048B_key.kdb".to_string(), None, Some("test/2048Bkey".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_4096_b_key() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_4096B_key.kdb".to_string(), None, Some("test/4096Bkey".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); } #[test] fn test_decrypt_it_w_both() { let test_content1: Vec<u8> = vec![0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x09, 0x00, 0x00, 0x00]; let test_content2: Vec<u8> = vec![0x00, 0x05, 0x00, 0x00, 0x00, 0x1F, 0x7C, 0xB5, 0x7E, 0xFB, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00]; let (mut crypter, header, encrypted_database) = setup("test/test_both.kdb".to_string(), Some("test".to_string()), Some("test/test_key".to_string())); let mut db_tmp: Vec<u8> = vec![]; match crypter.decrypt_database(&header, encrypted_database) { Ok(e) => db_tmp = e, Err(_) => assert!(false), }; let db_len = db_tmp.len(); let test1 = &db_tmp[0..16]; let test2 = &db_tmp[db_len - 16..db_len]; assert_eq!(test_content1, test1); assert_eq!(test_content2, test2); }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/common/mod.rs
src/common/mod.rs
pub mod common; pub mod common_error; //#[cfg(tests)] //mod tests_common;
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/common/common.rs
src/common/common.rs
use std::ptr; use common::common_error::CommonError; pub fn slice_to_u16(slice: &[u8]) -> Result<u16, CommonError> { if slice.len() < 2 { return Err(CommonError::ConvertErr); } let value = (slice[1] as u16) << 8; Ok(value | slice[0] as u16) } pub fn slice_to_u32(slice: &[u8]) -> Result<u32, CommonError> { if slice.len() < 4 { return Err(CommonError::ConvertErr); } let mut value = (slice[3] as u32) << 24; value |= (slice[2] as u32) << 16; value |= (slice[1] as u32) << 8; Ok(value | slice[0] as u32) } pub fn u16_to_vec_u8(value: u16) -> Vec<u8> { let mut ret: Vec<u8> = vec![0,0]; ret[0] |= (value & 0xFF) as u8; ret[1] |= ((value & (0xFF << 8)) >> 8) as u8; ret } pub fn u32_to_vec_u8(value: u32) -> Vec<u8> { let mut ret: Vec<u8> = vec![0,0,0,0]; ret[0] |= (value & 0xFF) as u8; ret[1] |= ((value & (0xFF << 8)) >> 8) as u8; ret[2] |= ((value & (0xFF << 16)) >> 16) as u8; ret[3] |= ((value & (0xFF << 24)) >> 24) as u8; ret } pub unsafe fn write_array_volatile(dst: *mut u8, val: u8, count: usize) { for i in 0..count { ptr::write_volatile(dst.offset(i as isize), val); } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/common/common_error.rs
src/common/common_error.rs
use std::fmt; use std::error; pub use self::CommonError::*; #[doc = " Use this for catching various errors that can happen when using V1Kpdb. "] #[derive(Debug, Clone, PartialEq, Eq, Copy)] pub enum CommonError { /// Some error in parsing ConvertErr, } impl fmt::Display for CommonError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(error::Error::description(self)) } } impl error::Error for CommonError { fn description(&self) -> &str { match *self { ConvertErr => "Some error while converting datatypes", } } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
raymontag/rust-keepass
https://github.com/raymontag/rust-keepass/blob/8c8cde446c833f57eebfdb50dc3dbaad21f4affa/src/sec_str/mod.rs
src/sec_str/mod.rs
use libc::{c_void, mlock, munlock, size_t}; use openssl::symm; use rand; use common::common::write_array_volatile; #[doc = " SecureString implements a secure string. This means in particular: * The input string moves to the struct, i.e. it's not just borrowed * The string is encrypted with a random password for obfuscation * mlock() is called on the string to prevent swapping * A method to overwrite the string with zeroes is implemented * The overwrite method is called on drop of the struct automatically * Implements fmt::Show to prevent logging of the secrets, i.e. you can access the plaintext string only via the string value. "] pub struct SecureString { /// Holds the decrypted string if unlock() is called. /// Don't forget to call delete if you don't need the decrypted /// string anymore. /// Use String as type to move ownership to the struct. pub string: String, // Use of Vec instead of &[u8] because specific lifetimes aren't needed encrypted_string: Vec<u8>, password: Vec<u8>, iv: Vec<u8>, } impl SecureString { /// Create a new SecureString /// The input string should already lie on the heap, i.e. the type should /// be String and not &str, otherwise a copy of the plain text string would /// lie in memory. The string will be automatically encrypted and deleted. pub fn new(string: String) -> SecureString { // Lock the string against swapping unsafe { mlock(string.as_ptr() as *const c_void, string.len() as size_t); } let mut sec_str = SecureString { string: string, encrypted_string: vec![], password: (0..32).map(|_| rand::random::<u8>()).collect(), iv: (0..16).map(|_| rand::random::<u8>()).collect(), }; unsafe { mlock(sec_str.encrypted_string.as_ptr() as *const c_void, sec_str.encrypted_string.len() as size_t); } sec_str.lock(); sec_str.delete(); sec_str } /// Overwrite the string with zeroes. Call this everytime after unlock() if you don't /// need the string anymore. pub fn delete(&self) { // Use volatile to make sure that the operation is executed. unsafe { write_array_volatile(self.string.as_ptr() as *mut u8, 0u8, self.string.len()) }; } fn lock(&mut self) { self.encrypted_string = symm::encrypt(symm::Cipher::aes_256_cbc(), &self.password, Some(&self.iv), self.string.as_bytes()).expect("Can't encrypt string!?"); } /// Unlock the string, i.e. decrypt it and make it available via the string value. /// Don't forget to call delete() if you don't need the plain text anymore. pub fn unlock(&mut self) { self.string = String::from_utf8(symm::decrypt(symm::Cipher::aes_256_cbc(), &self.password, Some(&self.iv), &self.encrypted_string).expect("Can't decrypt string!?")).unwrap(); } } // string value and encrypted_string value will be overwritten with zeroes after drop of struct impl Drop for SecureString { fn drop(&mut self) { self.delete(); unsafe { munlock(self.string.as_ptr() as *const c_void, self.string.len() as size_t); write_array_volatile(self.encrypted_string.as_ptr() as *mut u8, 0u8, self.encrypted_string.len()); munlock(self.encrypted_string.as_ptr() as *const c_void, self.encrypted_string.len() as size_t); } } } #[cfg(test)] mod tests { use super::SecureString; use std::str; use std::ptr::copy; #[test] fn test_drop() { let mut test_vec: Vec<u8> = Vec::with_capacity(4); let mut test_vec2: Vec<u8> = Vec::with_capacity(4); unsafe { test_vec.set_len(4); test_vec2.set_len(4); let str = "drop".to_string(); let mut sec_str = SecureString::new(str); let enc_str_ptr = sec_str.encrypted_string.as_mut_ptr(); let str_ptr = sec_str.string.as_mut_vec().as_mut_ptr(); drop(sec_str); copy(enc_str_ptr, test_vec.as_mut_ptr(), 4); copy(str_ptr, test_vec2.as_mut_ptr(), 4); } assert_eq!(test_vec, vec![0u8, 0u8, 0u8, 0u8]); assert_eq!(test_vec2, vec![0u8, 0u8, 0u8, 0u8]); } #[test] fn test_new() { let str = "Hello, box!".to_string(); // Ownership of str moves to SecureString <- secure input interface let mut sec_str = SecureString::new(str); sec_str.unlock(); assert_eq!(sec_str.string, "Hello, box!"); } #[test] fn test_delete() { let str = "delete".to_string(); let sec_str = SecureString::new(str); assert_eq!(sec_str.string, "\0\0\0\0\0\0"); // Test with umlauts let str = "ä".to_string(); let sec_str = SecureString::new(str); assert_eq!(sec_str.string, "\0\0"); } #[test] fn test_lock() { let str = "delete".to_string(); let mut sec_str = SecureString::new(str); assert!(str::from_utf8(&sec_str.encrypted_string) != Ok("delete")); sec_str.unlock(); assert_eq!(sec_str.string, "delete"); } #[test] fn test_encryption() { let str = "delete".to_string(); let sec_str = SecureString::new(str); let str = "delete".to_string(); let mut sec_str2 = SecureString::new(str); assert!(sec_str.encrypted_string != sec_str2.encrypted_string); sec_str2.unlock(); sec_str2.iv = sec_str.iv.clone(); sec_str2.password = sec_str.password.clone(); sec_str2.lock(); assert_eq!(sec_str.encrypted_string, sec_str2.encrypted_string); } }
rust
ISC
8c8cde446c833f57eebfdb50dc3dbaad21f4affa
2026-01-04T20:18:55.975833Z
false
sotanakamura/winui-rust
https://github.com/sotanakamura/winui-rust/blob/fa2f3320ed110b65833344a24c32b200b398d62f/build.rs
build.rs
fn main() { ::windows_app::bootstrap::deploy::to_output_dir(); // Temporary workaround for https://github.com/microsoft/WindowsAppSDK/issues/2634 ::windows_app::build::embed_manifest( r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" />"#, ); }
rust
MIT
fa2f3320ed110b65833344a24c32b200b398d62f
2026-01-04T20:18:54.660398Z
false
sotanakamura/winui-rust
https://github.com/sotanakamura/winui-rust/blob/fa2f3320ed110b65833344a24c32b200b398d62f/src/main.rs
src/main.rs
use std::cell::RefCell; use std::ops::ControlFlow; use windows::UI::Xaml::GridLengthHelper; use windows::core::IInspectable; use windows::core::implement; use windows::Foundation::Collections::IVector; use windows::UI::Xaml::Interop::TypeName; use windows_app::Microsoft::UI::Xaml::ThicknessHelper; use windows_app::bootstrap; use windows_app::Microsoft::UI::Xaml::Application; use windows_app::Microsoft::UI::Xaml::IApplicationOverrides; use windows_app::Microsoft::UI::Xaml::IApplicationOverrides_Impl; use windows_app::Microsoft::UI::Xaml::ApplicationInitializationCallback; use windows_app::Microsoft::UI::Xaml::Markup::IXamlMetadataProvider_Impl; use windows_app::Microsoft::UI::Xaml::Window; use windows_app::Microsoft::UI::Xaml::ResourceDictionary; use windows_app::Microsoft::UI::Xaml::LaunchActivatedEventArgs; use windows_app::Microsoft::UI::Xaml::Controls::XamlControlsResources; use windows_app::Microsoft::UI::Xaml::Controls::ColorPicker; use windows_app::Microsoft::UI::Xaml::Controls::RatingControl; use windows_app::Microsoft::UI::Xaml::Controls::ToggleSplitButton; use windows_app::Microsoft::UI::Xaml::Markup::XmlnsDefinition; use windows_app::Microsoft::UI::Xaml::Markup::IXamlMetadataProvider; use windows_app::Microsoft::UI::Xaml::XamlTypeInfo::XamlControlsXamlMetaDataProvider; use windows_app::Microsoft::UI::Xaml::Controls; use windows_app::Microsoft::UI::Xaml::Controls::Primitives; #[implement(IApplicationOverrides,IXamlMetadataProvider)] struct App { window: RefCell<Option<Window>>, provider: XamlControlsXamlMetaDataProvider } #[allow(non_snake_case)] impl App { fn new() -> windows::core::Result<App> { let app = App { window: RefCell::new(None), provider: XamlControlsXamlMetaDataProvider::new()? }; Ok(app) } } impl IApplicationOverrides_Impl for App { fn OnLaunched(&self, _: &Option<LaunchActivatedEventArgs>) -> windows::core::Result<()> { Application::Current()?.Resources()?.MergedDictionaries()?.Append(XamlControlsResources::new()?); let window = Window::new()?; let grid = Controls::Grid::new()?; let col1 = Controls::ColumnDefinition::new()?; col1.SetMaxWidth(200f64); let col2 = Controls::ColumnDefinition::new()?; grid.ColumnDefinitions()?.Append(col1); grid.ColumnDefinitions()?.Append(col2); let stackpanel = Controls::StackPanel::new()?; stackpanel.SetValue(Controls::Grid::ColumnProperty()?,IInspectable::try_from(0)?); let button = Controls::Button::new()?; button.SetContent(IInspectable::try_from("Button")?); button.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(button); let dropdownbutton = Controls::DropDownButton::new()?; dropdownbutton.SetContent(IInspectable::try_from("DropDownButton")?); dropdownbutton.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(dropdownbutton); let togglebutton = Controls::Primitives::ToggleButton::new()?; togglebutton.SetContent(IInspectable::try_from("ToggleButton")?); togglebutton.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(togglebutton); let splitbutton = Controls::SplitButton::new()?; splitbutton.SetContent(IInspectable::try_from("SplitButton")?); splitbutton.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(splitbutton); let togglesplitbutton = Controls::ToggleSplitButton::new()?; togglesplitbutton.SetContent(IInspectable::try_from("ToggleSplitButton")?); togglesplitbutton.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(togglesplitbutton); let combobox = Controls::ComboBox::new()?; combobox.Items()?.Append(IInspectable::try_from("ComboBox")?); combobox.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(combobox); let radiobutton = Controls::RadioButton::new()?; radiobutton.SetContent(IInspectable::try_from("RadioButton")?); radiobutton.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(radiobutton); let ratingcontrol = Controls::RatingControl::new()?; ratingcontrol.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(ratingcontrol); let slider = Controls::Slider::new()?; slider.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(slider); let toggleswitch = Controls::ToggleSwitch::new()?; toggleswitch.SetMargin(ThicknessHelper::FromUniformLength(10f64)?); stackpanel.Children()?.Append(toggleswitch); let colorpicker = Controls::ColorPicker::new()?; colorpicker.SetValue(Controls::Grid::ColumnProperty()?,IInspectable::try_from(1)?); //Controls::Grid::SetColumn(colorpicker, 1); grid.Children()?.Append(stackpanel); grid.Children()?.Append(colorpicker); window.SetContent(grid); let result = window.Activate(); *self.window.borrow_mut() = Some(window); result } } impl IXamlMetadataProvider_Impl for App{ fn GetXamlType(&self,r#type: &TypeName,) -> windows::core::Result<windows_app::Microsoft::UI::Xaml::Markup::IXamlType> { self.provider.GetXamlType(r#type) } fn GetXamlTypeByFullName(&self,fullname: &windows::core::HSTRING,) -> windows::core::Result<windows_app::Microsoft::UI::Xaml::Markup::IXamlType> { self.provider.GetXamlTypeByFullName(fullname) } fn GetXmlnsDefinitions(&self,) -> windows::core::Result<windows::core::Array<XmlnsDefinition>> { self.provider.GetXmlnsDefinitions() } } fn main() -> windows::core::Result<()> { bootstrap::initialize()?; Application::Start(ApplicationInitializationCallback::new(|_| { let _ = Application::compose(App::new()?)?; Ok(()) }))?; bootstrap::uninitialize() }
rust
MIT
fa2f3320ed110b65833344a24c32b200b398d62f
2026-01-04T20:18:54.660398Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm.rs
src/vm.rs
use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::convert::TryInto; use std::io::BufRead; use std::io::BufReader; use std::ops::Index; use std::ops::IndexMut; use std::path::Path; use std::rc::Rc; use std::str; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::SystemTime; use indexmap::IndexMap; use lazy_static::lazy_static; use regex::{Regex, RegexBuilder}; use resolv_conf::ScopedIp; use sysinfo::{System, Users}; use crate::chunk::{print_error, new_string_value, Chunk, GeneratorObject, StringTriple, Value, ValueLiteral, Variable}; use crate::compiler::Compiler; use crate::hasher::new_hash_indexmap; use crate::opcode::{to_opcode, OpCode}; use crate::rl::RLHelper; mod vm_arithmetic; mod vm_basics; mod vm_command; mod vm_datetime; mod vm_db; mod vm_digest; mod vm_dns; mod vm_env; mod vm_hash; mod vm_http; mod vm_io; mod vm_ip; mod vm_json; mod vm_list; mod vm_net; mod vm_parallel; mod vm_print; mod vm_regex; mod vm_sort; mod vm_string; mod vm_system; mod vm_xml; mod vm_yaml; /// For dealing with the EndList opcode, which also supports ending a /// hash. pub enum ListType { List, Hash, Set, } /// For running compiled bytecode. pub struct VM { /// Whether to print debug information to standard error while /// running. debug: bool, /// The stack. pub stack: Vec<Value>, /// The last stack, i.e. the (possibly partially) reified state of /// the stack as at the conclusion of the last call. last_stack: Vec<Value>, /// The current chunk. chunk: Rc<RefCell<Chunk>>, /// The instruction index for the current chunk. i: usize, /// Whether the stack should be printed after interpretation has /// finished. print_stack: bool, /// Whether the stack is currently being printed. printing_stack: bool, /// The local variable stack. local_var_stack: Rc<RefCell<Vec<Value>>>, /// The scopes. scopes: Vec<Rc<RefCell<HashMap<String, Variable>>>>, /// The global functions. global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>, /// The call stack chunks. pub call_stack_chunks: Vec<(Rc<RefCell<Chunk>>, usize)>, /// A flag for interrupting execution. pub running: Arc<AtomicBool>, /// A lookup for regexes, to save regenerating them. pub regexes: HashMap<String, (Rc<Regex>, bool)>, /// The readline object, for fetching history. pub readline: Option<Rc<RefCell<rustyline::Editor<RLHelper>>>>, /// A System object, for getting process information. sys: Option<System>, /// A Users object, for getting user information. users: Option<Users>, /// The local time zone. local_tz: chrono_tz::Tz, /// The UTC timezone. utc_tz: chrono_tz::Tz, /// The library directory. libdir: &'static str, /// Child process details. child_processes: IndexMap<u32, String>, /// The modification time of the nameserver file. dns_mtime: SystemTime, /// Local nameserver addresses. dns_servers: Vec<ScopedIp> } lazy_static! { /// A map from form name to the internal function supporting that /// name. pub static ref SIMPLE_FORMS: HashMap<&'static str, fn(&mut VM) -> i32> = { let mut map = HashMap::new(); map.insert("+", VM::opcode_add as fn(&mut VM) -> i32); map.insert("-", VM::opcode_subtract as fn(&mut VM) -> i32); map.insert("*", VM::opcode_multiply as fn(&mut VM) -> i32); map.insert("<<", VM::core_lsft as fn(&mut VM) -> i32); map.insert(">>", VM::core_rsft as fn(&mut VM) -> i32); map.insert("^", VM::core_xor as fn(&mut VM) -> i32); map.insert("||", VM::core_or as fn(&mut VM) -> i32); map.insert("&", VM::core_and as fn(&mut VM) -> i32); map.insert("/", VM::opcode_divide as fn(&mut VM) -> i32); map.insert("%", VM::opcode_remainder as fn(&mut VM) -> i32); map.insert("<=>", VM::opcode_cmp as fn(&mut VM) -> i32); map.insert("=", VM::opcode_eq as fn(&mut VM) -> i32); map.insert(">", VM::opcode_gt as fn(&mut VM) -> i32); map.insert("<", VM::opcode_lt as fn(&mut VM) -> i32); map.insert("print", VM::opcode_print as fn(&mut VM) -> i32); map.insert("drop", VM::opcode_drop as fn(&mut VM) -> i32); map.insert("clear", VM::opcode_clear as fn(&mut VM) -> i32); map.insert("dup", VM::opcode_dup as fn(&mut VM) -> i32); map.insert("over", VM::opcode_over as fn(&mut VM) -> i32); map.insert("swap", VM::opcode_swap as fn(&mut VM) -> i32); map.insert("rot", VM::opcode_rot as fn(&mut VM) -> i32); map.insert("depth", VM::opcode_depth as fn(&mut VM) -> i32); map.insert("is-null", VM::opcode_isnull as fn(&mut VM) -> i32); map.insert("is-list", VM::opcode_islist as fn(&mut VM) -> i32); map.insert("is-callable", VM::opcode_iscallable as fn(&mut VM) -> i32); map.insert("is-shiftable", VM::opcode_isshiftable as fn(&mut VM) -> i32); map.insert("open", VM::opcode_open as fn(&mut VM) -> i32); map.insert("tempfile", VM::opcode_tempfile as fn(&mut VM) -> i32); map.insert("tempdir", VM::opcode_tempdir as fn(&mut VM) -> i32); map.insert("readline", VM::opcode_readline as fn(&mut VM) -> i32); map.insert("read", VM::opcode_read as fn(&mut VM) -> i32); map.insert("println", VM::core_println as fn(&mut VM) -> i32); map.insert("rm", VM::core_rm as fn(&mut VM) -> i32); map.insert("rmf", VM::core_rmf as fn(&mut VM) -> i32); map.insert("rmrf", VM::core_rmrf as fn(&mut VM) -> i32); map.insert("writeline", VM::core_writeline as fn(&mut VM) -> i32); map.insert("write", VM::core_write as fn(&mut VM) -> i32); map.insert("close", VM::core_close as fn(&mut VM) -> i32); map.insert("opendir", VM::core_opendir as fn(&mut VM) -> i32); map.insert("readdir", VM::core_readdir as fn(&mut VM) -> i32); map.insert("cp", VM::core_cp as fn(&mut VM) -> i32); map.insert("mv", VM::core_mv as fn(&mut VM) -> i32); map.insert("rename", VM::core_rename as fn(&mut VM) -> i32); map.insert("cd", VM::core_cd as fn(&mut VM) -> i32); map.insert("cwd", VM::core_cwd as fn(&mut VM) -> i32); map.insert("touch", VM::core_touch as fn(&mut VM) -> i32); map.insert("stat", VM::core_stat as fn(&mut VM) -> i32); map.insert("lstat", VM::core_lstat as fn(&mut VM) -> i32); map.insert("ps", VM::core_ps as fn(&mut VM) -> i32); map.insert("pss", VM::core_pss as fn(&mut VM) -> i32); map.insert("kill", VM::core_kill as fn(&mut VM) -> i32); map.insert("m", VM::core_m as fn(&mut VM) -> i32); map.insert("s", VM::core_s as fn(&mut VM) -> i32); map.insert("c", VM::core_c as fn(&mut VM) -> i32); map.insert("++", VM::core_append as fn(&mut VM) -> i32); map.insert("push", VM::opcode_push as fn(&mut VM) -> i32); map.insert("unshift", VM::core_unshift as fn(&mut VM) -> i32); map.insert("pop", VM::opcode_pop as fn(&mut VM) -> i32); map.insert("len", VM::core_len as fn(&mut VM) -> i32); map.insert("empty", VM::core_empty as fn(&mut VM) -> i32); map.insert("is-dir", VM::core_is_dir as fn(&mut VM) -> i32); map.insert("is-file", VM::core_is_file as fn(&mut VM) -> i32); map.insert("is-link", VM::core_is_link as fn(&mut VM) -> i32); map.insert("is-r", VM::core_is_r as fn(&mut VM) -> i32); map.insert("is-w", VM::core_is_w as fn(&mut VM) -> i32); map.insert("is-x", VM::core_is_x as fn(&mut VM) -> i32); map.insert("split", VM::core_split as fn(&mut VM) -> i32); map.insert("splitr", VM::core_splitr as fn(&mut VM) -> i32); map.insert("get", VM::core_get as fn(&mut VM) -> i32); map.insert("set", VM::core_set as fn(&mut VM) -> i32); map.insert("keys", VM::core_keys as fn(&mut VM) -> i32); map.insert("values", VM::core_values as fn(&mut VM) -> i32); map.insert("each", VM::core_each as fn(&mut VM) -> i32); map.insert("from-json", VM::core_from_json as fn(&mut VM) -> i32); map.insert("to-json", VM::core_to_json as fn(&mut VM) -> i32); map.insert("from-xml", VM::core_from_xml as fn(&mut VM) -> i32); map.insert("to-xml", VM::core_to_xml as fn(&mut VM) -> i32); map.insert("from-yaml", VM::core_from_yaml as fn(&mut VM) -> i32); map.insert("to-yaml", VM::core_to_yaml as fn(&mut VM) -> i32); map.insert("bool", VM::opcode_bool as fn(&mut VM) -> i32); map.insert("byte", VM::opcode_byte as fn(&mut VM) -> i32); map.insert("str", VM::opcode_str as fn(&mut VM) -> i32); map.insert("int", VM::opcode_int as fn(&mut VM) -> i32); map.insert("float", VM::opcode_flt as fn(&mut VM) -> i32); map.insert("rand", VM::opcode_rand as fn(&mut VM) -> i32); map.insert("shift", VM::opcode_shift as fn(&mut VM) -> i32); map.insert("join", VM::core_join as fn(&mut VM) -> i32); map.insert("|", VM::core_pipe as fn(&mut VM) -> i32); map.insert("clone", VM::opcode_clone as fn(&mut VM) -> i32); map.insert("now", VM::core_now as fn(&mut VM) -> i32); map.insert("date", VM::core_date as fn(&mut VM) -> i32); map.insert("strftime", VM::core_strftime as fn(&mut VM) -> i32); map.insert("to-epoch", VM::core_to_epoch as fn(&mut VM) -> i32); map.insert("from-epoch", VM::core_from_epoch as fn(&mut VM) -> i32); map.insert("set-tz", VM::core_set_tz as fn(&mut VM) -> i32); map.insert("+time", VM::core_addtime as fn(&mut VM) -> i32); map.insert("-time", VM::core_subtime as fn(&mut VM) -> i32); map.insert("strptime", VM::core_strptime as fn(&mut VM) -> i32); map.insert("strptimez", VM::core_strptimez as fn(&mut VM) -> i32); map.insert("ip", VM::core_ip as fn(&mut VM) -> i32); map.insert("ip.from-int", VM::core_ip_from_int as fn(&mut VM) -> i32); map.insert("ip.addr", VM::core_ip_addr as fn(&mut VM) -> i32); map.insert("ip.len", VM::core_ip_len as fn(&mut VM) -> i32); map.insert("ip.addr-int", VM::core_ip_addr_int as fn(&mut VM) -> i32); map.insert("ip.last-addr", VM::core_ip_last_addr as fn(&mut VM) -> i32); map.insert( "ip.last-addr-int", VM::core_ip_last_addr_int as fn(&mut VM) -> i32, ); map.insert("ip.size", VM::core_ip_size as fn(&mut VM) -> i32); map.insert("ip.version", VM::core_ip_version as fn(&mut VM) -> i32); map.insert("ip.prefixes", VM::core_ip_prefixes as fn(&mut VM) -> i32); map.insert("ips", VM::core_ips as fn(&mut VM) -> i32); map.insert("union", VM::core_union as fn(&mut VM) -> i32); map.insert("isect", VM::core_isect as fn(&mut VM) -> i32); map.insert("diff", VM::core_diff as fn(&mut VM) -> i32); map.insert("symdiff", VM::core_symdiff as fn(&mut VM) -> i32); map.insert("is-bool", VM::opcode_is_bool as fn(&mut VM) -> i32); map.insert("is-int", VM::opcode_is_int as fn(&mut VM) -> i32); map.insert("is-bigint", VM::opcode_is_bigint as fn(&mut VM) -> i32); map.insert("is-str", VM::opcode_is_str as fn(&mut VM) -> i32); map.insert("is-float", VM::opcode_is_flt as fn(&mut VM) -> i32); map.insert("is-set", VM::opcode_is_set as fn(&mut VM) -> i32); map.insert("is-hash", VM::opcode_is_hash as fn(&mut VM) -> i32); map.insert("bigint", VM::opcode_bigint as fn(&mut VM) -> i32); map.insert("chr", VM::core_chr as fn(&mut VM) -> i32); map.insert("ord", VM::core_ord as fn(&mut VM) -> i32); map.insert("hex", VM::core_hex as fn(&mut VM) -> i32); map.insert("unhex", VM::core_unhex as fn(&mut VM) -> i32); map.insert("oct", VM::core_oct as fn(&mut VM) -> i32); map.insert("unoct", VM::core_unoct as fn(&mut VM) -> i32); map.insert("lc", VM::core_lc as fn(&mut VM) -> i32); map.insert("lcfirst", VM::core_lcfirst as fn(&mut VM) -> i32); map.insert("uc", VM::core_uc as fn(&mut VM) -> i32); map.insert("ucfirst", VM::core_ucfirst as fn(&mut VM) -> i32); map.insert("reverse", VM::core_reverse as fn(&mut VM) -> i32); map.insert("sqrt", VM::core_sqrt as fn(&mut VM) -> i32); map.insert("**", VM::core_exp as fn(&mut VM) -> i32); map.insert("abs", VM::core_abs as fn(&mut VM) -> i32); map.insert("delete", VM::core_delete as fn(&mut VM) -> i32); map.insert("exists", VM::core_exists as fn(&mut VM) -> i32); map.insert("chmod", VM::core_chmod as fn(&mut VM) -> i32); map.insert("chown", VM::core_chown as fn(&mut VM) -> i32); map.insert("mkdir", VM::core_mkdir as fn(&mut VM) -> i32); map.insert("rmdir", VM::core_rmdir as fn(&mut VM) -> i32); map.insert("link", VM::core_link as fn(&mut VM) -> i32); map.insert("sleep", VM::core_sleep as fn(&mut VM) -> i32); map.insert("env", VM::core_env as fn(&mut VM) -> i32); map.insert("getenv", VM::core_getenv as fn(&mut VM) -> i32); map.insert("setenv", VM::core_setenv as fn(&mut VM) -> i32); map.insert("md5", VM::core_md5 as fn(&mut VM) -> i32); map.insert("sha1", VM::core_sha1 as fn(&mut VM) -> i32); map.insert("sha256", VM::core_sha256 as fn(&mut VM) -> i32); map.insert("sha512", VM::core_sha512 as fn(&mut VM) -> i32); map.insert("sort", VM::core_sort as fn(&mut VM) -> i32); map.insert("sortp", VM::core_sortp as fn(&mut VM) -> i32); map.insert("fmt", VM::core_fmt as fn(&mut VM) -> i32); map.insert("fmtq", VM::core_fmtq as fn(&mut VM) -> i32); map.insert("exec", VM::core_exec as fn(&mut VM) -> i32); map.insert("cmd", VM::core_cmd as fn(&mut VM) -> i32); map.insert("cmd/e", VM::core_cmde as fn(&mut VM) -> i32); map.insert("cmd/o", VM::core_cmdo as fn(&mut VM) -> i32); map.insert("cmd/eo", VM::core_cmdeo as fn(&mut VM) -> i32); map.insert("cmd/oe", VM::core_cmdeo as fn(&mut VM) -> i32); map.insert("cmd/c", VM::core_cmdc as fn(&mut VM) -> i32); map.insert("history", VM::core_history as fn(&mut VM) -> i32); map.insert("last", VM::core_last as fn(&mut VM) -> i32); map.insert("r", VM::core_reify as fn(&mut VM) -> i32); map.insert("db.conn", VM::core_db_conn as fn(&mut VM) -> i32); map.insert("db.prep", VM::core_db_prep as fn(&mut VM) -> i32); map.insert("db.exec", VM::core_db_exec as fn(&mut VM) -> i32); map.insert("pmap", VM::core_pmap as fn(&mut VM) -> i32); map.insert("pmapn", VM::core_pmapn as fn(&mut VM) -> i32); map.insert("expand-tilde", VM::core_expand_tilde as fn(&mut VM) -> i32); map.insert("ifconfig", VM::core_ifconfig as fn(&mut VM) -> i32); map.insert("netstat", VM::core_netstat as fn(&mut VM) -> i32); map.insert("http.get", VM::core_http_get as fn(&mut VM) -> i32); map.insert("http", VM::core_http as fn(&mut VM) -> i32); map.insert("socket", VM::core_socket as fn(&mut VM) -> i32); map.insert("nc", VM::core_nc as fn(&mut VM) -> i32); map.insert("exit", VM::core_exit as fn(&mut VM) -> i32); map.insert(".ss", VM::core_printstacksingle as fn(&mut VM) -> i32); map.insert("jobs", VM::core_jobs as fn(&mut VM) -> i32); map.insert("status", VM::core_status as fn(&mut VM) -> i32); map.insert("source", VM::core_source as fn(&mut VM) -> i32); map.insert("dnsat", VM::core_dnsat as fn(&mut VM) -> i32); map.insert("dns", VM::core_dns as fn(&mut VM) -> i32); map.insert("readlink", VM::core_readlink as fn(&mut VM) -> i32); map }; /// A set containing the function names that are defined in /// lib/rt.ch (i.e. that are core functions, but are not /// implemented in the compiler proper). This is so that /// bin/cosh.rs can distinguish these function names from /// user-defined function names in its autocomplete logic. pub static ref LIB_FORMS: HashSet<&'static str> = { let mut set = HashSet::new(); set.insert("2over"); set.insert("lsh"); set.insert("2rot"); set.insert("lshr"); set.insert("<="); set.insert("lsr"); set.insert("product"); set.insert(">="); set.insert("map"); set.insert("range"); set.insert("all"); set.insert("map-generator"); set.insert("and"); set.insert("map-list"); set.insert("shuffle"); set.insert("any"); set.insert("max"); set.insert("chomp"); set.insert("grep"); set.insert("min"); set.insert("grep-generator"); set.insert("nip"); set.insert("f<"); set.insert("grep-list"); set.insert("no-upwards"); set.insert("sum"); set.insert("flatten"); set.insert("f>"); set.insert("none"); set.insert("take"); set.insert("first"); set.insert("not"); set.insert("take-all"); set.insert("foldl"); set.insert("is-list-or-set"); set.insert("notall"); set.insert("uniq"); set.insert("for"); set.insert("ls"); set.insert("or"); set.insert("after"); set.insert("before"); set.insert("pairwise"); set.insert("slide"); set.insert("id"); set.insert("funcall"); set }; /// A vector mapping from opcode to the function implementing that /// opcode. static ref SIMPLE_OPS: Vec<Option<fn(&mut VM) -> i32>> = { let mut vec = vec![None; 255]; vec[OpCode::Add as usize] = Some(VM::opcode_add as fn(&mut VM) -> i32); vec[OpCode::Subtract as usize] = Some(VM::opcode_subtract as fn(&mut VM) -> i32); vec[OpCode::Multiply as usize] = Some(VM::opcode_multiply as fn(&mut VM) -> i32); vec[OpCode::Divide as usize] = Some(VM::opcode_divide as fn(&mut VM) -> i32); vec[OpCode::Remainder as usize] = Some(VM::opcode_remainder as fn(&mut VM) -> i32); vec[OpCode::Cmp as usize] = Some(VM::opcode_cmp as fn(&mut VM) -> i32); vec[OpCode::Eq as usize] = Some(VM::opcode_eq as fn(&mut VM) -> i32); vec[OpCode::Gt as usize] = Some(VM::opcode_gt as fn(&mut VM) -> i32); vec[OpCode::Lt as usize] = Some(VM::opcode_lt as fn(&mut VM) -> i32); vec[OpCode::Print as usize] = Some(VM::opcode_print as fn(&mut VM) -> i32); vec[OpCode::Drop as usize] = Some(VM::opcode_drop as fn(&mut VM) -> i32); vec[OpCode::Clear as usize] = Some(VM::opcode_clear as fn(&mut VM) -> i32); vec[OpCode::Dup as usize] = Some(VM::opcode_dup as fn(&mut VM) -> i32); vec[OpCode::Over as usize] = Some(VM::opcode_over as fn(&mut VM) -> i32); vec[OpCode::Swap as usize] = Some(VM::opcode_swap as fn(&mut VM) -> i32); vec[OpCode::Rot as usize] = Some(VM::opcode_rot as fn(&mut VM) -> i32); vec[OpCode::Depth as usize] = Some(VM::opcode_depth as fn(&mut VM) -> i32); vec[OpCode::IsNull as usize] = Some(VM::opcode_isnull as fn(&mut VM) -> i32); vec[OpCode::DupIsNull as usize] = Some(VM::opcode_dupisnull as fn(&mut VM) -> i32); vec[OpCode::IsList as usize] = Some(VM::opcode_islist as fn(&mut VM) -> i32); vec[OpCode::IsCallable as usize] = Some(VM::opcode_iscallable as fn(&mut VM) -> i32); vec[OpCode::IsShiftable as usize] = Some(VM::opcode_isshiftable as fn(&mut VM) -> i32); vec[OpCode::Open as usize] = Some(VM::opcode_open as fn(&mut VM) -> i32); vec[OpCode::Readline as usize] = Some(VM::opcode_readline as fn(&mut VM) -> i32); vec[OpCode::Bool as usize] = Some(VM::opcode_bool as fn(&mut VM) -> i32); vec[OpCode::Str as usize] = Some(VM::opcode_str as fn(&mut VM) -> i32); vec[OpCode::Int as usize] = Some(VM::opcode_int as fn(&mut VM) -> i32); vec[OpCode::Flt as usize] = Some(VM::opcode_flt as fn(&mut VM) -> i32); vec[OpCode::Rand as usize] = Some(VM::opcode_rand as fn(&mut VM) -> i32); vec[OpCode::Push as usize] = Some(VM::opcode_push as fn(&mut VM) -> i32); vec[OpCode::Pop as usize] = Some(VM::opcode_pop as fn(&mut VM) -> i32); vec[OpCode::ToggleMode as usize] = Some(VM::opcode_togglemode as fn(&mut VM) -> i32); vec[OpCode::PrintStack as usize] = Some(VM::opcode_printstack as fn(&mut VM) -> i32); vec[OpCode::ToFunction as usize] = Some(VM::opcode_tofunction as fn(&mut VM) -> i32); vec[OpCode::Import as usize] = Some(VM::opcode_import as fn(&mut VM) -> i32); vec[OpCode::Clone as usize] = Some(VM::opcode_clone as fn(&mut VM) -> i32); vec[OpCode::IsBool as usize] = Some(VM::opcode_is_bool as fn(&mut VM) -> i32); vec[OpCode::IsInt as usize] = Some(VM::opcode_is_int as fn(&mut VM) -> i32); vec[OpCode::IsBigInt as usize] = Some(VM::opcode_is_bigint as fn(&mut VM) -> i32); vec[OpCode::IsStr as usize] = Some(VM::opcode_is_str as fn(&mut VM) -> i32); vec[OpCode::IsFlt as usize] = Some(VM::opcode_is_flt as fn(&mut VM) -> i32); vec[OpCode::BigInt as usize] = Some(VM::opcode_bigint as fn(&mut VM) -> i32); vec }; static ref RE_NOT_PARAMS: Regex = Regex::new("\\\\/[a-z]+$").unwrap(); static ref RE_CAPTURE_PARAMS: Regex = Regex::new("/([a-z]+)$").unwrap(); static ref RE_ESCAPED_SLASH: Regex = Regex::new("\\\\/").unwrap(); static ref RE_NEWLINE: Regex = Regex::new("\n").unwrap(); static ref RE_ERROR_PART: Regex = Regex::new(".*error:\\s*").unwrap(); static ref RE_HOME_DIR_TILDE: Regex = Regex::new("~").unwrap(); } impl VM { pub fn new( print_stack: bool, debug: bool, global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>, global_vars: Rc<RefCell<HashMap<String, Variable>>>, libdir: &'static str ) -> VM { let ltz = iana_time_zone::get_timezone().unwrap(); let contents = std::fs::read_to_string("/etc/resolv.conf").expect("Failed to open resolv.conf"); let config = resolv_conf::Config::parse(&contents).unwrap(); VM { debug, stack: Vec::new(), last_stack: Vec::new(), local_var_stack: Rc::new(RefCell::new(Vec::new())), print_stack, printing_stack: false, scopes: vec![global_vars], global_functions: global_functions, call_stack_chunks: Vec::new(), running: Arc::new(AtomicBool::new(true)), chunk: Rc::new(RefCell::new(Chunk::new_standard("unused".to_string()))), i: 0, sys: None, users: None, regexes: HashMap::new(), local_tz: chrono_tz::Tz::from_str(&ltz).unwrap(), utc_tz: chrono_tz::Tz::from_str("UTC").unwrap(), readline: None, libdir, child_processes: IndexMap::new(), dns_mtime: std::fs::metadata("/etc/resolv.conf").unwrap() .modified().unwrap(), dns_servers: config.nameservers } } /// Instantiate the VM's system object, if necessary. pub fn instantiate_sys(&mut self) { match self.sys { None => { self.sys = Some(System::new_all()); self.users = Some(Users::new()); } _ => {} } } /// Refresh the VM's DNS servers, if necessary. pub fn refresh_dns_servers_if_necessary(&mut self) { let current_mtime = std::fs::metadata("/etc/resolv.conf").unwrap() .modified().unwrap(); if current_mtime != self.dns_mtime { self.dns_mtime = current_mtime; let contents = std::fs::read_to_string("/etc/resolv.conf").expect("Failed to open resolv.conf"); let config = resolv_conf::Config::parse(&contents).unwrap(); self.dns_servers = config.nameservers; } } /// Takes a chunk, an instruction index, and an error message as its /// arguments. Prints the error message, including filename, line number /// and column number elements (if applicable). pub fn print_error(&self, error: &str) { let point = self.chunk.borrow().get_point(self.i); let name = &self.chunk.borrow().name; let error_start = if name == "(main)" { String::new() } else { format!("{}:", name) }; match point { Some((line, col)) => { eprintln!("{}{}:{}: {}", error_start, line, col, error); } _ => { eprintln!("{}{}", error_start, error); } } } /// Toggles whether the stack is printed and cleared on command /// execution when running interactively. pub fn opcode_togglemode(&mut self) -> i32 { self.print_stack = !self.print_stack; 1 } /// Prints the stack. pub fn opcode_printstack(&mut self) -> i32 { let res = self.print_stack(self.chunk.clone(), self.i, true); if res { 1 } else { 0 } } /// Prints a single element from the stack. pub fn core_printstacksingle(&mut self) -> i32 { if self.stack.is_empty() { self.print_error(".ss requires non-empty stack"); return 0; } if self.printing_stack { self.print_error("cannot call .s/.ss recursively"); return 0; } self.printing_stack = true; let mut window_width: i32 = 0; let mut window_height: i32 = 0; let dim_opt = term_size::dimensions(); if let Some((w, h)) = dim_opt { window_width = w.try_into().unwrap(); window_height = h.try_into().unwrap(); } let lines_to_print = window_height - 1; let mut last_stack = Vec::new(); let value_rr = self.stack.get(self.stack.len() - 1).unwrap().clone(); let chunk = self.chunk.clone(); let i = self.i; self.print_stack_value( &value_rr, chunk, i, 0, false, window_height, window_width, lines_to_print, None, &mut last_stack ); self.printing_stack = false; return 1; } /// Puts a job list on the stack. pub fn core_jobs(&mut self) -> i32 { self.instantiate_sys(); let sysopt = &mut self.sys; let sys = &mut sysopt.as_mut().unwrap(); let mut to_remove = Vec::new(); let mut lst = VecDeque::new(); for (pid_int, cmd) in &self.child_processes { let pid = sysinfo::Pid::from(*pid_int as usize); let mut res = sys.refresh_process(pid); if res { let pid = sysinfo::Pid::from(*pid_int as usize); let process = sys.process(pid).unwrap(); /* Zombie processes are currently reaped by Drop * implementations. */ if process.status() == sysinfo::ProcessStatus::Zombie { res = false; } } if !res { to_remove.push(*pid_int); } let mut map = new_hash_indexmap(); map.insert("pid".to_string(), Value::Int(*pid_int as i32)); map.insert("desc".to_string(), new_string_value(cmd.to_string())); map.insert("complete".to_string(), Value::Bool(!res)); lst.push_back(Value::Hash(Rc::new(RefCell::new(map)))); } for pid_int in to_remove { self.child_processes.shift_remove(&pid_int); } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); return 1; } /// Converts a callable (e.g. a string) into a function object. /// Calling funcall on the function object will be faster than /// calling it on the original string. pub fn opcode_tofunction(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("to-function requires one argument"); return 0; } let fn_rr = self.stack.pop().unwrap(); let backup_rr = fn_rr.clone(); let fn_opt: Option<&str>; to_str!(fn_rr, fn_opt); let mut pushed = false; if let Some(s) = fn_opt { let sv = self.string_to_callable(s); if let Some(v) = sv { self.stack.push(v); pushed = true; } } if !pushed { self.stack.push(backup_rr); } 1 } /// Expand a tilde that appears in the path. pub fn core_expand_tilde(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("expand-tilde requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let ss = Self::expand_tilde(s); let v = new_string_value(ss.to_string()); self.stack.push(v); return 1; } None => { self.print_error("expand-tilde argument must be a string"); return 0; } } } /// Return a generator over the shell history. If not being run /// in shell context, returns an error message. pub fn core_history(&mut self) -> i32 { let hist_gen = Value::HistoryGenerator(Rc::new(RefCell::new(0))); self.stack.push(hist_gen); return 1; } /// Push the elements from the last stack (i.e. the stack as at /// the conclusion of the last call) onto the stack. pub fn core_last(&mut self) -> i32 { self.stack.append(&mut self.last_stack); return 1; } fn find_library(libdir: &str, libname: &str) -> Option<String> { let s = format!("{}/{}", libdir, libname); if Path::new(&s).is_file() { return Some(s); } let s2 = format!("{}/{}.chc", libdir, libname); if Path::new(&s2).is_file() { return Some(s2); } let s3 = format!("{}/{}.ch", libdir, libname); if Path::new(&s3).is_file() { return Some(s3); } return None; } /// Import the functions from the specified library into the /// current context. pub fn opcode_import(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("import requires one argument"); return 0; } let lib_rr = self.stack.pop().unwrap(); let lib_str_opt: Option<&str>; to_str!(lib_rr, lib_str_opt); match lib_str_opt { Some(s) => { let mut path_opt = VM::find_library(".", s); if path_opt.is_none() { let libdir = format!("{}/{}", self.libdir, "cosh"); path_opt = VM::find_library(&libdir, s); } if path_opt.is_none() { self.print_error("unable to open import path"); return 0; } let path = path_opt.unwrap(); let mut compiler = Compiler::new(); let import_chunk_opt = compiler.deserialise(&path); match import_chunk_opt { Some(import_chunk) => { for (k, v) in import_chunk.functions.iter() { if !k.starts_with("anon") { self.global_functions.borrow_mut().insert(k.clone(), v.clone()); } } /* The main reason for running the chunk is so * that global variables are introduced. */ self.run(Rc::new(RefCell::new(import_chunk))); self.stack.clear(); } None => { let file_res = std::fs::File::open(path.clone()); match file_res { Ok(file) => {
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/lib.rs
src/lib.rs
#![allow( clippy::needless_late_init, clippy::comparison_chain, clippy::question_mark, clippy::type_complexity )] extern crate ahash; extern crate ansi_term; extern crate atty; extern crate chrono; extern crate chrono_tz; extern crate chronoutil; extern crate dirs; #[cfg(feature = "fxhash")] extern crate fxhash; extern crate iana_time_zone; extern crate indexmap; extern crate ipnet; extern crate ipnetwork; extern crate iprange; extern crate lazy_static; extern crate memchr; extern crate md5; extern crate netstat2; extern crate nix; extern crate nonblock; extern crate num; extern crate num_bigint; extern crate num_traits; extern crate pnet; extern crate rand; extern crate regex; extern crate roxmltree; extern crate rust_decimal; extern crate rustyline; extern crate rustyline_derive; extern crate searchpath; extern crate serde; extern crate sha1; extern crate sha2; extern crate sqlx; extern crate sysinfo; extern crate tempfile; extern crate term_size; extern crate termion; extern crate unicode_segmentation; extern crate utime; extern crate xml; #[macro_use] pub mod chunk; pub mod compiler; pub mod hasher; mod opcode; pub mod rl; pub mod vm;
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/opcode.rs
src/opcode.rs
/// The opcodes used in the compiler and the bytecode. #[derive(Debug, Clone, Copy)] pub enum OpCode { Constant = 1, Add = 2, Subtract = 3, Multiply = 4, Divide = 5, EndFn = 6, Call = 7, CallImplicit = 8, GLVCall = 9, Function = 10, Var = 11, SetVar = 12, GetVar = 13, SetLocalVar = 14, GetLocalVar = 15, PopLocalVar = 16, Jump = 17, JumpNe = 18, JumpR = 19, JumpNeR = 20, JumpNeREqC = 21, Clone = 22, Yield = 23, Error = 24, Return = 25, Import = 26, Eq = 27, Gt = 28, Lt = 29, Cmp = 30, Print = 31, Dup = 32, Swap = 33, Drop = 34, Rot = 35, Over = 36, Depth = 37, Clear = 38, DupIsNull = 39, StartList = 40, EndList = 41, StartHash = 42, StartSet = 43, AddConstant = 44, EqConstant = 45, CallConstant = 46, SubtractConstant = 47, MultiplyConstant = 48, DivideConstant = 49, CallImplicitConstant = 50, Shift = 51, GLVShift = 52, Push = 53, Pop = 54, Bool = 55, Int = 56, BigInt = 57, Str = 58, Flt = 59, IsNull = 60, IsBool = 61, IsInt = 62, IsBigInt = 63, IsStr = 64, IsFlt = 65, IsList = 66, IsCallable = 67, IsShiftable = 68, Open = 69, Readline = 70, Rand = 71, ToggleMode = 72, PrintStack = 73, ToFunction = 74, Byte = 75, IsByte = 76, Read = 77, Remainder = 78, VarM = 79, VarSet = 80, VarMSet = 81, Unknown = 255, } /// Convert a byte to an opcode value. pub fn to_opcode(value: u8) -> OpCode { match value { 1 => OpCode::Constant, 2 => OpCode::Add, 3 => OpCode::Subtract, 4 => OpCode::Multiply, 5 => OpCode::Divide, 6 => OpCode::EndFn, 7 => OpCode::Call, 8 => OpCode::CallImplicit, 9 => OpCode::GLVCall, 10 => OpCode::Function, 11 => OpCode::Var, 12 => OpCode::SetVar, 13 => OpCode::GetVar, 14 => OpCode::SetLocalVar, 15 => OpCode::GetLocalVar, 16 => OpCode::PopLocalVar, 17 => OpCode::Jump, 18 => OpCode::JumpNe, 19 => OpCode::JumpR, 20 => OpCode::JumpNeR, 21 => OpCode::JumpNeREqC, 22 => OpCode::Clone, 23 => OpCode::Yield, 24 => OpCode::Error, 25 => OpCode::Return, 26 => OpCode::Import, 27 => OpCode::Eq, 28 => OpCode::Gt, 29 => OpCode::Lt, 30 => OpCode::Cmp, 31 => OpCode::Print, 32 => OpCode::Dup, 33 => OpCode::Swap, 34 => OpCode::Drop, 35 => OpCode::Rot, 36 => OpCode::Over, 37 => OpCode::Depth, 38 => OpCode::Clear, 39 => OpCode::DupIsNull, 40 => OpCode::StartList, 41 => OpCode::EndList, 42 => OpCode::StartHash, 43 => OpCode::StartSet, 44 => OpCode::AddConstant, 45 => OpCode::EqConstant, 46 => OpCode::CallConstant, 47 => OpCode::SubtractConstant, 48 => OpCode::MultiplyConstant, 49 => OpCode::DivideConstant, 50 => OpCode::CallImplicitConstant, 51 => OpCode::Shift, 52 => OpCode::GLVShift, 53 => OpCode::Push, 54 => OpCode::Pop, 55 => OpCode::Bool, 56 => OpCode::Int, 57 => OpCode::BigInt, 58 => OpCode::Str, 59 => OpCode::Flt, 60 => OpCode::IsNull, 61 => OpCode::IsBool, 62 => OpCode::IsInt, 63 => OpCode::IsBigInt, 64 => OpCode::IsStr, 65 => OpCode::IsFlt, 66 => OpCode::IsList, 67 => OpCode::IsCallable, 68 => OpCode::IsShiftable, 69 => OpCode::Open, 70 => OpCode::Readline, 71 => OpCode::Rand, 72 => OpCode::ToggleMode, 73 => OpCode::PrintStack, 74 => OpCode::ToFunction, 75 => OpCode::Byte, 76 => OpCode::IsByte, 77 => OpCode::Read, 78 => OpCode::Remainder, 79 => OpCode::VarM, 80 => OpCode::VarSet, 81 => OpCode::VarMSet, 255 => OpCode::Unknown, _ => OpCode::Unknown, } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/hasher.rs
src/hasher.rs
use indexmap::IndexMap; use crate::chunk::Value; // Use compile-time features to select hasher // Default to AHash for performance, but allow override #[cfg(feature = "fxhash")] use fxhash::FxBuildHasher; #[cfg(feature = "fxhash")] pub type CoshIndexMap<K, V> = IndexMap<K, V, FxBuildHasher>; #[cfg(all(feature = "default-hasher", not(feature = "fxhash")))] pub type CoshIndexMap<K, V> = IndexMap<K, V>; #[cfg(all(not(feature = "default-hasher"), not(feature = "fxhash")))] use ahash::RandomState as AHashRandomState; #[cfg(all(not(feature = "default-hasher"), not(feature = "fxhash")))] pub type CoshIndexMap<K, V> = IndexMap<K, V, AHashRandomState>; /// Create a new IndexMap for hash values using the configured hasher. pub fn new_hash_indexmap() -> CoshIndexMap<String, Value> { #[cfg(feature = "fxhash")] { IndexMap::with_hasher(FxBuildHasher::default()) } #[cfg(all(feature = "default-hasher", not(feature = "fxhash")))] { IndexMap::new() } #[cfg(all(not(feature = "default-hasher"), not(feature = "fxhash")))] { IndexMap::with_hasher(AHashRandomState::new()) } } /// Create a new IndexMap for set values using the configured hasher. pub fn new_set_indexmap() -> CoshIndexMap<String, Value> { new_hash_indexmap() } /// Create a generic IndexMap with the configured hasher. pub fn new_indexmap<K, V>() -> CoshIndexMap<K, V> { #[cfg(feature = "fxhash")] { IndexMap::with_hasher(FxBuildHasher::default()) } #[cfg(all(feature = "default-hasher", not(feature = "fxhash")))] { IndexMap::new() } #[cfg(all(not(feature = "default-hasher"), not(feature = "fxhash")))] { IndexMap::with_hasher(AHashRandomState::new()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_hash_set_creation() { // Test that helper functions work let _hash_map = new_hash_indexmap(); let _set_map = new_set_indexmap(); } #[test] fn test_indexmap_functionality() { // Test that the created IndexMaps work correctly let mut map = new_hash_indexmap(); map.insert("test".to_string(), Value::Null); assert_eq!(map.len(), 1); assert!(map.contains_key("test")); } #[test] fn test_generic_indexmap() { let mut map: CoshIndexMap<String, i32> = new_indexmap(); map.insert("key".to_string(), 42); assert_eq!(map.get("key"), Some(&42)); } #[test] fn test_indexmap_ordering() { // Test that IndexMap maintains insertion order with custom hashers let mut map = new_hash_indexmap(); map.insert("first".to_string(), Value::Int(1)); map.insert("second".to_string(), Value::Int(2)); map.insert("third".to_string(), Value::Int(3)); let keys: Vec<_> = map.keys().collect(); assert_eq!(keys, vec!["first", "second", "third"]); } #[test] fn test_hash_vs_set_maps() { // Ensure both helper functions work and are compatible let mut hash_map = new_hash_indexmap(); let mut set_map = new_set_indexmap(); hash_map.insert("key1".to_string(), Value::Int(100)); set_map.insert("key2".to_string(), Value::Int(200)); assert_eq!(hash_map.len(), 1); assert_eq!(set_map.len(), 1); assert!(hash_map.contains_key("key1")); assert!(set_map.contains_key("key2")); } #[test] fn test_type_compatibility() { // Test that CoshIndexMap is compatible with Value enum let mut map = new_hash_indexmap(); // Test different Value types map.insert("null".to_string(), Value::Null); map.insert("bool".to_string(), Value::Bool(true)); map.insert("int".to_string(), Value::Int(42)); map.insert("float".to_string(), Value::Float(3.14)); assert_eq!(map.len(), 4); assert!(map.contains_key("bool")); assert!(map.contains_key("int")); assert!(map.contains_key("null")); assert!(map.contains_key("float")); } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/rl.rs
src/rl.rs
use std::borrow::Cow::{self, Borrowed}; use std::cell::RefCell; use std::collections::HashMap; use std::env::current_dir; use std::fs; use std::path::{self, Path}; use std::rc::Rc; use ansi_term::Colour::{Blue, Purple, Red}; use dirs::home_dir; use memchr::memchr; use rustyline::completion::{escape, unescape, Candidate, Completer, Pair, Quote}; use rustyline::highlight::Highlighter; use rustyline::hint::Hinter; use rustyline::validate::Validator; use rustyline::{Context, Result}; use rustyline_derive::Helper; use searchpath::search_path; use crate::chunk::{Chunk, Variable}; use crate::vm::{LIB_FORMS, SIMPLE_FORMS}; // Most of the code through to 'impl Completer for ShellCompleter' is // taken from kkawakam/rustyline#574 as at 3a41ee9, with some small // changes. Licence text from that repository: // // The MIT License (MIT) // // Copyright (c) 2015 Katsu Kawakami & Rustyline authors // // 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. const ESCAPE_CHAR: Option<char> = Some('\\'); const DOUBLE_QUOTES_ESCAPE_CHAR: Option<char> = Some('\\'); const DEFAULT_BREAK_CHARS: [u8; 19] = [ b' ', b'\t', b'\n', b'"', b'\\', b'\'', b'`', b'@', b'$', b'>', b'<', b'=', b';', b'|', b'&', b'{', b'(', b'\0', b'[' ]; const DOUBLE_QUOTES_SPECIAL_CHARS: [u8; 4] = [b'"', b'$', b'\\', b'`']; #[derive(PartialEq)] enum ScanMode { DoubleQuote, Escape, EscapeInDoubleQuote, Normal, SingleQuote, } fn normalize(s: &str) -> Cow<str> { Cow::Borrowed(s) } /// try to find an unclosed single/double quote in `s`. /// Return `None` if no unclosed quote is found. /// Return the unclosed quote position and if it is a double quote. fn find_unclosed_quote(s: &str) -> Option<(usize, Quote)> { let char_indices = s.char_indices(); let mut mode = ScanMode::Normal; let mut quote_index = 0; for (index, char) in char_indices { match mode { ScanMode::DoubleQuote => { if char == '"' { mode = ScanMode::Normal; } else if char == '\\' { mode = ScanMode::EscapeInDoubleQuote; } } ScanMode::Escape => { mode = ScanMode::Normal; } ScanMode::EscapeInDoubleQuote => { mode = ScanMode::DoubleQuote; } ScanMode::Normal => { if char == '"' { mode = ScanMode::DoubleQuote; quote_index = index; } else if char == '\\' { mode = ScanMode::Escape; } else if char == '\'' { mode = ScanMode::SingleQuote; quote_index = index; } } ScanMode::SingleQuote => { if char == '\'' { mode = ScanMode::Normal; } // no escape in single quotes } }; } if ScanMode::DoubleQuote == mode || ScanMode::EscapeInDoubleQuote == mode { return Some((quote_index, Quote::Double)); } else if ScanMode::SingleQuote == mode { return Some((quote_index, Quote::Single)); } None } /// Given a `line` and a cursor `pos`ition, /// try to find backward the start of a word. /// Return (0, `line[..pos]`) if no break char has been found. /// Return the word and its start position (idx, `line[idx..pos]`) otherwise. pub fn extract_word<'l>( line: &'l str, pos: usize, esc_char: Option<char>, break_chars: &[u8], ) -> (usize, &'l str) { let line = &line[..pos]; if line.is_empty() { return (0, line); } let mut start = None; for (i, c) in line.char_indices().rev() { if let (Some(esc_char), true) = (esc_char, start.is_some()) { if esc_char == c { // escaped break char start = None; continue; } else { break; } } if c.is_ascii() && memchr(c as u8, break_chars).is_some() { start = Some(i + c.len_utf8()); if esc_char.is_none() { break; } // else maybe escaped... } } match start { Some(start) => (start, &line[start..]), None => (0, line), } } fn filename_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, ) -> Vec<Pair> { let sep = path::MAIN_SEPARATOR; let (dir_name, file_name) = match path.rfind(sep) { Some(idx) => path.split_at(idx + sep.len_utf8()), None => ("", path), }; let dir_path = Path::new(dir_name); let dir = if dir_path.starts_with("~") { if let Some(home) = home_dir() { match dir_path.strip_prefix("~") { Ok(rel_path) => home.join(rel_path), _ => home, } } else { dir_path.to_path_buf() } } else if dir_path.is_relative() { if let Ok(cwd) = current_dir() { cwd.join(dir_path) } else { dir_path.to_path_buf() } } else { dir_path.to_path_buf() }; let mut entries: Vec<Pair> = Vec::new(); // if dir doesn't exist, then don't offer any completions if !dir.exists() { return entries; } // if any of the below IO operations have errors, just ignore them if let Ok(read_dir) = dir.read_dir() { let file_name = normalize(file_name); for entry in read_dir.flatten() { if let Some(s) = entry.file_name().to_str() { let ns = normalize(s); if ns.starts_with(file_name.as_ref()) { if let Ok(metadata) = fs::metadata(entry.path()) { let mut path = String::from(dir_name) + s; if metadata.is_dir() { path.push(sep); } entries.push(Pair { display: String::from(s), replacement: escape(path, esc_char, break_chars, quote), }); } // else ignore PermissionDenied } } } } entries } fn internal_complete( path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote, global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>, global_vars: Rc<RefCell<HashMap<String, Variable>>>, ) -> Vec<Pair> { let mut entries: Vec<Pair> = Vec::new(); for k in SIMPLE_FORMS.keys() { if k.starts_with(path) { entries.push(Pair { display: Red.paint(*k).to_string(), replacement: escape((*k).to_string(), esc_char, break_chars, quote), }); } } for k in LIB_FORMS.iter() { if k.starts_with(path) { entries.push(Pair { display: Red.paint(*k).to_string(), replacement: escape((*k).to_string(), esc_char, break_chars, quote), }); } } for k in global_functions.borrow().keys() { if k.starts_with(path) && !LIB_FORMS.contains::<str>(k) { entries.push(Pair { display: Blue.paint(k).to_string(), replacement: escape(k.to_string(), esc_char, break_chars, quote), }); } } for k in global_vars.borrow().keys() { if k.starts_with(path) { entries.push(Pair { display: Purple.paint(k).to_string(), replacement: escape(k.to_string(), esc_char, break_chars, quote), }); } } entries } fn bin_complete(path: &str, esc_char: Option<char>, break_chars: &[u8], quote: Quote) -> Vec<Pair> { let mut entries: Vec<Pair> = Vec::new(); for file in search_path(path, std::env::var_os("PATH").as_deref(), None) { entries.push(Pair { display: file.clone(), replacement: escape(file, esc_char, break_chars, quote), }); } entries } pub struct ShellCompleter { break_chars: &'static [u8], double_quotes_special_chars: &'static [u8], global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>, global_vars: Rc<RefCell<HashMap<String, Variable>>>, } fn should_complete_executable(path: &str, line: &str, start: usize) -> bool { // If the string prior to path comprises whitespace, then // executable completion should be used (unless the path is // qualified). let before = &line[0..start]; if !before.is_empty() && before.chars().all(char::is_whitespace) && !path.contains(char::is_whitespace) { return !(path.starts_with("./") || path.starts_with('/')); } // If the string prior to path includes a $ or { character, // followed by (optional) whitespace, and then the path, then // executable completion should be used (unless the path is // qualified). let mut index_opt = before.rfind('$'); if index_opt.is_none() { index_opt = before.rfind('{'); } if index_opt.is_none() { return false; } let index = index_opt.unwrap(); let before2_chars = &mut before[index + 1..start].chars(); let mut hit_char = false; loop { let c_opt = before2_chars.next(); if c_opt.is_none() { break; } let c = c_opt.unwrap(); if c.is_whitespace() { if hit_char { return false; } } else { hit_char = true; } } !(path.starts_with("./") || path.starts_with('/')) } impl ShellCompleter { /// Constructor pub fn new( global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>, global_vars: Rc<RefCell<HashMap<String, Variable>>>, ) -> Self { Self { break_chars: &DEFAULT_BREAK_CHARS, double_quotes_special_chars: &DOUBLE_QUOTES_SPECIAL_CHARS, global_functions, global_vars, } } /// Takes the currently edited `line` with the cursor `pos`ition and /// returns the start position and the completion candidates for the /// partial path to be completed. pub fn complete_path(&self, line: &str, pos: usize) -> Result<(usize, Vec<Pair>)> { let (start, path, _, esc_char, break_chars, quote) = if let Some((idx, quote)) = find_unclosed_quote(&line[..pos]) { let start = idx + 1; if quote == Quote::Double { ( start, unescape(&line[start..pos], DOUBLE_QUOTES_ESCAPE_CHAR), Borrowed(&line[..pos]), DOUBLE_QUOTES_ESCAPE_CHAR, &self.double_quotes_special_chars, quote, ) } else { ( start, Borrowed(&line[start..pos]), Borrowed(&line[..pos]), None, &self.break_chars, quote, ) } } else { let (start, path) = extract_word(line, pos, ESCAPE_CHAR, self.break_chars); ( start, unescape(path, ESCAPE_CHAR), Borrowed(path), ESCAPE_CHAR, &self.break_chars, Quote::None, ) }; let mut matches = if should_complete_executable(&path, line, start) { bin_complete(&path, esc_char, break_chars, quote) } else { filename_complete(&path, esc_char, break_chars, quote) }; let mut internal_matches = internal_complete( &path, esc_char, break_chars, quote, self.global_functions.clone(), self.global_vars.clone(), ); #[allow(clippy::unnecessary_sort_by)] matches.append(&mut internal_matches); matches.sort_by(|a, b| a.display().cmp(b.display())); Ok((start, matches)) } } impl Default for ShellCompleter { fn default() -> Self { Self::new( Rc::new(RefCell::new(HashMap::new())), Rc::new(RefCell::new(HashMap::new())), ) } } impl Completer for ShellCompleter { type Candidate = Pair; fn complete(&self, line: &str, pos: usize, _ctx: &Context<'_>) -> Result<(usize, Vec<Pair>)> { self.complete_path(line, pos) } } #[derive(Helper)] pub struct RLHelper { pub completer: ShellCompleter, } impl Completer for RLHelper { type Candidate = Pair; fn complete(&self, line: &str, pos: usize, ctx: &Context<'_>) -> Result<(usize, Vec<Pair>)> { self.completer.complete(line, pos, ctx) } } impl Hinter for RLHelper {} impl Highlighter for RLHelper {} impl Validator for RLHelper {}
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/chunk.rs
src/chunk.rs
use std::cell::RefCell; use std::collections::HashMap; use std::collections::HashSet; use std::collections::VecDeque; use std::convert::TryInto; use std::fmt; use std::fs::File; use std::fs::ReadDir; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::ErrorKind; use std::io::Read; use std::io::Write; use std::net::{Ipv4Addr, Ipv6Addr, TcpStream}; use std::rc::Rc; use std::str::FromStr; use std::thread; use std::time; use chrono::format::{parse, Parsed, StrftimeItems}; use chrono::prelude::*; use indexmap::IndexMap; use ipnet::{Ipv4Net, Ipv6Net}; use iprange::IpRange; use nix::{sys::signal::Signal, sys::wait::waitpid, sys::wait::WaitPidFlag, sys::wait::WaitStatus}; use nonblock::NonBlockingReader; use num::FromPrimitive; use num::ToPrimitive; use num_bigint::BigInt; use num_traits::{Zero, Num}; use regex::Regex; use serde::{Deserialize, Serialize}; use std::process::{ChildStderr, ChildStdout}; use sqlx::{MySql, Postgres, Sqlite}; use crate::hasher::{CoshIndexMap, new_hash_indexmap, new_set_indexmap}; use crate::opcode::{to_opcode, OpCode}; use crate::vm::*; /// A chunk is a parsed/processed piece of code. #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Chunk { /// The name of the chunk. Either the name of the file that /// contains the associated code, or "(main)", for code entered at /// the REPL. pub name: String, /// The bytecode for the chunk. pub data: Vec<u8>, /// Whether the byte at this position in data is an opcode. pub is_opcode: Vec<bool>, /// The line and column number information for the chunk. The /// entries in this vector correspond to the entries in the /// bytecode vector. pub points: Vec<(u32, u32)>, /// The set of constant values for the chunk. pub constants: Vec<ValueLiteral>, /// The functions defined within the chunk. pub functions: HashMap<String, Rc<RefCell<Chunk>>>, #[serde(skip)] /// Initialised values for the constants of the chunk. pub constant_values: Vec<Value>, /// Whether the chunk is for a generator function. pub is_generator: bool, /// Whether the chunk deals with global variables. pub has_vars: bool, /// The maximum argument count for a generator function /// (only set if is_generator is true). pub arg_count: i32, /// The required argument count for a generator function /// (only set if is_generator is true). pub req_arg_count: i32, /// Whether the chunk represents a nested function. pub nested: bool, /// The scope depth for the chunk. pub scope_depth: u32, } /// StringTriple is used for the core string type. It binds together /// a display string (i.e. a raw string), an escaped string (to save /// repeating that operation), and the corresponding regex (to save /// regenerating that regex). The bool flag indicates whether global /// matching should be used for the regex. The display string is the /// 'real' string, and includes e.g. literal newline characters, /// whereas the escaped string includes escapes for those characters. #[derive(Debug, Clone)] pub struct StringTriple { pub string: String, pub escaped_string: String, pub regex: Option<(Rc<Regex>, bool)>, } /// Takes a display string and returns an escaped string. fn escape_string(s: &str) -> String { let mut s2 = String::from(""); let mut next_escaped = false; for c in s.chars() { if next_escaped { match c { '\\' => { s2.push('\\'); } '"' => { s2.push('\\'); s2.push('\\'); s2.push(c); } _ => { s2.push('\\'); s2.push(c); } } next_escaped = false; } else { match c { '\\' => { next_escaped = true; } '\n' => { s2.push('\\'); s2.push('n'); } '\r' => { s2.push('\\'); s2.push('r'); } '\t' => { s2.push('\\'); s2.push('t'); } '"' => { s2.push('\\'); s2.push('"'); } _ => { s2.push(c); } } } } s2 } impl StringTriple { pub fn new(s: String, r: Option<(Rc<Regex>, bool)>) -> StringTriple { let e = escape_string(&s); StringTriple { string: s, escaped_string: e, regex: r, } } pub fn new_with_escaped(s: String, e: String, r: Option<(Rc<Regex>, bool)>) -> StringTriple { StringTriple { string: s, escaped_string: e, regex: r, } } } /// A generator object, containing a generator chunk along with all of /// its associated state. #[derive(Debug, Clone)] pub struct GeneratorObject { /// The local variable stack. pub local_vars_stack: Rc<RefCell<Vec<Value>>>, /// The current instruction index. pub index: usize, /// The chunk of the associated generator function. pub chunk: Rc<RefCell<Chunk>>, /// The chunks of the other functions in the call stack. pub call_stack_chunks: Vec<(Rc<RefCell<Chunk>>, usize)>, /// The values that need to be passed into the generator when /// it is first called. pub gen_args: Vec<Value>, } impl GeneratorObject { /// Construct a generator object. pub fn new( local_vars_stack: Rc<RefCell<Vec<Value>>>, index: usize, chunk: Rc<RefCell<Chunk>>, call_stack_chunks: Vec<(Rc<RefCell<Chunk>>, usize)>, gen_args: Vec<Value>, ) -> GeneratorObject { GeneratorObject { local_vars_stack, index, chunk, call_stack_chunks, gen_args, } } } /// A file BufReader paired with an additional buffer, for dealing /// with calls to read. #[derive(Debug)] pub struct BufReaderWithBuffer<T: Read> { pub reader: BufReader<T>, pub buffer: [u8; 1024], pub buffer_index: i32, pub buffer_limit: i32, } impl<T: Read> BufReaderWithBuffer<T> { pub fn new(reader: BufReader<T>) -> BufReaderWithBuffer<T> { BufReaderWithBuffer { reader, buffer: [0; 1024], buffer_index: -1, buffer_limit: -1, } } fn fill_buffer(&mut self) -> i32 { let n_res = self.reader.read(&mut self.buffer); match n_res { Ok(n) => { if n == 0 { return 0; } self.buffer_index = 0; self.buffer_limit = n as i32; return 1; } Err(_) => { return -1; } } } pub fn read(&mut self, mut n: usize) -> Option<Value> { let mut buflst = VecDeque::new(); while n > 0 { if self.buffer_index > -1 { while (self.buffer_index < self.buffer_limit) && (n > 0) { buflst.push_back( Value::Byte( self.buffer[self.buffer_index as usize] ) ); self.buffer_index += 1; n -= 1; } if self.buffer_index == self.buffer_limit { self.buffer_index = -1; self.buffer_limit = -1; } } else { let res = self.fill_buffer(); if res == 0 { break; } else if res == -1 { return None; } } } if buflst.len() == 0 { Some(Value::Null) } else { Some(Value::List(Rc::new(RefCell::new(buflst)))) } } pub fn readline(&mut self) -> Option<Value> { if self.buffer_index == -1 { let res = self.fill_buffer(); if res == 0 { return Some(Value::Null); } else if res == -1 { return None; } } let mut i = self.buffer_index; let mut found = false; while i < self.buffer_limit { if self.buffer[i as usize] == '\n' as u8 { i += 1; found = true; break; } i += 1; } if found { let slice = &self.buffer[self.buffer_index as usize..i as usize]; let s = String::from_utf8_lossy(slice); self.buffer_index = i; if self.buffer_index == self.buffer_limit { self.buffer_index = -1; self.buffer_limit = -1; } Some(new_string_value(s.to_string())) } else { let mut sbuf = Vec::new(); let res = self.reader.read_until('\n' as u8, &mut sbuf); match res { Ok(_) => { let bufvec = &mut self.buffer[self.buffer_index as usize.. self.buffer_limit as usize].to_vec(); bufvec.append(&mut sbuf); let s = String::from_utf8_lossy(bufvec); self.buffer_index = -1; self.buffer_limit = -1; Some(new_string_value(s.to_string())) } _ => None } } } } /// A hash object paired with its current index, for use within /// the various hash generators. #[derive(Debug, Clone)] pub struct HashWithIndex { pub i: usize, pub h: Value, } impl HashWithIndex { pub fn new(i: usize, h: Value) -> HashWithIndex { HashWithIndex { i, h } } } /// An IPv4 range object. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Ipv4Range { pub s: Ipv4Addr, pub e: Ipv4Addr, } impl Ipv4Range { pub fn new(s: Ipv4Addr, e: Ipv4Addr) -> Ipv4Range { Ipv4Range { s, e } } } /// An IPv6 range object. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Ipv6Range { pub s: Ipv6Addr, pub e: Ipv6Addr, } impl Ipv6Range { pub fn new(s: Ipv6Addr, e: Ipv6Addr) -> Ipv6Range { Ipv6Range { s, e } } } /// An IP set object. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct IpSet { pub ipv4: IpRange<Ipv4Net>, pub ipv6: IpRange<Ipv6Net>, } impl IpSet { pub fn new(ipv4: IpRange<Ipv4Net>, ipv6: IpRange<Ipv6Net>) -> IpSet { IpSet { ipv4, ipv6 } } pub fn shift(&mut self) -> Value { /* todo: not sure how else to implement this, since * the IP range object doesn't order by address. * Could serialise to a vector in the IPSet object, * but that might make other operations less * efficient. */ let mut ipranges = self.ipv4.iter().collect::<Vec<Ipv4Net>>(); ipranges.sort_by_key(|a| a.network()); let next = ipranges.first(); if let Some(next_value) = next { let mut next_range = IpRange::new(); next_range.add(*next_value); let new_set = self.ipv4.exclude(&next_range); self.ipv4 = new_set; return Value::Ipv4(*next_value); } let mut ipranges2 = self.ipv6.iter().collect::<Vec<Ipv6Net>>(); ipranges2.sort_by_key(|a| a.network()); let next2 = ipranges2.first(); if let Some(next2_value) = next2 { let mut next2_range = IpRange::new(); next2_range.add(*next2_value); let new_set = self.ipv6.exclude(&next2_range); self.ipv6 = new_set; return Value::Ipv6(*next2_value); } return Value::Null; } pub fn get(&self, n: usize) -> Value { let mut ipranges = self.ipv4.iter().collect::<Vec<Ipv4Net>>(); if ipranges.len() >= n + 1 { ipranges.sort_by_key(|a| a.network()); return Value::Ipv4(*ipranges.get(n).unwrap()); } let ipv6_index = n - ipranges.len(); let mut ipranges2 = self.ipv6.iter().collect::<Vec<Ipv6Net>>(); if ipranges2.len() >= ipv6_index + 1 { ipranges2.sort_by_key(|a| a.network()); return Value::Ipv6(*ipranges2.get(ipv6_index).unwrap()); } return Value::Null; } } /// MySQL database objects. #[derive(Debug, Clone)] pub struct DBConnectionMySQL { pub pool: sqlx::Pool<MySql>, } impl DBConnectionMySQL { pub fn new(pool: sqlx::Pool<MySql>) -> DBConnectionMySQL { DBConnectionMySQL { pool } } } #[derive(Debug)] pub struct DBStatementMySQL { pub pool: sqlx::Pool<MySql>, pub query: String, } impl DBStatementMySQL { pub fn new(pool: sqlx::Pool<MySql>, query: String) -> DBStatementMySQL { DBStatementMySQL { pool, query } } } /// PostgreSQL database objects. #[derive(Debug, Clone)] pub struct DBConnectionPostgres { pub pool: sqlx::Pool<Postgres>, } impl DBConnectionPostgres { pub fn new(pool: sqlx::Pool<Postgres>) -> DBConnectionPostgres { DBConnectionPostgres { pool } } } #[derive(Debug)] pub struct DBStatementPostgres { pub pool: sqlx::Pool<Postgres>, pub query: String, } impl DBStatementPostgres { pub fn new(pool: sqlx::Pool<Postgres>, query: String) -> DBStatementPostgres { DBStatementPostgres { pool, query } } } /// SQLite database objects. #[derive(Debug, Clone)] pub struct DBConnectionSQLite { pub pool: sqlx::Pool<Sqlite>, } impl DBConnectionSQLite { pub fn new(pool: sqlx::Pool<Sqlite>) -> DBConnectionSQLite { DBConnectionSQLite { pool } } } #[derive(Debug)] pub struct DBStatementSQLite { pub pool: sqlx::Pool<Sqlite>, pub query: String, } impl DBStatementSQLite { pub fn new(pool: sqlx::Pool<Sqlite>, query: String) -> DBStatementSQLite { DBStatementSQLite { pool, query } } } /// A channel generator object (see pmap). #[derive(Debug)] pub struct ChannelGenerator { pub rx: std::fs::File, pub pid: nix::unistd::Pid, pub input_generator: Value, pub finished: bool, } impl ChannelGenerator { pub fn new(rx: std::fs::File, pid: nix::unistd::Pid, input_generator: Value) -> ChannelGenerator { ChannelGenerator { rx, pid, input_generator, finished: false } } } /// A command generator object. pub struct CommandGenerator { /* The two pids are stored individually, rather than as a list, * because there will only ever be one or two processes that need * to be waited on. */ pub pid: Option<nix::unistd::Pid>, pub pid2: Option<nix::unistd::Pid>, pub value: Option<Value>, pub stdout: NonBlockingReader<ChildStdout>, pub stderr: NonBlockingReader<ChildStderr>, pub stdout_buffer: Vec<u8>, pub stderr_buffer: Vec<u8>, get_stdout: bool, get_stderr: bool, pub get_combined: bool, pub get_bytes: bool, pub status: Option<i32>, dropped: bool, } impl CommandGenerator { pub fn new( pid: Option<nix::unistd::Pid>, pid2: Option<nix::unistd::Pid>, value: Option<Value>, stdout: NonBlockingReader<ChildStdout>, stderr: NonBlockingReader<ChildStderr>, get_stdout: bool, get_stderr: bool, get_combined: bool, get_bytes: bool, ) -> CommandGenerator { CommandGenerator { pid, pid2, value, stdout, stderr, stdout_buffer: Vec::new(), stderr_buffer: Vec::new(), get_stdout, get_stderr, get_combined, get_bytes, status: None, dropped: false } } /// Determine whether standard output has been exhausted. fn stdout_eof(&mut self) -> bool { return self.stdout_buffer.is_empty() && self.stdout.is_eof(); } /// Determine whether standard error has been exhausted. fn stderr_eof(&mut self) -> bool { return self.stderr_buffer.is_empty() && self.stderr.is_eof(); } /// Read a line from standard output (non-blocking). fn stdout_read_line_nb(&mut self) -> Option<String> { let mut index = self.stdout_buffer.iter().position(|&r| r == b'\n'); if index.is_none() && !self.stdout.is_eof() { let _res = self.stdout.read_available(&mut self.stdout_buffer); index = self.stdout_buffer.iter().position(|&r| r == b'\n'); } match index { Some(n) => { /* todo: may not work if newline falls within * a multibyte Unicode character? Not sure if this * is possible, though. */ let new_buf: Vec<u8> = (&mut self.stdout_buffer).drain(0..(n + 1)).collect(); let new_str = String::from_utf8_lossy(&new_buf).to_string(); Some(new_str) } _ => { if !self.stdout_buffer.is_empty() && self.stdout.is_eof() { let new_buf: Vec<u8> = (&mut self.stdout_buffer).drain(..).collect(); let new_str = String::from_utf8_lossy(&new_buf).to_string(); Some(new_str) } else { None } } } } /// Read a line from standard error (non-blocking). fn stderr_read_line_nb(&mut self) -> Option<String> { let mut index = self.stderr_buffer.iter().position(|&r| r == b'\n'); if index.is_none() && !self.stderr.is_eof() { let _res = self.stderr.read_available(&mut self.stderr_buffer); index = self.stderr_buffer.iter().position(|&r| r == b'\n'); } match index { Some(n) => { /* todo: may not work if newline falls within * a multibyte Unicode character? Not sure if this * is possible, though. */ let new_buf: Vec<u8> = (&mut self.stderr_buffer).drain(0..(n + 1)).collect(); let new_str = String::from_utf8_lossy(&new_buf).to_string(); Some(new_str) } _ => { if !self.stderr_buffer.is_empty() && self.stderr.is_eof() { let new_buf: Vec<u8> = (&mut self.stderr_buffer).drain(..).collect(); let new_str = String::from_utf8_lossy(&new_buf).to_string(); Some(new_str) } else { None } } } } /// Read a line from standard output or standard error. This /// blocks until one returns a line. pub fn read_line(&mut self) -> Option<String> { loop { if self.get_stdout { let s = self.stdout_read_line_nb(); if s.is_some() { return s; } else if self.stdout_eof() && (!self.get_stderr || self.stderr_eof()) { return None; } } if self.get_stderr { let s = self.stderr_read_line_nb(); if s.is_some() { return s; } else if self.stderr_eof() && (!self.get_stdout || self.stdout_eof()) { return None; } } } } /// Read a line from standard output or standard error, and return /// an identifier for the stream and the string. This blocks /// until one returns a line. pub fn read_line_combined(&mut self) -> Option<(i32, String)> { loop { let so = self.stdout_read_line_nb(); match so { Some(ss) => { return Some((1, ss)); } _ => { if self.stdout_eof() && self.stderr_eof() { return None; } } } let se = self.stderr_read_line_nb(); match se { Some(ss) => { return Some((2, ss)); } _ => { if self.stderr_eof() && self.stdout_eof() { return None; } } } } } /// Read bytes from standard output and return the bytes as a /// list. By default, 1024 bytes are read on each call. pub fn read_bytes(&mut self) -> Option<Vec<u8>> { /* If get_bytes is set, then this is the only function that's * called, and it doesn't make use of the buffer. */ let mut bytes = Vec::new(); loop { let res_n = self.stdout.read_available(&mut bytes); match res_n { Ok(0) => { if self.stdout.is_eof() { return None; } else { continue; } } Ok(_) => { return Some(bytes); } _ => { return None; } } } } pub fn status(&self) -> Value { match self.status { Some(n) => { Value::Int(n) } _ => { Value::Null } } } /// Clean up the associated processes and store the exit code. #[allow(unused_must_use)] pub fn cleanup(&mut self) { if self.dropped { return; } match self.pid { Some(p) => { let res = waitpid(p, Some(WaitPidFlag::WNOHANG)); match res { Ok(WaitStatus::Exited(_, n)) => { self.status = Some(n); } Ok(WaitStatus::StillAlive) => { let res = nix::sys::signal::kill(p, Signal::SIGTERM); match res { Ok(_) => {} Err(e) => { eprintln!("unable to kill process: {}", e); } } } _ => {} } if self.status.is_none() { let es_res = waitpid(p, None); match es_res { Ok(WaitStatus::Exited(_, n)) => { self.status = Some(n); } _ => {} } } } _ => {} } match self.pid2 { Some(p) => { let res = waitpid(p, Some(WaitPidFlag::WNOHANG)); match res { Ok(WaitStatus::StillAlive) => { let res = nix::sys::signal::kill(p, Signal::SIGTERM); match res { Ok(_) => {} Err(e) => { eprintln!("unable to kill process: {}", e); } } } _ => {} } waitpid(p, None); } _ => {} } self.dropped = true; } } impl Drop for CommandGenerator { fn drop(&mut self) { self.cleanup(); } } impl Drop for ChannelGenerator { /// Kill the associated process when this is dropped. #[allow(unused_must_use)] fn drop(&mut self) { let p = self.pid; let res = waitpid(p, Some(WaitPidFlag::WNOHANG)); match res { Ok(WaitStatus::StillAlive) => { let res = nix::sys::signal::kill(p, Signal::SIGTERM); match res { Ok(_) => {} Err(e) => { eprintln!("unable to kill process: {}", e); } } } _ => {} } waitpid(p, None); } } /// The core value type used by the compiler and VM. #[derive(Clone)] pub enum Value { /// Used to indicate that a generator is exhausted. Null, /// Boolean. Bool(bool), /// Byte. Byte(u8), /// 32-bit integer. Int(i32), /// Unbounded integer. BigInt(num_bigint::BigInt), /// Floating-point number. Float(f64), /// String. The second part here is the regex object that /// corresponds to the string, which is generated and cached /// when the string is used as a regex. String(Rc<RefCell<StringTriple>>), /// An external command (wrapped in curly brackets), where the /// output is captured. Command(Rc<String>, Rc<HashSet<char>>), /// An external command (begins with $), where the output is not /// captured. CommandUncaptured(Rc<String>), /// A list. List(Rc<RefCell<VecDeque<Value>>>), /// A hash. Hash(Rc<RefCell<CoshIndexMap<String, Value>>>), /// A set. The stringification of the value is used as the map /// key, and the set may only contain values of a single type. /// (Not terribly efficient, but can be made decent later without /// affecting the language interface.) Set(Rc<RefCell<CoshIndexMap<String, Value>>>), /// An anonymous function (includes reference to local variable /// stack). AnonymousFunction(Rc<RefCell<Chunk>>, Rc<RefCell<Vec<Value>>>), /// A core function. See SIMPLE_FORMS in the VM. CoreFunction(fn(&mut VM) -> i32), /// A named function. NamedFunction(Rc<RefCell<Chunk>>), /// A generator constructed by way of a generator function. Generator(Rc<RefCell<GeneratorObject>>), /// A generator for getting the output of a Command. CommandGenerator(Rc<RefCell<CommandGenerator>>), /// A generator over the keys of a hash. KeysGenerator(Rc<RefCell<HashWithIndex>>), /// A generator over the values of a hash. ValuesGenerator(Rc<RefCell<HashWithIndex>>), /// A generator over key-value pairs (lists) of a hash. EachGenerator(Rc<RefCell<HashWithIndex>>), /// A file reader value. FileReader(Rc<RefCell<BufReaderWithBuffer<File>>>), /// A file writer value. FileWriter(Rc<RefCell<BufWriter<File>>>), /// A directory handle. DirectoryHandle(Rc<RefCell<ReadDir>>), /// A datetime with a named timezone. DateTimeNT(DateTime<chrono_tz::Tz>), /// A datetime with an offset timezone. DateTimeOT(DateTime<FixedOffset>), /// An IPv4 address/prefix object. Ipv4(Ipv4Net), /// An IPv6 address/prefix object. Ipv6(Ipv6Net), /// An IPv4 range object (arbitrary start/end addresses). Ipv4Range(Ipv4Range), /// An IPv6 range object (arbitrary start/end addresses). Ipv6Range(Ipv6Range), /// An IP set (IPv4 and IPv6 together). IpSet(Rc<RefCell<IpSet>>), /// Multiple generators combined together. MultiGenerator(Rc<RefCell<VecDeque<Value>>>), /// A generator over the shell history. This is presented as a /// 'plain' generator outside of the compiler. HistoryGenerator(Rc<RefCell<i32>>), /// A generator from a channel from a forked process. ChannelGenerator(Rc<RefCell<ChannelGenerator>>), /// A MySQL database connection. DBConnectionMySQL(Rc<RefCell<DBConnectionMySQL>>), /// A MySQL database statement. DBStatementMySQL(Rc<RefCell<DBStatementMySQL>>), /// A PostgreSQL database connection. DBConnectionPostgres(Rc<RefCell<DBConnectionPostgres>>), /// A PostgreSQL database statement. DBStatementPostgres(Rc<RefCell<DBStatementPostgres>>), /// A SQLite database connection. DBConnectionSQLite(Rc<RefCell<DBConnectionSQLite>>), /// A SQLite database statement. DBStatementSQLite(Rc<RefCell<DBStatementSQLite>>), /// A value that when accessed, indicates that a scope error has /// occurred. ScopeError, /// A TCP socket reader. TcpSocketReader(Rc<RefCell<BufReaderWithBuffer<TcpStream>>>), /// A TCP socket writer. TcpSocketWriter(Rc<RefCell<BufWriter<TcpStream>>>), } impl fmt::Debug for Value { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Value::Null => { write!(f, "Null") } Value::Byte(i) => { write!(f, "{:#04x}", i) } Value::Int(i) => { write!(f, "{}", i) } Value::BigInt(i) => { write!(f, "{}", i) } Value::Float(i) => { write!(f, "{}", i) } Value::Bool(b) => { write!(f, "{}", b) } Value::String(s) => { let ss = &s.borrow().string; write!(f, "\"{}\"", ss) } Value::Command(s, _) => { write!(f, "Command \"{}\"", s) } Value::CommandUncaptured(s) => { write!(f, "CommandUncaptured \"{}\"", s) } Value::List(ls) => { write!(f, "{:?}", ls) } Value::Hash(hs) => { write!(f, "{:?}", hs) } Value::Set(st) => { write!(f, "{:?}", st) } Value::AnonymousFunction(_, _) => { write!(f, "((Function))") } Value::CoreFunction(_) => { write!(f, "((CoreFunction))") } Value::NamedFunction(_) => { write!(f, "((NamedFunction))") } Value::Generator(_) => { write!(f, "((Generator))") } Value::CommandGenerator(_) => { write!(f, "((CommandGenerator))") } Value::KeysGenerator(_) => { write!(f, "((KeysGenerator))") } Value::ValuesGenerator(_) => { write!(f, "((ValuesGenerator))") } Value::EachGenerator(_) => { write!(f, "((EachGenerator))") } Value::FileReader(_) => { write!(f, "((FileReader))") } Value::FileWriter(_) => { write!(f, "((FileWriter))") } Value::DirectoryHandle(_) => { write!(f, "((DirectoryHandle))") } Value::DateTimeNT(_) => { write!(f, "((DateTimeNT))") } Value::DateTimeOT(_) => { write!(f, "((DateTimeOT))") } Value::Ipv4(_) => { write!(f, "((IPv4))") } Value::Ipv4Range(_) => { write!(f, "((IPv4Range))") } Value::Ipv6(_) => { write!(f, "((IPv6))") } Value::Ipv6Range(_) => { write!(f, "((IPv6))") } Value::IpSet(_) => { write!(f, "((IpSet))") } Value::MultiGenerator(_) => { write!(f, "((MultiGenerator))") } Value::HistoryGenerator(_) => { write!(f, "((Generator))") } Value::DBConnectionMySQL(_) => { write!(f, "((DBConnection))") } Value::DBStatementMySQL(_) => { write!(f, "((DBStatement))") } Value::DBConnectionPostgres(_) => { write!(f, "((DBConnection))") } Value::DBStatementPostgres(_) => { write!(f, "((DBStatement))") } Value::DBConnectionSQLite(_) => { write!(f, "((DBConnection))") } Value::DBStatementSQLite(_) => { write!(f, "((DBStatement))") } Value::ChannelGenerator(_) => { write!(f, "((ChannelGenerator))") } Value::ScopeError => { write!(f, "((ScopeError))") } Value::TcpSocketReader(_) => { write!(f, "((SocketReader))") } Value::TcpSocketWriter(_) => { write!(f, "((SocketWriter))") } } } } /// An enum for the Value types that can be parsed from literals,
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/compiler.rs
src/compiler.rs
use std::cell::RefCell; use std::collections::HashSet; use std::convert::TryInto; use std::fs; use std::io::BufRead; use std::io::ErrorKind; use std::io::Read; use std::io::Write; use std::rc::Rc; use std::str; use lazy_static::lazy_static; use regex::Regex; use crate::chunk::{Chunk, StringTriple, Value, new_string_value}; use crate::opcode::OpCode; /// The various token types used by the compiler. #[derive(Debug, Clone)] pub enum TokenType { True, False, Null, LeftBracket, RightBracket, LeftBrace, RightBrace, StartFunction, StartGenerator, EndFunction, Int(i32), BigInt(num_bigint::BigInt), Float(f64), String(String), Command(String, HashSet<char>), /// This is a Command that includes a ';' character at the end, or /// otherwise should be executed immediately (e.g. it's followed /// by a newline). CommandExplicit(String, HashSet<char>), CommandUncaptured(String), Word(String), /// This is a Word that should be executed implicitly (e.g. it's /// followed by a newline). WordImplicit(String), StartList, StartHash, StartSet, /// The EndList token also serves as the terminating token for /// hashes and sets, which is why there is no EndHash or EndSet /// token. EndList, /// A dummy token that indicates that the caller should try to /// fetch another token. Retry, Error, Eof, } /// The token struct, which includes the line and column number where /// the token begins. #[derive(Debug, Clone)] pub struct Token { token_type: TokenType, column_number: u32, line_number: u32, } impl Token { fn new(token_type: TokenType, line_number: u32, column_number: u32) -> Token { Token { token_type, line_number, column_number, } } } /// A Local is a local variable. The depth of a Local is its scope /// depth, which will always be greater than one. #[derive(Debug)] pub struct Local { name: String, depth: u32, } impl Local { pub fn new(name: String, depth: u32) -> Local { Local { name, depth } } } /// A Scanner is used to get tokens from a BufRead object. It manages /// a single character of lookahead. pub struct Scanner<'a> { fh: &'a mut Box<dyn BufRead>, line_number: u32, column_number: u32, token_line_number: u32, token_column_number: u32, has_lookahead: bool, lookahead: u8, next_is_eof: bool, interactive_mode: bool, } lazy_static! { static ref INT: Regex = Regex::new(r"^-?\d+$").unwrap(); } impl<'a> Scanner<'a> { pub fn new(fh: &mut Box<dyn BufRead>, interactive_mode: bool) -> Scanner { Scanner { fh, line_number: 1, column_number: 1, token_line_number: 1, token_column_number: 1, has_lookahead: false, lookahead: 0, next_is_eof: false, interactive_mode, } } /// Scans the BufRead for potential parameters, and returns a /// char set for those parameters if they are present. Parameters /// are currently used only with commands. pub fn scan_parameters(&mut self) -> Option<HashSet<char>> { let mut buffer = [0; 1]; let mut eof = false; let mut done = false; let mut parameters: HashSet<char> = HashSet::new(); if self.has_lookahead { buffer[0] = self.lookahead; self.has_lookahead = false; } else { self.fh.read_exact(&mut buffer).unwrap_or_else(|e| { if e.kind() == ErrorKind::UnexpectedEof { eof = true; } else { eprintln!("unable to read from buffer!"); std::process::abort(); } }); if eof { self.next_is_eof = true; return None; } } match buffer[0] as char { '/' => { /* Has parameters. */ self.column_number += 1; while !done { self.fh.read_exact(&mut buffer).unwrap_or_else(|e| { if e.kind() == ErrorKind::UnexpectedEof { eof = true; } else { eprintln!("unable to read from buffer!"); std::process::abort(); } }); if eof { self.next_is_eof = true; return Some(parameters); } if char::is_whitespace(buffer[0] as char) || buffer[0] == b';' { self.lookahead = buffer[0]; self.has_lookahead = true; done = true; } else { parameters.insert(buffer[0] as char); self.column_number += 1; } } Some(parameters) } _ => { self.lookahead = buffer[0]; self.has_lookahead = true; None } } } /// Skip any whitespace, updating line and column numbers /// accordingly. The next non-whitespace character will be set as /// the lookahead character. Returns a boolean indicating whether /// EOF was not hit. pub fn skip_whitespace(&mut self) -> bool { let mut buffer = [0; 1]; let mut eof = false; loop { if self.has_lookahead { buffer[0] = self.lookahead; self.has_lookahead = false; self.column_number += 1; if self.token_line_number == 0 { self.token_line_number = self.line_number; self.token_column_number = self.column_number; } } else { self.fh.read_exact(&mut buffer).unwrap_or_else(|e| { if e.kind() == ErrorKind::UnexpectedEof { eof = true; } else { eprintln!("unable to read from buffer!"); std::process::abort(); } }); } if eof { return false; } match buffer[0] as char { '\n' => { self.line_number += 1; self.column_number = 1; } ' ' => { self.column_number += 1; } '\t' => { self.column_number = self.column_number + (self.column_number % 4); } _ => { self.has_lookahead = true; self.lookahead = buffer[0] as u8; self.column_number -= 1; return true; } } } } /// Returns a new token object for the given token type. pub fn get_token(&self, token_type: TokenType) -> Token { Token::new(token_type, self.token_line_number, self.token_column_number) } /// Scans the BufRead for the next token, and returns it. pub fn scan(&mut self) -> Token { let at_start_of_line = self.column_number == 1; if self.next_is_eof { self.next_is_eof = false; return Token::new(TokenType::Eof, self.line_number, self.column_number); } /* For storing the token as a whole. */ let mut result = [0; 2048]; /* The current index into which the next token character * should be written. */ let mut result_index = 0; /* The buffer for reading a character from the input stream. * */ let mut buffer = [0; 1]; /* Whether the token is a string (i.e. can contain * whitespace). */ let mut is_string = false; /* Whether token parsing is currently inside the string. */ let mut in_string = false; /* The delimiter for the string (if applicable). */ let mut string_delimiter = ' '; /* Skip whitespace, and deal with the first character of the * token. */ let res = self.skip_whitespace(); if !res { return self.get_token(TokenType::Eof); } buffer[0] = self.lookahead; self.has_lookahead = false; self.column_number += 1; self.token_line_number = self.line_number; self.token_column_number = self.column_number; self.column_number += 1; if (buffer[0] as char == '"') || (buffer[0] as char == '\'') || (buffer[0] as char == '{') || (buffer[0] as char == '$' && self.interactive_mode) { string_delimiter = buffer[0] as char; in_string = true; is_string = true; } else { result[result_index] = buffer[0]; result_index += 1; match buffer[0] as char { '#' => { /* Treat this as a comment only if it occurs * at the start of the line (whether after * whitespace or not). */ if at_start_of_line { let mut ignored = String::new(); self.fh.read_line(&mut ignored).unwrap(); self.line_number += 1; self.column_number = 1; return self.get_token(TokenType::Retry); } } '(' => { return self.get_token(TokenType::StartList); } ')' => { return self.get_token(TokenType::EndList); } '[' => { return self.get_token(TokenType::LeftBracket); } ']' => { return self.get_token(TokenType::RightBracket); } _ => {} } } /* This loop is for getting the rest of the token. */ let mut done = false; let mut last_escaped = false; let mut brace_count = 0; let mut params: HashSet<char> = HashSet::new(); while !done { let mut eof = false; self.fh.read_exact(&mut buffer).unwrap_or_else(|e| { if e.kind() == ErrorKind::UnexpectedEof { eof = true; } else { eprintln!("unable to read from buffer!"); std::process::abort(); } }); if eof { if result_index == 0 { return self.get_token(TokenType::Eof); } else { self.next_is_eof = true; break; } } match buffer[0] as char { '\n' => { self.line_number += 1; self.column_number = 1; } ' ' => { self.column_number += 1; } '\t' => { self.column_number = self.column_number + (self.column_number % 4); } '(' => { self.column_number += 1; if result_index == 1 { match result[0] as char { 'h' => return self.get_token(TokenType::StartHash), 's' => { return self.get_token(TokenType::StartSet); } _ => {} } } } _ => { self.column_number += 1; } } if in_string { if string_delimiter == '{' { /* Commands may contain nested braces, which are * used for value substitution, which is why there is * extra processing here. Commands may also have * parameters attached to the end of them. */ if result_index >= 1 && result[result_index - 1] as char == '\\' && !last_escaped { result[result_index] = buffer[0]; result_index += 1; } else { if buffer[0] as char == '{' { brace_count += 1; } else if buffer[0] as char == '}' { brace_count -= 1; } if brace_count < 0 { in_string = false; done = true; let params_opt = self.scan_parameters(); if let Some(po) = params_opt { params = po; } } else { result[result_index] = buffer[0]; result_index += 1; } } } else if string_delimiter == '$' && self.interactive_mode { /* Uncaptured commands do not need to include a * terminating delimiter. */ result[result_index] = buffer[0]; result_index += 1; } else if buffer[0] as char == string_delimiter { if result_index > 0 && result[result_index - 1] as char == '\\' { result[result_index - 1] = buffer[0]; } else { in_string = false; done = true; } } else { result[result_index] = buffer[0]; result_index += 1; } } else { match buffer[0] as char { '\n' | '\t' => { done = true; } ' ' => { if result_index >= 1 && result[result_index - 1] as char == '\\' && !last_escaped { result[result_index - 1] = buffer[0]; } else { done = true; } } /* A token that ends in a right parenthesis or * right bracket is stopped on the previous * character, to allow for syntax like '(1 2 3)'. * */ ')' => { self.has_lookahead = true; self.lookahead = buffer[0] as u8; self.column_number -= 1; done = true; } ']' => { self.has_lookahead = true; self.lookahead = buffer[0] as u8; self.column_number -= 1; done = true; } _ => { if result_index >= 2048 { eprintln!("token is too long (more than 2048 chars)"); return self.get_token(TokenType::Error); } if result_index > 0 && result[result_index - 1] as char == '\\' && buffer[0] as char == '\\' && !last_escaped { last_escaped = true; } else { last_escaped = false; } result[result_index] = buffer[0]; result_index += 1; let c = buffer[0] as char; if result_index == 1 && (c == '{' || c == '}' || c == '[' || c == ']') { done = true; } } } } /* Allow for the execution character ';' to occur after * whitespace. */ if done && (buffer[0] as char) != '\n' { let res = self.skip_whitespace(); if res && self.lookahead == b';' { self.column_number += 1; result[result_index] = self.lookahead; self.has_lookahead = false; result_index += 1; } } } if in_string { /* Uncaptured commands do not need to include a * terminating delimiter, so there is special handling for * them here. */ if string_delimiter == '$' && self.interactive_mode { result[result_index] = 0; let s_all = str::from_utf8(&result).unwrap(); let s = &s_all[..result_index]; return self.get_token(TokenType::CommandUncaptured(s.to_string())); } else { eprintln!( "{}:{}: unterminated string literal '{}'", self.token_line_number, self.token_column_number, string_delimiter ); return self.get_token(TokenType::Error); } } /* Determine whether the word is explicit or implicit. An * explicit word terminates in the execution character, while * an implicit word terminates with a newline, the right * bracket of an anonymous function, or EOF. */ let mut is_explicit_word = false; let mut is_implicit_word = false; if result_index > 1 && (result[result_index - 1] as char) == ';' { is_explicit_word = true; result_index -= 1; } if (buffer[0] as char) == '\n' || self.next_is_eof || (self.has_lookahead && self.lookahead == b']') { is_implicit_word = true; } result[result_index] = 0; let s_all = str::from_utf8(&result).unwrap(); let s = &s_all[..result_index]; let token_type = if !is_string { match s { "h(" => TokenType::StartHash, "s(" => TokenType::StartSet, "(" => TokenType::StartList, ")" => TokenType::EndList, "{" => TokenType::LeftBrace, "}" => TokenType::RightBrace, "[" => TokenType::LeftBracket, "]" => TokenType::RightBracket, ":" => TokenType::StartFunction, ":~" => TokenType::StartGenerator, ",," => TokenType::EndFunction, ".t" => TokenType::True, ".f" => TokenType::False, "null" => TokenType::Null, _ => { if INT.is_match(s) { let n_res = s.to_string().parse::<i32>(); match n_res { Ok(n) => TokenType::Int(n), Err(_) => { let n = s.to_string().parse::<num_bigint::BigInt>().unwrap(); TokenType::BigInt(n) } } } else if is_explicit_word { TokenType::Word(s.to_string()) } else if is_implicit_word { TokenType::WordImplicit(s.to_string()) } else { TokenType::String(s.to_string()) } } } } else if string_delimiter == '{' { if is_explicit_word || is_implicit_word { TokenType::CommandExplicit(s.to_string(), params) } else { TokenType::Command(s.to_string(), params) } } else { TokenType::String(s.to_string()) }; self.get_token(token_type) } } /// A Compiler compiles program code (by way of a scanner) into /// bytecode, in the form of a chunk. #[derive(Debug)] pub struct Compiler { locals: Vec<Local>, scope_depth: u32, interactive_mode: bool, } /// Unescapes a single string value, by replacing string /// representations of certain characters (e.g. "\n") with the actual /// character. pub fn unescape_string(s: &str) -> String { let mut s2 = String::from(""); let mut next_escaped = false; for c in s.chars() { if next_escaped { match c { 'n' => { s2.push('\n'); } 't' => { s2.push('\t'); } 'r' => { s2.push('\r'); } '\\' => { s2.push('\\'); } '\'' => { s2.push('\''); } '"' => { s2.push('\"'); } _ => { s2.push('\\'); s2.push(c); } } next_escaped = false; } else { match c { '\\' => { next_escaped = true; } _ => { next_escaped = false; s2.push(c); } } } } s2 } impl Compiler { pub fn new() -> Compiler { Compiler { locals: Vec::new(), scope_depth: 0, interactive_mode: false, } } pub fn new_interactive() -> Compiler { Compiler { locals: Vec::new(), scope_depth: 0, interactive_mode: true, } } /// Increases the scope depth. Used when a new function is /// defined (whether a named function or an anonymous one). fn increase_scope_depth(&mut self) { self.scope_depth += 1; } /// Decreases the scope depth. This adds appropriate pop opcodes /// for dealing with local variables that will no longer be in use /// after the scope depth is decreased. fn decrease_scope_depth(&mut self, chunk: &mut Chunk, ln: u32, cn: u32) -> bool { while !self.locals.is_empty() && (self.locals.last().unwrap().depth == self.scope_depth) { chunk.add_opcode(OpCode::PopLocalVar); self.locals.pop(); } if self.scope_depth == 0 { eprintln!( "{}:{}: attempting to close scope at top level", ln, cn ); return false; } self.scope_depth -= 1; return true; } /// Takes a scanner and a chunk as its arguments. Reads tokens by /// way of the scanner, and compiles that token data into /// bytecode, which is added to the chunk. Returns a boolean /// indicating whether compilation was successful. fn compile_inner(&mut self, scanner: &mut Scanner, chunk: &mut Chunk) -> bool { // Stores instruction indexes for various types of statement, // in order to be able to jump later. let mut if_indexes: Vec<(Option<usize>, Option<usize>)> = Vec::new(); let mut if_index = None; let mut else_index = None; let mut begin_indexes: Vec<(Option<usize>, Vec<usize>)> = Vec::new(); let mut begin_index = None; let mut leave_indexes: Vec<usize> = Vec::new(); // The current anonymous function index. let mut anon_index = 0; // Whether this chunk has global variables. let mut has_vars = false; loop { let token = scanner.scan(); chunk.set_next_point(token.line_number, token.column_number); let mut is_implicit = false; let token_type = token.token_type; if let TokenType::WordImplicit(_) = token_type { is_implicit = true; } match token_type { TokenType::Retry => { continue; } TokenType::StartList => { chunk.add_opcode(OpCode::StartList); } TokenType::StartHash => { chunk.add_opcode(OpCode::StartHash); } TokenType::StartSet => { chunk.add_opcode(OpCode::StartSet); } TokenType::EndList => { chunk.add_opcode(OpCode::EndList); } TokenType::Eof => { break; } TokenType::Error => { return false; } TokenType::StartGenerator => { let name_token = scanner.scan(); let name_str = match name_token.token_type { TokenType::Word(s) => s, TokenType::WordImplicit(s) => s, TokenType::String(s) => s, _ => { eprintln!( "{}:{}: expected name token", name_token.line_number, name_token.column_number ); return false; } }; let arg_count_token = scanner.scan(); let arg_count = match arg_count_token.token_type { TokenType::Int(n) => n, _ => { eprintln!( "{}:{}: expected argument count token", arg_count_token.line_number, arg_count_token.column_number ); return false; } }; let req_arg_count_token = scanner.scan(); let req_arg_count = match req_arg_count_token.token_type { TokenType::Int(n) => n, _ => { eprintln!( "{}:{}: expected required argument count token", req_arg_count_token.line_number, req_arg_count_token.column_number ); return false; } }; let mut generator_chunk = Chunk::new_generator(chunk.name.to_string(), arg_count, req_arg_count); self.increase_scope_depth(); let res = self.compile_inner(scanner, &mut generator_chunk); if !res { return false; } chunk .functions .insert(name_str, Rc::new(RefCell::new(generator_chunk))); } TokenType::StartFunction => { let mut function_chunk = Chunk::new_standard(chunk.name.to_string()); let name_token = scanner.scan(); let name_str = match name_token.token_type { TokenType::Word(s) => s, TokenType::WordImplicit(s) => s, TokenType::String(s) => s, _ => { eprintln!( "{}:{}: expected name token", name_token.line_number, name_token.column_number ); return false; } }; self.increase_scope_depth(); if self.scope_depth > 1 { function_chunk.nested = true; function_chunk.scope_depth = self.scope_depth; } let res = self.compile_inner(scanner, &mut function_chunk); if !res { return false; } chunk .functions .insert(name_str, Rc::new(RefCell::new(function_chunk))); } TokenType::EndFunction => { let res = self.decrease_scope_depth(chunk, token.line_number, token.column_number); if !res { return false; } chunk.add_opcode(OpCode::EndFn); if !has_vars { chunk.has_vars = false; } return true; } TokenType::LeftBracket => { let mut function_chunk = Chunk::new_standard(chunk.name.to_string()); if self.scope_depth > 0 { function_chunk.nested = true; function_chunk.scope_depth = self.scope_depth; } let name_str = format!("anon{}", anon_index); anon_index += 1; self.increase_scope_depth(); let res = self.compile_inner(scanner, &mut function_chunk); if !res { return false; } let name_str_rr = new_string_value(name_str.as_str().to_string()); chunk.add_opcode(OpCode::Function); chunk.add_constant_and_index(name_str_rr); chunk .functions .insert(name_str, Rc::new(RefCell::new(function_chunk))); } TokenType::RightBracket => { if let Some(OpCode::Constant) = chunk.get_second_last_opcode() { match chunk.get_last_opcode() { Some(OpCode::Call) => {} Some(OpCode::CallImplicit) => {} _ => { chunk.add_opcode(OpCode::CallImplicit); } } } let res = self.decrease_scope_depth(chunk, token.line_number, token.column_number); if !res { return false; } chunk.add_opcode(OpCode::EndFn); if !has_vars { chunk.has_vars = false; } return true; } TokenType::True => { let value_rr = Value::Bool(true); chunk.add_opcode(OpCode::Constant); chunk.add_constant_and_index(value_rr); } TokenType::False => { let value_rr = Value::Bool(false); chunk.add_opcode(OpCode::Constant); chunk.add_constant_and_index(value_rr); } TokenType::Int(n) => { let value_rr = Value::Int(n); chunk.add_opcode(OpCode::Constant); chunk.add_constant_and_index(value_rr); } TokenType::BigInt(n) => { let value_rr = Value::BigInt(n); chunk.add_opcode(OpCode::Constant); chunk.add_constant_and_index(value_rr); } TokenType::Float(n) => { let value_rr = Value::Float(n); chunk.add_opcode(OpCode::Constant); chunk.add_constant_and_index(value_rr); } TokenType::Word(s) | TokenType::WordImplicit(s) => { if s == "+" { match chunk.get_third_last_opcode() {
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/bin/cosh.rs
src/bin/cosh.rs
extern crate cosh; extern crate ctrlc; extern crate dirs; extern crate getopts; extern crate nix; extern crate regex; extern crate rustyline; extern crate tempfile; use std::cell::RefCell; use std::collections::HashMap; use std::env; use nix::fcntl::{Flock, FlockArg}; use std::fs; use std::fs::OpenOptions; use std::io::Write; use std::io::{BufRead, BufReader, Cursor}; use std::path::Path; use std::rc::Rc; use std::sync::atomic::Ordering; use std::time::{SystemTime, UNIX_EPOCH}; use cpu_time::ProcessTime; use getopts::Options; use regex::Regex; use rustyline::config::OutputStreamType; use rustyline::error::ReadlineError; use rustyline::{ At, Cmd, CompletionType, Config, EditMode, Editor, KeyPress, Movement, Word, }; use cosh::chunk::{Chunk, new_string_value}; use cosh::compiler::Compiler; use cosh::vm::VM; use cosh::rl::{RLHelper, ShellCompleter}; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options] [file] [args]", program); print!("{}", opts.usage(&brief)); } fn import_cosh_conf(vm: &mut VM, global_functions: Rc<RefCell<HashMap<String, Rc<RefCell<Chunk>>>>>) { let home_opt = dirs::home_dir(); let config_opt = dirs::config_dir(); match (home_opt, config_opt) { (Some(home), Some(config)) => { let old_path = format!("{}/.coshrc", home.into_os_string().into_string().unwrap()); let new_path = format!("{}/cosh.conf", config.into_os_string().into_string().unwrap()); let has_old_path = Path::new(&old_path).exists(); let has_new_path = Path::new(&new_path).exists(); if has_old_path && !has_new_path { eprintln!("error: please move '{}' to new expected location '{}'", old_path, new_path); std::process::exit(1); } if has_new_path { let file_res = fs::File::open(new_path); if let Ok(file) = file_res { let mut bufread: Box<dyn BufRead> = Box::new(BufReader::new(file)); let chunk_opt = vm.interpret(&mut bufread, "cosh.conf"); if let Some(chunk) = chunk_opt { for (k, v) in chunk.borrow().functions.iter() { if !k.starts_with("anon") { global_functions.borrow_mut().insert(k.clone(), v.clone()); } } } } } } _ => {} } } fn main() { let args: Vec<String> = env::args().collect(); let mut program = args[0].clone(); let mut program_done = false; let md_opt = fs::metadata(&program); if let Ok(md) = md_opt { if md.is_file() { program_done = true; } } if !program_done { program = format!("/proc/{}/exe", std::process::id()); } let mut opts = Options::new(); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "bytecode", "input file is bytecode (for compilation)"); opts.optflag("c", "compile", "compile to bytecode"); opts.optflag("", "disassemble", "disassemble from bytecode"); opts.optflag("", "no-rt", "run without loading runtime"); opts.optflag("", "no-cosh-conf", "run without loading cosh.conf"); opts.optflag("d", "debug", "show debug information"); opts.optopt("e", "", "run single expression", "EXPR"); opts.optopt("o", "", "set output file name for compilation", "NAME"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { eprintln!("unable to parse option: {}", f); std::process::exit(1); } }; if matches.opt_present("h") { print_usage(&program, opts); return; } if matches.opt_present("disassemble") && matches.opt_present("bytecode") { println!("--bytecode and --disassemble options are mutually exclusive."); print_usage(&program, opts); return; } let libdir_opt: Option<&'static str> = option_env!("libdir"); let libdir = match libdir_opt { Some(s) => s, None => "/usr/local/lib" }; let rt_chc = format!("{}/cosh/rt.chc", libdir); let debug = matches.opt_present("debug"); let expr_opt = matches.opt_str("e"); if !matches.free.is_empty() { /* A path has been provided, so the user is attempting to run * non-interactively, for compilation/disassembly or similar. * */ let path = &matches.free[0]; if matches.opt_present("disassemble") { let mut compiler = Compiler::new(); let chunk_opt = compiler.deserialise(path); if chunk_opt.is_none() { eprintln!("unable to deserialise file"); std::process::exit(1); } let chunk = chunk_opt.unwrap(); chunk.disassemble(path); } else if matches.opt_present("bytecode") { let mut compiler = Compiler::new(); let chunk_opt = compiler.deserialise(path); if chunk_opt.is_none() { eprintln!("unable to deserialise file"); std::process::exit(1); } let chunk = Rc::new(RefCell::new(chunk_opt.unwrap())); let mut vm = VM::new(true, debug, Rc::new(RefCell::new(HashMap::new())), Rc::new(RefCell::new(HashMap::new())), libdir); let mut functions = Vec::new(); if !matches.opt_present("no-rt") { let mut rtchunk_opt = compiler.deserialise(&rt_chc); if rtchunk_opt.is_none() { rtchunk_opt = compiler.deserialise("./rt.chc"); if rtchunk_opt.is_none() { eprintln!("unable to deserialise runtime library"); std::process::exit(1); } } functions.push(Rc::new(RefCell::new(rtchunk_opt.unwrap()))); } if !functions.is_empty() { vm.call_stack_chunks.push((functions[0].clone(), 0)); } vm.run(chunk); } else { let file_res = fs::File::open(path); match file_res { Ok(_) => {} Err(e) => { let err_str = format!("unable to open file: {}", e); eprintln!("{}", err_str); std::process::exit(1); } } let file = file_res.unwrap(); let mut bufread: Box<dyn BufRead> = Box::new(BufReader::new(file)); if matches.opt_present("c") { let mut compiler = Compiler::new(); let re_pre = Regex::new(r#".*/"#).unwrap(); let path1 = re_pre.replace_all(path, ""); let re_post = Regex::new(r#"\..*"#).unwrap(); let name = re_post.replace_all(&path1, ""); let res = compiler.compile(&mut bufread, &name); if let Some(chunk) = res { let output_path_opt = matches.opt_str("o"); if output_path_opt.is_none() { eprintln!("output path is required for compilation"); std::process::exit(1); } let output_path = output_path_opt.unwrap(); let mut res = true; let mut err_str = "".to_owned(); { let file_res = fs::File::create(output_path.clone()); match file_res { Ok(mut file) => { compiler.serialise(&chunk, &mut file); } Err(e) => { res = false; err_str = e.to_string(); } } } if !res { eprintln!("unable to write to path {}: {}", output_path, err_str); } } } else { let mut vm = VM::new(true, debug, Rc::new(RefCell::new(HashMap::new())), Rc::new(RefCell::new(HashMap::new())), libdir); let global_functions = Rc::new(RefCell::new(HashMap::new())); if !matches.opt_present("no-rt") { vm.stack.push(new_string_value("rt".to_string())); let res = vm.opcode_import(); if res == 0 { std::process::exit(1); } } if !matches.opt_present("no-cosh-conf") { import_cosh_conf(&mut vm, global_functions.clone()); } for arg in &matches.free[1..] { vm.stack.push(new_string_value(arg.to_string())); } vm.interpret(&mut bufread, "(main)"); } } } else if !expr_opt.is_none() { let expr = expr_opt.unwrap(); let global_functions = Rc::new(RefCell::new(HashMap::new())); let global_vars = Rc::new(RefCell::new(HashMap::new())); let mut vm = VM::new(true, debug, global_functions.clone(), global_vars.clone(), libdir); if !matches.opt_present("no-rt") { vm.stack.push(new_string_value("rt".to_string())); let res = vm.opcode_import(); if res == 0 { std::process::exit(1); } } let running_clone = vm.running.clone(); ctrlc::set_handler(move || { running_clone.store(false, Ordering::SeqCst); }) .unwrap(); if !matches.opt_present("no-cosh-conf") { import_cosh_conf(&mut vm, global_functions.clone()); } let mut bufread: Box<dyn BufRead> = Box::new(Cursor::new(expr.into_bytes())); vm.interpret(&mut bufread, "(main)"); } else { /* A path has not been provided, so start the shell. */ let global_functions = Rc::new(RefCell::new(HashMap::new())); let global_vars = Rc::new(RefCell::new(HashMap::new())); let mut vm = VM::new(true, debug, global_functions.clone(), global_vars.clone(), libdir); if !matches.opt_present("no-rt") { vm.stack.push(new_string_value("rt".to_string())); let res = vm.opcode_import(); if res == 0 { std::process::exit(1); } } let running_clone = vm.running.clone(); ctrlc::set_handler(move || { running_clone.store(false, Ordering::SeqCst); }) .unwrap(); if !matches.opt_present("no-cosh-conf") { import_cosh_conf(&mut vm, global_functions.clone()); } let config = Config::builder() .completion_type(CompletionType::List) .edit_mode(EditMode::Emacs) .output_stream(OutputStreamType::Stdout) .build(); let helper = RLHelper { completer: ShellCompleter::new(global_functions.clone(), global_vars), }; let mut rl = Editor::with_config(config); rl.bind_sequence( KeyPress::ControlLeft, Cmd::Move(Movement::BackwardWord(1, Word::Vi)), ); rl.bind_sequence( KeyPress::ControlRight, Cmd::Move(Movement::ForwardWord(1, At::AfterEnd, Word::Vi)), ); rl.set_helper(Some(helper)); let homedir_res = std::env::var("HOME"); let history_path_opt = match homedir_res { Ok(homedir) => { Some(format!("{}/.cosh_history", homedir)) } _ => { None } }; /* There isn't a "no limit" setting in rustyline, so just set * it to an arbitrary large number. */ rl.history_mut().set_max_len(1000000); if let Some(history_path) = history_path_opt.clone() { if rl.load_history(&history_path).is_err() {} } let history_start_len = rl.history().len(); let rl_rr = Rc::new(RefCell::new(rl)); vm.readline = Some(rl_rr.clone()); // Keep track of the last known working directory for the prompt let mut last_known_cwd = env::current_dir() .map(|p| p.as_path().to_str().unwrap_or("/").to_string()) .unwrap_or_else(|_| "/".to_string()); loop { /* The ctrl-c handler that sets running to false is * supposed to be caught by the loop in run_inner in the * VM and set to true again, but that doesn't always * happen, so set it to true here just in case. */ vm.running.clone().store(true, Ordering::SeqCst); let cwd_res = env::current_dir(); let cwd_str = match cwd_res { Ok(cwd) => { // Update the last known directory when successful let cwd_str = cwd.as_path().to_str().unwrap_or("/").to_string(); last_known_cwd = cwd_str.clone(); cwd_str } Err(_) => { // If current directory is not available (e.g., removed), // continue using the last known directory for the prompt last_known_cwd.clone() } }; let prompt = format!("{}$ ", cwd_str); let readline_res = rl_rr.borrow_mut().readline(&prompt); match readline_res { Ok(mut line) => { let original_line = line.clone(); if line.is_empty() { continue; } let starts_with_space = line.starts_with(' '); if starts_with_space { line = "$".to_owned() + &line; } if line.ends_with("; sudo") || line.ends_with("; sudo;") { let sudo_re = Regex::new(r" sudo;?$").unwrap(); line = sudo_re.replace(&line, "").to_string(); line = format!("$ sudo {} -e '{}'", program, line); } let timing = if line.ends_with("; time") || line.ends_with("; time;") { let time_re = Regex::new(r" time;?$").unwrap(); line = time_re.replace(&line, "").to_string(); Some((ProcessTime::try_now().unwrap(), SystemTime::now())) } else { None }; line = line.trim().to_string(); let mut bufread: Box<dyn BufRead> = Box::new(Cursor::new(line.into_bytes())); rl_rr.borrow_mut().add_history_entry(original_line.as_str()); let chunk_opt = vm.interpret_with_mode(&mut bufread, "(main)", true); match chunk_opt { Some(chunk) => { for (k, v) in chunk.borrow().functions.iter() { if !k.starts_with("anon") { global_functions.borrow_mut().insert(k.clone(), v.clone()); } } } None => {} } if starts_with_space && !vm.stack.is_empty() { vm.stack.pop().unwrap(); } match timing { Some((ct, rt_start)) => { let ct_dur = ct.try_elapsed().unwrap(); let rt_end = SystemTime::now(); let rt_start_dur = rt_start.duration_since(UNIX_EPOCH).unwrap(); let rt_end_dur = rt_end.duration_since(UNIX_EPOCH).unwrap(); let rt_dur = rt_end_dur - rt_start_dur; let rt_min = rt_dur.as_secs() / 60; let rt_sec = rt_dur.as_secs() % 60; let rt_ms = rt_dur.subsec_millis(); let ct_min = ct_dur.as_secs() / 60; let ct_sec = ct_dur.as_secs() % 60; let ct_ms = ct_dur.subsec_millis(); eprintln!(""); eprintln!("real {}m{}.{:03}s", rt_min, rt_sec, rt_ms); eprintln!("cpu {}m{}.{:03}s", ct_min, ct_sec, ct_ms); } _ => {} } } Err(ReadlineError::Interrupted) => {} Err(ReadlineError::Eof) => break, Err(err) => { println!("Error: {:?}", err); break; } } } if let Some(history_path) = history_path_opt.clone() { let history_end_len = rl_rr.borrow().history().len(); let mut history_file = OpenOptions::new() .write(true) .create(true) .append(true) .open(&history_path) .unwrap(); Flock::lock(history_file.try_clone().unwrap(), FlockArg::LockExclusive).unwrap(); for i in history_start_len..history_end_len { writeln!(history_file, "{}", rl_rr.borrow().history().get(i).unwrap()).unwrap(); } } } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_json.rs
src/vm/vm_json.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::convert::TryFrom; use std::rc::Rc; use indexmap::IndexMap; use num_bigint::ToBigInt; use crate::chunk::Value; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; /// Converts a serde_json object into a value. fn convert_from_json(v: &serde_json::value::Value) -> Value { match v { serde_json::value::Value::Null => Value::Null, serde_json::value::Value::Bool(true) => Value::Bool(true), serde_json::value::Value::Bool(false) => Value::Bool(false), serde_json::value::Value::Number(n) => { if n.is_i64() { let n_uw = n.as_i64().unwrap(); let n2_res = i32::try_from(n_uw); match n2_res { Ok(n2) => Value::Int(n2), _ => Value::BigInt(n_uw.to_bigint().unwrap()), } } else if n.is_u64() { let n_uw = n.as_u64().unwrap(); let n2_res = i32::try_from(n_uw); match n2_res { Ok(n2) => Value::Int(n2), _ => Value::BigInt(n_uw.to_bigint().unwrap()), } } else { Value::Float(n.as_f64().unwrap()) } } serde_json::value::Value::String(s) => new_string_value(s.to_string()), serde_json::value::Value::Array(lst) => Value::List(Rc::new(RefCell::new( lst.iter().map(convert_from_json).collect::<VecDeque<_>>(), ))), serde_json::value::Value::Object(map) => { let mut result = new_hash_indexmap(); for (k, v) in map.iter() { result.insert(k.to_string(), convert_from_json(v)); } Value::Hash(Rc::new(RefCell::new(result))) }, } } /// Convert a value into a JSON string. fn convert_to_json(v: &Value) -> String { match v { Value::Null => "null".to_string(), Value::Bool(true) => "true".to_string(), Value::Bool(false) => "false".to_string(), Value::Byte(n) => n.to_string(), Value::Int(n) => n.to_string(), Value::Float(f) => f.to_string(), Value::String(st) => { format!("\"{}\"", &st.borrow().string) } Value::List(lst) => { let s = lst .borrow() .iter() .map(convert_to_json) .collect::<Vec<_>>() .join(","); format!("[{}]", s) } Value::Hash(vm) => { let s = vm .borrow() .iter() .map(|(k, v_rr)| format!("\"{}\":{}", k, convert_to_json(v_rr))) .collect::<Vec<_>>() .join(","); format!("{{{}}}", s) } _ => { let s_opt = v.to_string(); match s_opt { Some(s) => { format!("\"{}\"", s) } None => { let type_str = v.type_string(); let s = format!("\"v[{}]\"", type_str); s } } } } } impl VM { /// Takes a JSON string, converts it into a hash, and puts the /// result onto the stack. pub fn core_from_json(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("from-json requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); if !value_rr.is_generator() { let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let doc_res = serde_json::from_str(s); let doc; match doc_res { Err(e) => { let err_str = format!("from-json argument is not valid JSON: {}", e); self.print_error(&err_str); return 0; } Ok(d) => { doc = d; } } let json_rr = convert_from_json(&doc); self.stack.push(json_rr); 1 } _ => { self.print_error("from-json argument must be string or generator"); 0 } } } else { self.stack.push(value_rr); self.stack.push(new_string_value("".to_string())); let function_rr = self.string_to_callable("join").unwrap(); let res = self.call(OpCode::Call, function_rr); if !res { return 0; } self.core_from_json() } } /// Takes a hash, converts it into a JSON string representation, /// and puts the result onto the stack. pub fn core_to_json(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("to-json requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); self.stack.push(new_string_value(convert_to_json(&value_rr))); 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_command.rs
src/vm/vm_command.rs
use std::cell::RefCell; use std::collections::HashSet; use std::collections::VecDeque; use std::env; use std::fs::File; use std::io::Write; use std::os::fd::FromRawFd; use std::rc::Rc; use std::str; use lazy_static::lazy_static; use nix::unistd::{fork, ForkResult}; use nonblock::NonBlockingReader; use regex::Regex; use std::process::{Command, Stdio}; use crate::chunk::{CommandGenerator, Value}; use crate::vm::*; lazy_static! { static ref START_DOUBLE_QUOTE: Regex = Regex ::new(r#"^\s*""#).unwrap(); static ref END_DOUBLE_QUOTE: Regex = Regex ::new(r#""\s*$"#).unwrap(); static ref START_SINGLE_QUOTE: Regex = Regex ::new(r#"^\s*'"#).unwrap(); static ref END_SINGLE_QUOTE: Regex = Regex ::new(r#"'\s*$"#).unwrap(); static ref END_SLASH_EXTRA: Regex = Regex ::new(r#".*\\$"#).unwrap(); static ref END_SLASH: Regex = Regex ::new(r#"\\$"#).unwrap(); static ref CAPTURE_NUM: Regex = Regex ::new("\\{(\\d+)\\}").unwrap(); static ref CAPTURE_WITHOUT_NUM: Regex = Regex ::new("\\{\\}").unwrap(); static ref HOME_DIR_TILDE: Regex = Regex ::new("\\s~").unwrap(); static ref LEADING_WS: Regex = Regex ::new("^\\s*").unwrap(); static ref ENV_VAR: Regex = Regex ::new("^(.*)=(.*)$").unwrap(); static ref STDOUT_REDIRECT: Regex = Regex ::new("^1?>(.*)$").unwrap(); static ref STDERR_REDIRECT: Regex = Regex ::new("^2>(.*)$").unwrap(); static ref STDOUT_APPEND_REDIRECT: Regex = Regex ::new("^1?>>(.*)$").unwrap(); static ref STDERR_APPEND_REDIRECT: Regex = Regex ::new("^2>>(.*)$").unwrap(); } /// Splits a string on whitespace, taking into account quoted values /// (for both single-quotes and double-quotes). fn split_command(s: &str) -> Option<VecDeque<String>> { let elements = s.split_whitespace(); let mut final_elements = Vec::new(); let mut buffer = Vec::new(); let mut delimiter = '"'; let mut add_to_next_opt: Option<String> = None; for e in elements { let mut e_str = e.to_string(); match add_to_next_opt { Some(add_to_next) => { e_str = add_to_next + &e_str; add_to_next_opt = None; } _ => { if e_str == ">" || e_str == "2>" || e_str == "1>" || e_str == ">>" || e_str == "2>>" || e_str == "1>>" { add_to_next_opt = Some(e_str); continue; } } } if !buffer.is_empty() { if !e_str.is_empty() { if e_str.chars().last().unwrap() == delimiter { buffer.push(e_str); let new_str = buffer.join(" "); if delimiter == '"' { let new_str2 = START_DOUBLE_QUOTE.replace(&new_str, ""); let new_str3 = END_DOUBLE_QUOTE.replace(&new_str2, ""); final_elements.push(new_str3.to_string()); } else { let new_str2 = START_SINGLE_QUOTE.replace(&new_str, ""); let new_str3 = END_SINGLE_QUOTE.replace(&new_str2, ""); final_elements.push(new_str3.to_string()); } buffer.clear(); } else { buffer.push(e_str); } } } else if START_DOUBLE_QUOTE.is_match(&e_str) && !END_DOUBLE_QUOTE.is_match(&e_str) { buffer.push(e_str); delimiter = '"'; } else if START_SINGLE_QUOTE.is_match(&e_str) && !END_SINGLE_QUOTE.is_match(&e_str) { buffer.push(e_str); delimiter = '\''; } else { /* If this element is a single string, then replace any * quotation marks that are present. */ let new_str2 = START_DOUBLE_QUOTE.replace(&e_str, ""); let new_str3 = END_DOUBLE_QUOTE.replace(&new_str2, ""); let new_str4 = START_SINGLE_QUOTE.replace(&new_str3, ""); let new_str5 = END_SINGLE_QUOTE.replace(&new_str4, ""); final_elements.push(new_str5.to_string()); } } if !buffer.is_empty() { return None; } let mut lst = VecDeque::new(); for e in final_elements.iter() { if lst.is_empty() { lst.push_back(e.to_string()); } else { let back = lst.back().unwrap(); if END_SLASH_EXTRA.is_match(back) { let back = lst.pop_back().unwrap(); let back2 = END_SLASH.replace_all(&back, ""); let back3 = format!("{} {}", back2, e); lst.push_back(back3); } else { lst.push_back(e.to_string()); } } } Some(lst) } fn restore_env(env: HashMap<String, String>, del_env: HashSet<String>) { for (key, value) in env { env::set_var(key, value); } for key in del_env { env::remove_var(key); } } impl VM { /// Takes a command string, substitutes for the {num} and {} /// stack element placeholders as well as the ~ home directory /// placeholder, and returns the resulting string. fn prepare_command(&mut self, s: &str) -> Option<String> { let st = StringTriple::new(s.to_string(), None); self.stack.push(Value::String(Rc::new(RefCell::new(st)))); let res = self.core_fmtq(); if res == 0 { return None; } let str_rr = self.stack.pop().unwrap(); match str_rr { Value::String(st) => { let input_s = &(st.borrow().string); let final_s: String; let homedir_res = std::env::var("HOME"); match homedir_res { Ok(homedir) => { let s = " ".to_owned() + &homedir; final_s = HOME_DIR_TILDE.replace_all(input_s, &*s).to_string(); } _ => { final_s = input_s.to_string(); } } Some(final_s) } _ => { eprintln!("expected string!"); std::process::abort(); } } } fn prepare_and_split_command( &mut self, cmd: &str, accept_redirects: bool ) -> Option<(String, Vec<String>, HashMap<String, String>, HashSet<String>, Option<(String, bool)>, Option<(String, bool)>)> { let prepared_cmd_opt = self.prepare_command(cmd); if prepared_cmd_opt.is_none() { return None; } let prepared_cmd = prepared_cmd_opt.unwrap(); let elements_opt = split_command(&prepared_cmd); if elements_opt.is_none() { self.print_error("syntax error in command"); return None; } let mut elements = elements_opt.unwrap(); if elements.is_empty() { self.print_error("unable to execute empty command"); return None; } let mut prev_env = HashMap::new(); let mut del_env = HashSet::new(); while !elements.is_empty() { let element = elements.get(0).unwrap(); let captures = ENV_VAR.captures_iter(element); let mut has = false; for capture in captures { has = true; let key_str = capture.get(1).unwrap().as_str(); let value_str = capture.get(2).unwrap().as_str(); let current_str = env::var(key_str); match current_str { Ok(s) => { prev_env.insert(key_str.to_string(), s); } _ => { del_env.insert(key_str.to_string()); } } env::set_var(key_str, value_str); } if has { elements.pop_front(); } else { break; } } let mut stdout_redirect = None; let mut stderr_redirect = None; if accept_redirects { while !elements.is_empty() { let len = elements.len(); let element = elements.get(len - 1).unwrap(); let mut captures = STDOUT_APPEND_REDIRECT.captures_iter(element); match captures.next() { Some(capture) => { let output = capture.get(1).unwrap().as_str(); stdout_redirect = Some((output.to_string(), true)); elements.pop_back(); continue; } _ => {} } captures = STDERR_APPEND_REDIRECT.captures_iter(element); match captures.next() { Some(capture) => { let output = capture.get(1).unwrap().as_str(); stderr_redirect = Some((output.to_string(), true)); elements.pop_back(); continue; } _ => {} } captures = STDOUT_REDIRECT.captures_iter(element); match captures.next() { Some(capture) => { let output = capture.get(1).unwrap().as_str(); stdout_redirect = Some((output.to_string(), false)); elements.pop_back(); continue; } _ => {} } captures = STDERR_REDIRECT.captures_iter(element); match captures.next() { Some(capture) => { let output = capture.get(1).unwrap().as_str(); stderr_redirect = Some((output.to_string(), false)); elements.pop_back(); continue; } _ => {} } break; } } let mut element_iter = elements.iter(); let executable_opt = element_iter.next(); if executable_opt.is_none() { self.print_error("unable to execute empty command"); return None; } let executable = executable_opt.unwrap(); let executable_final = LEADING_WS.replace_all(executable, "").to_string(); let args = element_iter.map(|v| v.to_string()).collect::<Vec<_>>(); Some((executable_final, args, prev_env, del_env, stdout_redirect, stderr_redirect)) } /// Takes a command string and a set of parameters as its /// arguments. Substitutes for placeholders, executes the /// command, and places a generator over the standard output/error /// (depends on parameters) of the command onto the stack. pub fn core_command(&mut self, cmd: &str, params: HashSet<char>) -> i32 { let prepared_cmd_opt = self.prepare_and_split_command(cmd, false); if prepared_cmd_opt.is_none() { return 0; } let (executable, args, env, del_env, _, _) = prepared_cmd_opt.unwrap(); let process_res = Command::new(executable) .args(args) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn(); restore_env(env, del_env); match process_res { Ok(mut process) => { self.child_processes.insert(process.id(), cmd.to_string()); let upstream_stdout = process.stdout.take().unwrap(); let upstream_stderr = process.stderr.take().unwrap(); let noblock_stdout = NonBlockingReader::from_fd(upstream_stdout).unwrap(); let noblock_stderr = NonBlockingReader::from_fd(upstream_stderr).unwrap(); let mut get_stdout = params.contains(&'o'); let get_stderr = params.contains(&'e'); let get_combined = params.contains(&'c'); if !get_stdout && !get_stderr && !get_combined { get_stdout = true; } let get_bytes = params.contains(&'b'); let cmd_generator = Value::CommandGenerator(Rc::new(RefCell::new(CommandGenerator::new( Some(nix::unistd::Pid::from_raw(process.id() as i32)), None, None, noblock_stdout, noblock_stderr, get_stdout, get_stderr, get_combined, get_bytes, )))); self.stack.push(cmd_generator); } Err(e) => { let err_str = format!("unable to run command: {}", e); self.print_error(&err_str); return 0; } } 1 } /// As per `core_command`, except that the output isn't captured /// and nothing is placed onto the stack. pub fn core_command_uncaptured(&mut self, cmd: &str) -> i32 { let separator = Regex::new(r"\s+&&\s+").unwrap(); let cmds: Vec<_> = separator.split(cmd).into_iter().collect(); let mut last_status = 0; for cmd in cmds { let prepared_cmd_opt = self.prepare_and_split_command(cmd, true); if prepared_cmd_opt.is_none() { return 0; } let (executable, args, env, del_env, stdout_redirect_opt, stderr_redirect_opt) = prepared_cmd_opt.unwrap(); let mut process_cmd = Command::new(executable); let mut process_im = process_cmd.args(args); let mut stdout_file_opt = None; let mut stdout_to_stderr = false; if let Some((stdout_redirect, is_append)) = stdout_redirect_opt { if stdout_redirect == "&2" { stdout_to_stderr = true; } else { let stdout_file_res = if is_append { File::options().create(true).append(true).open(stdout_redirect) } else { File::create(stdout_redirect) }; match stdout_file_res { Ok(stdout_file_arg) => { stdout_file_opt = Some(stdout_file_arg.try_clone().unwrap()); process_im = process_im.stdout(stdout_file_arg); } Err(e) => { let err_str = format!("unable to open stdout redirect file: {}", e); self.print_error(&err_str); return 0; } } } } let mut stderr_file_opt = None; let mut stderr_to_stdout = false; if let Some((stderr_redirect, is_append)) = stderr_redirect_opt { if stderr_redirect == "&1" { stderr_to_stdout = true; } else { let stderr_file_res = if is_append { File::options().create(true).append(true).open(stderr_redirect) } else { File::create(stderr_redirect) }; match stderr_file_res { Ok(stderr_file_arg) => { stderr_file_opt = Some(stderr_file_arg.try_clone().unwrap()); process_im = process_im.stderr(stderr_file_arg); } Err(e) => { let err_str = format!("unable to open stderr redirect file: {}", e); self.print_error(&err_str); return 0; } } } } if stdout_to_stderr { match stderr_file_opt { Some(stderr_file) => { process_im = process_im.stdout(stderr_file.try_clone().unwrap()); } _ => { unsafe { process_im = process_im.stdout(Stdio::from_raw_fd(2)); } } } } if stderr_to_stdout { match stdout_file_opt { Some(stdout_file) => { process_im = process_im.stderr(stdout_file.try_clone().unwrap()); } _ => { unsafe { process_im = process_im.stderr(Stdio::from_raw_fd(1)); } } } } let process_res = process_im.spawn(); restore_env(env, del_env); match process_res { Ok(mut process) => { let res = process.wait(); match res { Ok(es) => { let code = es.code(); match code { Some(n) => { last_status = n; if last_status != 0 { break; } } _ => { let err_str = format!("command execution failed"); self.print_error(&err_str); return 0; } } } Err(e) => { let err_str = format!("command execution failed: {}", e); self.print_error(&err_str); return 0; } } } Err(e) => { let err_str = format!("unable to execute command: {}", e); self.print_error(&err_str); return 0; } } } self.stack.push(Value::Int(last_status)); 1 } /// Takes a generator and a command as its arguments. Takes /// output from the generator and pipes it to the standard input /// of the command, and places a generator over the command's /// standard output onto the stack. pub fn core_pipe(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("| requires two arguments"); return 0; } let cmd_rr = self.stack.pop().unwrap(); match cmd_rr { Value::Command(s, _) => { let prepared_cmd_opt = self.prepare_and_split_command(&s, false); if prepared_cmd_opt.is_none() { return 0; } let (executable, args, env, del_env, _, _) = prepared_cmd_opt.unwrap(); let process_ = Command::new(executable) .args(args) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .stdin(Stdio::piped()) .spawn(); restore_env(env, del_env); match process_ { Ok(mut process) => { self.child_processes.insert(process.id(), s.to_string()); let pipe_pid = process.id(); let upstream_stdin_opt = process.stdin; if upstream_stdin_opt.is_none() { let err_str = "unable to get stdin from parent".to_string(); self.print_error(&err_str); return 0; } let mut upstream_stdin = upstream_stdin_opt.unwrap(); unsafe { match fork() { Ok(ForkResult::Parent { child }) => { let input_value = self.stack.pop().unwrap(); let upstream_stdout_opt = process.stdout.take(); if upstream_stdout_opt.is_none() { let err_str = "unable to get stdout from parent".to_string(); self.print_error(&err_str); return 0; } let upstream_stdout = upstream_stdout_opt.unwrap(); let upstream_stderr_opt = process.stderr.take(); if upstream_stderr_opt.is_none() { let err_str = "unable to get stderr from parent".to_string(); self.print_error(&err_str); return 0; } let upstream_stderr = upstream_stderr_opt.unwrap(); let cmd_generator = Value::CommandGenerator(Rc::new(RefCell::new( CommandGenerator::new( Some(child), Some(nix::unistd::Pid::from_raw(pipe_pid as i32)), Some(input_value), NonBlockingReader::from_fd(upstream_stdout).unwrap(), NonBlockingReader::from_fd(upstream_stderr).unwrap(), true, false, false, false, ), ))); self.stack.push(cmd_generator); } Ok(ForkResult::Child) => { loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return 0; } let shift_res = self.opcode_shift(); if shift_res == 0 { return 0; } let element_rr = self.stack.pop().unwrap(); if let Value::Null = element_rr { break; } let element_str_opt: Option<&str>; to_str!(element_rr, element_str_opt); match element_str_opt { Some(s) => { let res = upstream_stdin.write(s.as_bytes()); match res { Ok(_) => {} _ => { eprintln!("unable to write to parent process!"); std::process::abort(); } } } _ => { break; } } } std::process::exit(0); } _ => { eprintln!("unexpected fork result!"); std::process::abort(); } } } } Err(e) => { let err_str = format!("unable to run command: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("| argument must be a command"); } } 1 } /// Takes a command generator as its single argument, and returns /// the exit status, terminating the process if required. pub fn core_status(&mut self) -> i32 { if self.stack.len() < 1 { self.print_error("status requires one argument"); return 0; } let mut cg_rr = self.stack.pop().unwrap(); match cg_rr { Value::CommandGenerator(ref mut cg) => { cg.borrow_mut().cleanup(); self.stack.push(cg.borrow().status()); return 1; } _ => { self.print_error("status argument must be command generator"); return 0; } } } /// Takes a string as its single argument, and runs the string as /// a command (uncaptured). pub fn core_exec(&mut self) -> i32 { if self.stack.len() < 1 { self.print_error("exec requires one argument"); return 0; } let cmd_rr = self.stack.pop().unwrap(); let cmd_str_opt: Option<&str>; to_str!(cmd_rr, cmd_str_opt); match cmd_str_opt { None => { self.print_error("exec argument must be a string"); return 0; } Some(s) => { let i = self.core_command_uncaptured(&s); if i == 0 { return 0; } } } return 1; } /// Takes a string and a set of parameters as its arguments, and /// runs the string as a command (captured). pub fn core_cmd_internal(&mut self, params: HashSet<char>) -> i32 { if self.stack.len() < 1 { self.print_error("cmd requires one argument"); return 0; } let cmd_rr = self.stack.pop().unwrap(); let cmd_str_opt: Option<&str>; to_str!(cmd_rr, cmd_str_opt); match cmd_str_opt { None => { self.print_error("exec argument must be a string"); return 0; } Some(s) => { return self.core_command(&s, params); } } } pub fn core_cmd(&mut self) -> i32 { let params: HashSet<char> = HashSet::new(); return self.core_cmd_internal(params); } pub fn core_cmde(&mut self) -> i32 { let mut params: HashSet<char> = HashSet::new(); params.insert('e'); return self.core_cmd_internal(params); } pub fn core_cmdo(&mut self) -> i32 { let mut params: HashSet<char> = HashSet::new(); params.insert('o'); return self.core_cmd_internal(params); } pub fn core_cmdeo(&mut self) -> i32 { let mut params: HashSet<char> = HashSet::new(); params.insert('e'); params.insert('o'); return self.core_cmd_internal(params); } pub fn core_cmdc(&mut self) -> i32 { let mut params: HashSet<char> = HashSet::new(); params.insert('c'); return self.core_cmd_internal(params); } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_ip.rs
src/vm/vm_ip.rs
use std::net::{Ipv4Addr, Ipv6Addr}; use ipnet::{Ipv4Net, Ipv6Net}; use iprange::IpRange; use num_bigint::{BigInt, BigUint}; use num_traits::{FromPrimitive, ToPrimitive, Zero}; use crate::chunk::{IpSet, Ipv4Range, Ipv6Range}; use crate::vm::*; /// Convert an IPv4 address to a u32. fn ipv4_addr_to_int(ipv4: Ipv4Addr) -> u32 { let octets = ipv4.octets(); let mut n: u32 = 0; for (i, item) in octets.iter().enumerate() { let next = item.to_u32().unwrap() << (32 - ((i + 1) * 8)); n |= next; } n } /// Convert an IPv4 address to a BigUint. fn ipv6_addr_to_int(ipv6: Ipv6Addr) -> BigUint { let octets = ipv6.octets(); let mut n = BigUint::zero(); for (i, item) in octets.iter().enumerate() { let next = BigUint::from(*item) << (128 - ((i + 1) * 8)); n |= next; } n } /// Convert a u32 to an IPv4 address. fn int_to_ipv4_addr(n: u32) -> Ipv4Addr { let o1 = (n >> 24 & 0xFF).to_u8().unwrap(); let o2 = (n >> 16 & 0xFF).to_u8().unwrap(); let o3 = (n >> 8 & 0xFF).to_u8().unwrap(); let o4 = (n & 0xFF).to_u8().unwrap(); Ipv4Addr::new(o1, o2, o3, o4) } /// Convert a BigUint to an IPv6 address. fn int_to_ipv6_addr(n: BigUint) -> Ipv6Addr { let mask = BigUint::from_u32(0xFFFF).unwrap(); let o1 = (n.clone() >> 112u16 & mask.clone()).to_u16().unwrap(); let o2 = (n.clone() >> 96u16 & mask.clone()).to_u16().unwrap(); let o3 = (n.clone() >> 80u16 & mask.clone()).to_u16().unwrap(); let o4 = (n.clone() >> 64u16 & mask.clone()).to_u16().unwrap(); let o5 = (n.clone() >> 48u16 & mask.clone()).to_u16().unwrap(); let o6 = (n.clone() >> 32u16 & mask.clone()).to_u16().unwrap(); let o7 = (n.clone() >> 16u16 & mask.clone()).to_u16().unwrap(); let o8 = (n & mask).to_u16().unwrap(); Ipv6Addr::new(o1, o2, o3, o4, o5, o6, o7, o8) } /// Convert an IPv4 range (arbitrary start-end pair) into a list of /// IPv4Net objects (prefixes). fn ipv4range_to_nets(ipv4range: Ipv4Range) -> VecDeque<Ipv4Net> { let mut lst = VecDeque::new(); let s = ipv4range.s; let e = ipv4range.e; let mut s_num = ipv4_addr_to_int(s); let e_num = ipv4_addr_to_int(e); if (s_num == 0) && (e_num == !0) { lst.push_back(Ipv4Net::from_str("0.0.0.0/0").unwrap()); } else { while s_num <= e_num { let mut host_count = if s_num == 0 { (!0 >> 1) + 1 } else { s_num & !(s_num - 1) }; while s_num + (host_count - 1) > e_num { host_count /= 2; } let fst = int_to_ipv4_addr(s_num); let mut len = 32; let prev_host_count = host_count; while (host_count & 1) != 1 { host_count >>= 1; len -= 1; } let pfx = format!("{}/{}", fst, len); lst.push_back(Ipv4Net::from_str(&pfx).unwrap()); if s_num.checked_add(prev_host_count).is_none() { break; } else { s_num += prev_host_count; } } } lst } /// Convert an IPv6 range (arbitrary start-end pair) into a list of /// IPv6Net objects (prefixes). fn ipv6range_to_nets(ipv6range: Ipv6Range) -> VecDeque<Ipv6Net> { let mut lst = VecDeque::new(); let s = ipv6range.s; let e = ipv6range.e; let mut s_num = ipv6_addr_to_int(s); let e_num = ipv6_addr_to_int(e); let zero = BigUint::from(0u8); let one = BigUint::from(1u8); let mut max: BigUint = BigUint::from(1u8) << 128; max -= 1u8; while s_num <= e_num { let mut host_count = if s_num == zero { (max.clone() >> 1) + one.clone() } else { let n = s_num.clone() - one.clone(); let n_negated = n ^ max.clone(); s_num.clone() & n_negated }; while s_num.clone() + host_count.clone() - one.clone() > e_num { host_count = host_count.clone() / 2u8; } let fst = int_to_ipv6_addr(s_num.clone()); s_num = s_num.clone() + host_count.clone(); let mut len = 128; while (host_count.clone() & one.clone()) != one { host_count = host_count.clone() >> 1u8; len -= 1; } let pfx = format!("{}/{}", fst, len); lst.push_back(Ipv6Net::from_str(&pfx).unwrap()); } lst } impl VM { /// Parses an IP address or range and returns an IP object. pub fn core_ip(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { if s.contains('.') { if s.contains('-') { let mut iter = s.split('-'); let fst = iter.next(); if fst.is_none() { self.print_error("ip argument must be valid IP address string"); return 0; } let snd = iter.next(); if snd.is_none() { self.print_error("ip argument must be valid IP address string"); return 0; } if iter.next().is_some() { self.print_error("ip argument must be valid IP address string"); return 0; } let fst_str = fst.unwrap().trim(); let snd_str = snd.unwrap().trim(); let fst_str_wp = format!("{}/32", fst_str); let snd_str_wp = format!("{}/32", snd_str); let ipv4_fst = Ipv4Net::from_str(&fst_str_wp); let ipv4_snd = Ipv4Net::from_str(&snd_str_wp); match (ipv4_fst, ipv4_snd) { (Ok(ipv4_fst_obj), Ok(ipv4_snd_obj)) => { if ipv4_fst_obj == ipv4_snd_obj { self.stack.push(Value::Ipv4(ipv4_fst_obj)); return 1; } else if ipv4_fst_obj > ipv4_snd_obj { self.print_error("ip argument must be valid IP address string"); return 0; } else { self.stack.push(Value::Ipv4Range(Ipv4Range::new( ipv4_fst_obj.network(), ipv4_snd_obj.network(), ))); return 1; } } (_, _) => { self.print_error("ip argument must be valid IP address string"); 0 } } } else { let ipv4_res; if !s.contains('/') { let s2 = format!("{}/32", s); ipv4_res = Ipv4Net::from_str(&s2); } else { ipv4_res = Ipv4Net::from_str(s); } match ipv4_res { Ok(ipv4) => { let addr = ipv4.addr(); let addr_int = ipv4_addr_to_int(addr); let prefix_len = ipv4.prefix_len(); if prefix_len == 0 && addr_int != 0 { self.print_error("ip argument must be valid IP address string"); return 0; } if !(prefix_len == 0 && addr_int == 0) { let addr_check = addr_int & ((1 << (32 - prefix_len)) - 1); if addr_check != 0 { self.print_error( "ip argument must be valid IP address string", ); return 0; } } self.stack.push(Value::Ipv4(ipv4)); 1 } Err(e) => { let err_str = format!("ip argument must be valid IP address string: {}", e); self.print_error(&err_str); 0 } } } } else if s.contains('-') { let mut iter = s.split('-'); let fst = iter.next(); if fst.is_none() { self.print_error("ip argument must be valid IP address string"); return 0; } let snd = iter.next(); if snd.is_none() { self.print_error("ip argument must be valid IP address string"); return 0; } if iter.next().is_some() { self.print_error("ip argument must be valid IP address string"); return 0; } let fst_str = fst.unwrap().trim(); let snd_str = snd.unwrap().trim(); let fst_str_wp = format!("{}/128", fst_str); let snd_str_wp = format!("{}/128", snd_str); let ipv6_fst = Ipv6Net::from_str(&fst_str_wp); let ipv6_snd = Ipv6Net::from_str(&snd_str_wp); match (ipv6_fst, ipv6_snd) { (Ok(ipv6_fst_obj), Ok(ipv6_snd_obj)) => { if ipv6_fst_obj == ipv6_snd_obj { self.stack.push(Value::Ipv6(ipv6_fst_obj)); return 1; } else if ipv6_fst_obj > ipv6_snd_obj { self.print_error("ip argument must be valid IP address string"); return 0; } else { self.stack.push(Value::Ipv6Range(Ipv6Range::new( ipv6_fst_obj.network(), ipv6_snd_obj.network(), ))); return 1; } } (_, _) => { self.print_error("ip argument must be valid IP address string"); 0 } } } else { let ipv6_res; if !s.contains('/') { let s2 = format!("{}/128", s); ipv6_res = Ipv6Net::from_str(&s2); } else { ipv6_res = Ipv6Net::from_str(s); } match ipv6_res { Ok(ipv6) => { let addr = ipv6.addr(); let addr_int = ipv6_addr_to_int(addr); let prefix_len = ipv6.prefix_len(); if prefix_len == 0 && !addr_int.is_zero() { self.print_error("ip argument must be valid IP address string"); return 0; } if !(prefix_len == 0 && addr_int == BigUint::from(0u8)) { let prefix_mask = (BigUint::from(1u8) << (128 - prefix_len)) - BigUint::from(1u8); let addr_check: BigUint = addr_int & prefix_mask; if !addr_check.is_zero() { self.print_error("ip argument must be valid IP address string"); return 0; } } self.stack.push(Value::Ipv6(ipv6)); 1 } Err(e) => { let err_str = format!("ip argument must be valid IP address string: {}", e); self.print_error(&err_str); 0 } } } } _ => { self.print_error("ip argument must be valid IP address string"); 0 } } } /// Converts an integer into an IP object. pub fn core_ip_from_int(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("ip.from-int requires two arguments"); return 0; } let version_rr = self.stack.pop().unwrap(); let version_opt = version_rr.to_int(); let value_rr = self.stack.pop().unwrap(); let value_opt = value_rr.to_bigint(); match (version_opt, value_opt) { (Some(4), Some(value)) => { if value > BigInt::from_u32(0xFFFFFFFF).unwrap() { self.print_error("first ip.from-int argument must be u32 integer"); return 0; } let uvalue = value.to_biguint().unwrap().to_u32().unwrap(); let ipv4 = int_to_ipv4_addr(uvalue); self.stack .push(Value::Ipv4(Ipv4Net::new(ipv4, 32).unwrap())); } (Some(6), Some(value)) => { let uvalue = value.to_biguint().unwrap(); let ipv6 = int_to_ipv6_addr(uvalue); self.stack .push(Value::Ipv6(Ipv6Net::new(ipv6, 128).unwrap())); } (Some(_), _) => { self.print_error("second ip.from-int argument must be IP address version"); return 0; } _ => { self.print_error("first ip.from-int argument must be integer"); return 0; } } 1 } /// Returns the first address of an IP object. pub fn core_ip_addr(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.addr requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); let ip_str; match ip_rr { Value::Ipv4(ipv4net) => { ip_str = format!("{}", ipv4net); } Value::Ipv4Range(ipv4range) => { ip_str = format!("{}", ipv4range.s); } Value::Ipv6(ipv6net) => { ip_str = format!("{}", ipv6net); } Value::Ipv6Range(ipv6range) => { ip_str = format!("{}", ipv6range.s); } _ => { self.print_error("ip.addr argument must be ip object"); return 0; } } let ip_str_no_len = ip_str.chars().take_while(|&c| c != '/').collect::<String>(); let st = new_string_value(ip_str_no_len); self.stack.push(st); 1 } /// Returns the prefix length of an IP object. pub fn core_ip_len(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.len requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(ipv4net) => { let len = Value::Int(ipv4net.prefix_len().into()); self.stack.push(len); 1 } Value::Ipv4Range(ipv4range) => { let s = ipv4range.s; let e = ipv4range.e; let s_num = ipv4_addr_to_int(s); let e_num = ipv4_addr_to_int(e); if s_num == 0 && e_num == 0xFFFFFFFF { self.stack.push(Value::Int(0)); return 1; } let mut host_count = e_num - s_num + 1; let mut len = 32; if host_count & (host_count - 1) == 0 { loop { if host_count == 1 { break; } else { host_count >>= 1; len -= 1; } } self.stack.push(Value::Int(len)); 1 } else { self.print_error("ip.len argument has no length"); 0 } } Value::Ipv6(ipv6net) => { let len = Value::Int(ipv6net.prefix_len().into()); self.stack.push(len); 1 } Value::Ipv6Range(ipv6range) => { let s = ipv6range.s; let e = ipv6range.e; let s_num = ipv6_addr_to_int(s); let e_num = ipv6_addr_to_int(e); let zero = BigUint::zero(); let one = BigUint::from(1u8); let mut host_count = e_num - s_num + one.clone(); let mut len = 128; if host_count.clone() & (host_count.clone() - one.clone()) == zero { loop { if host_count == one { break; } else { host_count >>= 1; len -= 1; } } self.stack.push(Value::Int(len)); 1 } else { self.print_error("ip.len argument has no length"); 0 } } _ => { self.print_error("ip.len argument must be ip object"); 0 } } } /// Returns the first address of the IP object as an integer. pub fn core_ip_addr_int(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.addr-int requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(ipv4net) => { let ipv4addr_int = ipv4_addr_to_int(ipv4net.network()); let ipv4addr_val = Value::BigInt(BigInt::from(ipv4addr_int)); self.stack.push(ipv4addr_val); 1 } Value::Ipv4Range(ipv4range) => { let ipv4addr_int = ipv4_addr_to_int(ipv4range.s); let ipv4addr_val = Value::BigInt(BigInt::from(ipv4addr_int)); self.stack.push(ipv4addr_val); 1 } Value::Ipv6(ipv6net) => { let ipv6addr_int = ipv6_addr_to_int(ipv6net.network()); let ipv6addr_val = Value::BigInt(BigInt::from(ipv6addr_int)); self.stack.push(ipv6addr_val); 1 } Value::Ipv6Range(ipv6range) => { let ipv6addr_int = ipv6_addr_to_int(ipv6range.s); let ipv6addr_val = Value::BigInt(BigInt::from(ipv6addr_int)); self.stack.push(ipv6addr_val); 1 } _ => { self.print_error("ip.addr-int argument must be ip object"); 0 } } } /// Returns the last address of the IP object. pub fn core_ip_last_addr(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.last-addr requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(ipv4net) => { if ipv4_addr_to_int(ipv4net.network()) == 0 && ipv4net.prefix_len() == 0 { let lastaddr = "255.255.255.255".to_string(); let st = new_string_value(lastaddr); self.stack.push(st); return 1; } let ipv4addr_int = ipv4_addr_to_int(ipv4net.network()) | ((1 << (32 - ipv4net.prefix_len())) - 1); let lastaddr_int = int_to_ipv4_addr(ipv4addr_int); let lastaddr = format!("{}", lastaddr_int); let st = new_string_value(lastaddr); self.stack.push(st); return 1; } Value::Ipv4Range(ipv4range) => { let ipv4addr_int = ipv4_addr_to_int(ipv4range.e); let lastaddr_int = int_to_ipv4_addr(ipv4addr_int); let lastaddr = format!("{}", lastaddr_int); let st = new_string_value(lastaddr); self.stack.push(st); } Value::Ipv6(ipv6net) => { let prefix_mask = (BigUint::from(1u8) << (128 - ipv6net.prefix_len())) - BigUint::from(1u8); let ipv6addr_int = ipv6_addr_to_int(ipv6net.network()) | prefix_mask; let lastaddr_int = int_to_ipv6_addr(ipv6addr_int); let lastaddr = format!("{}", lastaddr_int); let st = new_string_value(lastaddr); self.stack.push(st); } Value::Ipv6Range(ipv6range) => { let ipv6addr_int = ipv6_addr_to_int(ipv6range.e); let lastaddr_int = int_to_ipv6_addr(ipv6addr_int); let lastaddr = format!("{}", lastaddr_int); let st = new_string_value(lastaddr); self.stack.push(st); } _ => { self.print_error("ip.last-addr argument must be ip object"); return 0; } } 1 } /// Returns the last address of the IP object as an integer. pub fn core_ip_last_addr_int(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.last-addr-int requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(ipv4net) => { if ipv4_addr_to_int(ipv4net.network()) == 0 && ipv4net.prefix_len() == 0 { let lastaddr_val = Value::BigInt(BigInt::from_u32(0xFFFFFFFF).unwrap()); self.stack.push(lastaddr_val); return 1; } let ipv4addr_int = ipv4_addr_to_int(ipv4net.network()) | ((1 << (32 - ipv4net.prefix_len())) - 1); let lastaddr_val = Value::BigInt(BigInt::from_u32(ipv4addr_int).unwrap()); self.stack.push(lastaddr_val); return 1; } Value::Ipv4Range(ipv4range) => { let ipv4addr_int = ipv4_addr_to_int(ipv4range.e); let lastaddr_val = Value::BigInt(BigInt::from(ipv4addr_int)); self.stack.push(lastaddr_val); } Value::Ipv6(ipv6net) => { let prefix_mask = (BigUint::from(1u8) << (128 - ipv6net.prefix_len())) - BigUint::from(1u8); let ipv6addr_int = ipv6_addr_to_int(ipv6net.network()) | prefix_mask; let lastaddr_val = Value::BigInt(BigInt::from(ipv6addr_int)); self.stack.push(lastaddr_val); } Value::Ipv6Range(ipv6range) => { let ipv6addr_int = ipv6_addr_to_int(ipv6range.e); let lastaddr_val = Value::BigInt(BigInt::from(ipv6addr_int)); self.stack.push(lastaddr_val); } _ => { self.print_error("ip.last-addr-int argument must be ip object"); return 0; } } 1 } /// Returns the number of hosts covered by this IP object. pub fn core_ip_size(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.size requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(ipv4net) => { if ipv4_addr_to_int(ipv4net.network()) == 0 && ipv4net.prefix_len() == 0 { let size_val = Value::BigInt(BigInt::from_u32(0xFFFFFFFF).unwrap()); self.stack.push(size_val); return 1; } let ipv4addr_int = ipv4_addr_to_int(ipv4net.network()); let lastaddr_int = ipv4addr_int | ((1 << (32 - ipv4net.prefix_len())) - 1); let size = lastaddr_int - ipv4addr_int + 1; let size_val = Value::BigInt(BigInt::from_u32(size).unwrap()); self.stack.push(size_val); return 1; } Value::Ipv4Range(ipv4range) => { let s = ipv4range.s; let e = ipv4range.e; let s_num = ipv4_addr_to_int(s); let e_num = ipv4_addr_to_int(e); if s_num == 0 && e_num == 0xFFFFFFFF { self.stack.push(Value::BigInt( BigInt::from_u32(0xFFFFFFFF).unwrap() + BigInt::from(1u8), )); return 1; } let host_count = e_num - s_num + 1; self.stack .push(Value::BigInt(BigInt::from_u32(host_count).unwrap())); return 1; } Value::Ipv6(ipv6net) => { let prefix_mask = (BigUint::from(1u8) << (128 - ipv6net.prefix_len())) - BigUint::from(1u8); let ipv6addr_int = ipv6_addr_to_int(ipv6net.network()); let lastaddr_int = ipv6addr_int.clone() | prefix_mask; let size = lastaddr_int - ipv6addr_int + BigUint::from(1u8); let size_val = Value::BigInt(BigInt::from(size)); self.stack.push(size_val); } Value::Ipv6Range(ipv6range) => { let s = ipv6range.s; let e = ipv6range.e; let s_num = ipv6_addr_to_int(s); let e_num = ipv6_addr_to_int(e); let host_count = e_num - s_num + BigUint::from(1u8); self.stack.push(Value::BigInt(BigInt::from(host_count))); return 1; } _ => { self.print_error("ip.size argument must be ip object"); return 0; } } 1 } /// Returns the IP object version. pub fn core_ip_version(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.version requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); match ip_rr { Value::Ipv4(_) => { self.stack.push(Value::Int(4)); 1 } Value::Ipv4Range(_) => { self.stack.push(Value::Int(4)); 1 } Value::Ipv6(_) => { self.stack.push(Value::Int(6)); 1 } Value::Ipv6Range(_) => { self.stack.push(Value::Int(6)); 1 } _ => { self.print_error("ip.version argument must be ip object"); 0 } } } /// Returns the IP object as a set of IP prefixes. pub fn core_ip_prefixes(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ip.prefixes requires one argument"); return 0; } let ip_rr = self.stack.pop().unwrap(); let mut lst1 = VecDeque::new(); let mut lst3 = VecDeque::new(); match ip_rr { Value::Ipv4(ipv4net) => { lst1.push_back(ipv4net); } Value::Ipv4Range(ipv4range) => { let lst2 = ipv4range_to_nets(ipv4range); for el in lst2.iter() { lst1.push_back(*el); } } Value::Ipv6(ipv6net) => { lst3.push_back(ipv6net); } Value::Ipv6Range(ipv6range) => { let lst2 = ipv6range_to_nets(ipv6range); for el in lst2.iter() { lst3.push_back(*el); } } _ => { self.print_error("ip.prefixes argument must be ip object"); return 0; } } let rlst = if !lst1.is_empty() { lst1.iter().map(|e| Value::Ipv4(*e)).collect() } else { lst3.iter().map(|e| Value::Ipv6(*e)).collect() }; let vlst = Value::List(Rc::new(RefCell::new(rlst))); self.stack.push(vlst); 1 } /// Converts an arbitrary value into a list of IP net objects. pub fn value_to_nets( &mut self, value_rr: Value, ) -> Option<(VecDeque<Ipv4Net>, VecDeque<Ipv6Net>)> { let mut ipv4_nets = VecDeque::new(); let mut ipv6_nets = VecDeque::new(); if value_rr.is_generator() { self.stack.push(value_rr); loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return None; } let shift_res = self.opcode_shift(); if shift_res == 0 { return None; } let element_rr = self.stack.pop().unwrap(); match element_rr { Value::Null => { self.stack.pop(); return Some((ipv4_nets, ipv6_nets)); } _ => { let opt = self.value_to_nets(element_rr.clone()); match opt { Some((ipv4_nets2, ipv6_nets2)) => { for el2 in ipv4_nets2.iter() { ipv4_nets.push_back(*el2); } for el2 in ipv6_nets2.iter() { ipv6_nets.push_back(*el2); } } None => { return None; } } } } } } else { match value_rr { Value::List(lst) => { for el in lst.borrow().iter() { let opt = self.value_to_nets(el.clone()); match opt { Some((ipv4_nets2, ipv6_nets2)) => { for el2 in ipv4_nets2.iter() { ipv4_nets.push_back(*el2); } for el2 in ipv6_nets2.iter() { ipv6_nets.push_back(*el2); } } None => { return None; } } } } Value::Ipv4(ipv4net) => { ipv4_nets.push_back(ipv4net); } Value::Ipv6(ipv6net) => { ipv6_nets.push_back(ipv6net); } Value::Ipv4Range(ipv4range) => { let lst_ipv4 = ipv4range_to_nets(ipv4range); for el in lst_ipv4.iter() { ipv4_nets.push_back(*el); } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_print.rs
src/vm/vm_print.rs
use std::convert::TryInto; use std::io; use std::io::Write; use std::str; use atty::Stream; use termion::input::TermRead; use termion::raw::IntoRawMode; use unicode_segmentation::UnicodeSegmentation; use crate::chunk::{Chunk, Value}; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; /// Helper function for paging once the line limit has been reached. fn pager_input(window_height: i32, mut lines_to_print: i32) -> i32 { if (window_height <= 0) || !atty::is(Stream::Stdout) { return 1; } if lines_to_print > 0 { return lines_to_print; } let mut stdout = io::stdout().into_raw_mode().unwrap(); let stdin = std::io::stdin(); for c in stdin.keys() { match c { Ok(termion::event::Key::Char('q')) => { stdout.suspend_raw_mode().unwrap(); return -1; } Ok(termion::event::Key::Ctrl('c')) => { stdout.suspend_raw_mode().unwrap(); return -1; } Ok(termion::event::Key::PageDown) => { lines_to_print += window_height - 1; } Ok(termion::event::Key::End) => { /* todo: a bit of a hack. It would be better * if there were some way of indicating that * there's no need to wait on input if End is * pressed. */ lines_to_print = i32::MAX; } Ok(termion::event::Key::Ctrl('f')) => { lines_to_print += window_height - 1; } Ok(termion::event::Key::Char('G')) => { lines_to_print = i32::MAX; } /* The default behaviour for these two might be * confusing, so make them no-ops. */ Ok(termion::event::Key::Home) => { continue; } Ok(termion::event::Key::PageUp) => { continue; } Ok(_) => { lines_to_print += 1; } _ => { continue; } } stdout.flush().unwrap(); break; } stdout.suspend_raw_mode().unwrap(); return lines_to_print; } /// Helper function for print_stack_value. Takes a string, an indent /// count, whether the first indent needs to be skipped, the window /// height, and the number of lines that can be printed without /// waiting as its arguments. Prints the string to standard output, /// waiting for user input as required. Returns the new number of /// lines that can be printed without waiting. Returns -1 if the user /// cancels further output. (A window height of zero indicates that /// the current program is not being run interactively, in which case /// no waiting is required.) fn psv_helper( s: &str, indent: i32, no_first_indent: bool, window_height: i32, window_width: i32, mut lines_to_print: i32, index: Option<i32>, ) -> i32 { if !atty::is(Stream::Stdout) || (window_width == 0) { if !no_first_indent { for _ in 0..indent { print!(" "); } } if let Some(n) = index { print!("{}: ", n); } println!("{}", s); return lines_to_print - 1; } lines_to_print = pager_input(window_height, lines_to_print); if lines_to_print == -1 { return -1; } let mut str_offset = 0; if !no_first_indent { str_offset += indent; for _ in 0..indent { print!(" "); } } if let Some(n) = index { str_offset += n.to_string().len() as i32; str_offset += 2; print!("{}: ", n); } let mut str_finish = (window_width - str_offset) as usize; let graphemes: Vec<&str> = s.graphemes(true).collect(); let slen = graphemes.len(); if slen < str_finish { println!("{}", s); return lines_to_print - 1; } let mut str_start = 0; while str_finish < slen { let joined_str = graphemes[str_start..str_finish].join(""); println!("{}", joined_str); str_start = str_finish; str_finish += window_width as usize; lines_to_print -= 1; lines_to_print = pager_input(window_height, lines_to_print); if lines_to_print == -1 { return -1; } } if str_start <= slen { let joined_str = graphemes[str_start..slen].join(""); println!("{}", joined_str); lines_to_print -= 1; } return lines_to_print; } impl VM { /// Takes a value that can be stringified as its single argument, /// and prints that value to standard output. pub fn opcode_print(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("print requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { print!("{}", s); 1 } _ => { self.print_error("print argument must be a string"); 0 } } } /// Takes a value that can be stringified as its single argument, /// and prints that value followed by newline to standard output. pub fn core_println(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("println requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { println!("{}", s); 1 } _ => { self.print_error("println argument must be a string"); 0 } } } /// Used by print_stack to print a single stack value. Takes a /// wrapped value, the current chunk, the instruction index, the /// map of global functions, the current indent, the window height /// (if run interactively), and the number of lines that can be /// printed without waiting for user input as its arguments. /// Prints the stack value to standard output, returning the new /// number of lines that can be printed without waiting for user /// input. #[allow(clippy::too_many_arguments)] pub fn print_stack_value( &mut self, value_rr: &Value, chunk: Rc<RefCell<Chunk>>, i: usize, indent: i32, no_first_indent: bool, window_height: i32, window_width: i32, mut lines_to_print: i32, index: Option<i32>, last_stack: &mut Vec<Value>, ) -> i32 { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return -1; } let type_string = value_rr.type_string(); let mut shiftable_fallback = false; { match value_rr { Value::Ipv4(_) | Value::Ipv4Range(_) | Value::Ipv6(_) | Value::Ipv6Range(_) => { last_stack.push(value_rr.clone()); let s = format!("v[{} {}]", &type_string, value_rr.to_string().unwrap()); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DateTimeNT(dt) => { last_stack.push(value_rr.clone()); let s = format!("v[{} {}]", &type_string, dt.format("%F %T %Z")); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DateTimeOT(dt) => { last_stack.push(value_rr.clone()); let s = format!("v[{} {}]", &type_string, dt.format("%F %T %Z")); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } /* The way this works is less than ideal, what with it * being different from standard stringification, but * it may be that having separate representations is * useful for some reason. */ Value::CoreFunction(_) | Value::NamedFunction(_) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &type_string); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Null => { last_stack.push(value_rr.clone()); lines_to_print = psv_helper( "null", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Bool(b) => { last_stack.push(value_rr.clone()); let s = if *b { ".t" } else { ".f" }; lines_to_print = psv_helper( s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Byte(b) => { last_stack.push(value_rr.clone()); let s = format!("{:#04x}", b); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Int(n) => { last_stack.push(value_rr.clone()); let s = format!("{}", n); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::BigInt(n) => { last_stack.push(value_rr.clone()); let s = format!("{}", n); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Float(f) => { last_stack.push(value_rr.clone()); let s = format!("{}", f); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::String(st) => { last_stack.push(value_rr.clone()); let mut ss = st.borrow().escaped_string.clone(); if st.borrow().string.contains(char::is_whitespace) { ss = format!("\"{}\"", ss); } else if ss.is_empty() { ss = "\"\"".to_string(); } else if ss == ".t" { ss = "\".t\"".to_string(); } else if ss == ".f" { ss = "\".f\"".to_string(); } lines_to_print = psv_helper( &ss, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::Command(s, _) => { last_stack.push(value_rr.clone()); let s = format!("v[{} {}]", &type_string, s); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::CommandUncaptured(s) => { last_stack.push(value_rr.clone()); let s = format!("v[{} {}]", &type_string, s); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::FileWriter(_) | Value::DirectoryHandle(_) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &type_string); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::AnonymousFunction(_, _) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBConnectionMySQL(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBConnectionPostgres(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBConnectionSQLite(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBStatementMySQL(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBStatementPostgres(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::DBStatementSQLite(..) => { last_stack.push(value_rr.clone()); let s = format!("v[{}]", &(value_rr.type_string())); lines_to_print = psv_helper( &s, indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } Value::List(list) => { let mut sublist = Vec::new(); if list.borrow().len() == 0 { last_stack.push(Value::List(Rc::new(RefCell::new(VecDeque::from(sublist))))); lines_to_print = psv_helper( "()", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } else { lines_to_print = psv_helper( "(", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); if lines_to_print == -1 { last_stack.push(Value::List(Rc::new(RefCell::new(VecDeque::from(sublist))))); return lines_to_print; } let new_indent = indent + 4; let lb = list.borrow(); let mut eniter = lb.iter().enumerate(); loop { let next = eniter.next(); match next { Some((index, element)) => { lines_to_print = self.print_stack_value( element, chunk.clone(), i, new_indent, false, window_height, window_width, lines_to_print, Some(index.try_into().unwrap()), &mut sublist, ); if lines_to_print == -1 { loop { let next = eniter.next(); match next { Some((_, element)) => { sublist.push(element.clone()); } _ => { break; } } } last_stack.push(Value::List(Rc::new(RefCell::new(VecDeque::from(sublist))))); return lines_to_print; } } _ => { break; } } } last_stack.push(Value::List(Rc::new(RefCell::new(VecDeque::from(sublist))))); lines_to_print = psv_helper(")", indent, false, window_height, window_width, lines_to_print, None); } } Value::Hash(map) => { let mut subhash = new_hash_indexmap(); if map.borrow().len() == 0 { last_stack.push(Value::Hash(Rc::new(RefCell::new(subhash)))); lines_to_print = psv_helper( "h()", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } else { lines_to_print = psv_helper( "h(", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); if lines_to_print == -1 { last_stack.push(Value::Hash(Rc::new(RefCell::new(subhash)))); return lines_to_print; } let mut key_maxlen = 0; for (k, _) in map.borrow().iter() { let key_len = k.len(); if key_len > key_maxlen { key_maxlen = key_len; } } let new_indent = indent + 4; let mut hash_values = Vec::new(); let mb = map.borrow(); let mut iter = mb.iter(); loop { let next = iter.next(); match next { Some((k, v)) => { for _ in 0..new_indent { print!(" "); } print!("\"{}\": ", k); let extra_spaces = key_maxlen - k.len(); for _ in 0..extra_spaces { print!(" "); } lines_to_print = self.print_stack_value( v, chunk.clone(), i, new_indent, true, window_height, window_width, lines_to_print, None, &mut hash_values, ); let new_hash_value = hash_values.pop().unwrap(); subhash.insert(k.to_string(), new_hash_value); if lines_to_print == -1 { loop { let next = iter.next(); match next { Some((k, v)) => { subhash.insert(k.to_string(), v.clone()); } _ => { break; } } } last_stack.push(Value::Hash(Rc::new(RefCell::new(subhash)))); return lines_to_print; } } _ => { break; } } } last_stack.push(Value::Hash(Rc::new(RefCell::new(subhash)))); lines_to_print = psv_helper(")", indent, false, window_height, window_width, lines_to_print, None); } } Value::Set(map) => { let mut subhash = new_set_indexmap(); if map.borrow().len() == 0 { last_stack.push(Value::Set(Rc::new(RefCell::new(subhash)))); lines_to_print = psv_helper( "s()", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); } else { lines_to_print = psv_helper( "s(", indent, no_first_indent, window_height, window_width, lines_to_print, index, ); if lines_to_print == -1 { last_stack.push(Value::Set(Rc::new(RefCell::new(subhash)))); return lines_to_print; } let new_indent = indent + 4; let mut hash_values = Vec::new(); let mb = map.borrow(); let mut iter = mb.iter(); loop { let next = iter.next(); match next { Some((k, v)) => { lines_to_print = self.print_stack_value( v, chunk.clone(), i, new_indent, false, window_height, window_width, lines_to_print, None, &mut hash_values, ); let new_hash_value = hash_values.pop().unwrap(); subhash.insert(k.to_string(), new_hash_value); if lines_to_print == -1 { loop { let next = iter.next(); match next { Some((k, v)) => { subhash.insert(k.to_string(), v.clone()); } _ => { break; } } } last_stack.push(Value::Set(Rc::new(RefCell::new(subhash)))); return lines_to_print; } } _ => { break; } } } last_stack.push(Value::Set(Rc::new(RefCell::new(subhash)))); lines_to_print = psv_helper(")", indent, false, window_height, window_width, lines_to_print, None); } } _ => { shiftable_fallback = true; } } } if shiftable_fallback && value_rr.is_shiftable() { let mut has_elements = false; self.stack.push(value_rr.clone()); let mut element_index = 0; let mut sublist = Vec::new(); loop { let dup_res = self.opcode_dup(); if dup_res == 0 { let mut submg = VecDeque::new(); submg.push_back( Value::List(Rc::new(RefCell::new(VecDeque::from(sublist)))) ); submg.push_back(value_rr.clone()); last_stack.push( Value::MultiGenerator(Rc::new(RefCell::new(submg))) ); return -1; } let shift_res = self.opcode_shift(); if shift_res == 0 { let mut submg = VecDeque::new(); submg.push_back( Value::List(Rc::new(RefCell::new(VecDeque::from(sublist)))) ); submg.push_back(value_rr.clone()); last_stack.push( Value::MultiGenerator(Rc::new(RefCell::new(submg))) ); self.stack.pop(); return -1; } if self.stack.is_empty() { break; } let is_null; let element_rr = self.stack.pop().unwrap(); { match element_rr { Value::Null => { is_null = true; } _ => { is_null = false; } } } if !is_null { if !has_elements { let new_str = format!("v[{} (", &type_string); lines_to_print = psv_helper(
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_xml.rs
src/vm/vm_xml.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use indexmap::IndexMap; use crate::chunk::{StringTriple, Value}; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; /// Converts a value into an XML string. fn convert_to_xml(v: &Value) -> Option<String> { let mut begin_open_element = String::new(); let attributes; let namespaces; let mut begin_close_element = String::new(); let mut text = String::new(); let child_nodes; let mut end_element = String::new(); match v { Value::Hash(vm) => { let vmm = vm.borrow(); let key_opt = vmm.get("key"); if let Some(Value::String(st)) = key_opt { let s = &st.borrow().string; if !s.is_empty() { begin_open_element = format!("<{}", s); begin_close_element = ">".to_string(); end_element = format!("</{}>", s); } } let attributes_opt = vmm.get("attributes"); let attributes_str = match attributes_opt { Some(Value::Hash(map)) => { let mut has_none = false; let attributes_str_lst = map .borrow() .iter() .map(|(key, value_rr)| { let value_str_opt: Option<&str>; to_str!(value_rr, value_str_opt); match value_str_opt { Some(s) => { format!("{}=\"{}\"", key, s) } None => { has_none = true; "".to_string() } } }) .collect::<Vec<_>>(); if has_none { return None; } else { attributes_str_lst.join(" ") } } _ => "".to_string(), }; attributes = if !attributes_str.is_empty() { format!(" {}", attributes_str) } else { "".to_owned() }; let namespaces_opt = vmm.get("namespaces"); let namespaces_str = match namespaces_opt { Some(Value::List(lst)) => { let namespaces_lst = lst .borrow() .iter() .map(|el| match el { Value::Hash(hsh) => { let hb = hsh.borrow(); let uri_opt = hb.get("uri").unwrap(); let name_opt = hb.get("name").unwrap(); let uri_str_opt: Option<&str>; to_str!(uri_opt, uri_str_opt); let name_str_opt: Option<&str>; to_str!(name_opt, name_str_opt); match (name_str_opt, uri_str_opt) { (Some(name), Some(uri)) => { if name.eq("") { format!("xmlns=\"{}\"", uri) } else { format!("xmlns:{}=\"{}\"", name, uri) } } _ => "".to_string(), } } _ => "".to_string(), }) .collect::<Vec<_>>(); namespaces_lst.join(" ") } _ => "".to_string(), }; namespaces = if !namespaces_str.is_empty() { format!(" {}", namespaces_str) } else { "".to_owned() }; let value_opt = vmm.get("value"); let mut has_none = false; child_nodes = match value_opt { Some(Value::List(lst)) => lst .borrow() .iter() .map(|lst_value_rr| { let lst_value_rrb = convert_to_xml(lst_value_rr); match lst_value_rrb { Some(lst_value) => lst_value, None => { has_none = true; "".to_string() } } }) .collect::<Vec<_>>() .join(""), _ => "".to_string(), }; if has_none { return None; } if vmm.contains_key("text") { let t = vmm.get("text").unwrap(); if let Value::String(ts) = t { text = ts.borrow().string.clone(); } else { let s_opt = t.to_string(); match s_opt { Some(s) => { text = s; } None => { let type_str = v.type_string(); text = format!("v[{}]", type_str); } } } } Some(format!( "{}{}{}{}{}{}{}", begin_open_element, namespaces, attributes, begin_close_element, text, child_nodes, end_element )) } _ => Some("".to_string()), } } impl VM { /// Converts a roxmltree object into a value. fn convert_from_xml( &self, node: &roxmltree::Node, param_namespaces: &HashMap<String, String>, ) -> Value { let mut map = new_hash_indexmap(); let mut current_namespaces = param_namespaces; let mut changed_namespaces = false; for ns in node.namespaces() { let uri = ns.uri(); let ns_name_opt = ns.name(); let name = match ns_name_opt { Some(ns_name) => ns_name.to_string(), None => "".to_string(), }; if let Some(prev_name) = current_namespaces.get(uri) { if name.eq(prev_name) { continue; } } changed_namespaces = true; break; } let mut new_namespaces; if changed_namespaces { let mut node_namespaces = VecDeque::new(); new_namespaces = current_namespaces.clone(); for ns in node.namespaces() { let uri = ns.uri(); let ns_name_opt = ns.name(); let name = match ns_name_opt { Some(ns_name) => ns_name.to_string(), None => "".to_string(), }; if let Some(prev_name) = current_namespaces.get(uri) { if name.eq(prev_name) { continue; } } let mut ns_map = new_hash_indexmap(); ns_map.insert( "uri".to_string(), Value::String(Rc::new(RefCell::new(StringTriple::new( uri.to_string(), None, )))), ); ns_map.insert( "name".to_string(), Value::String(Rc::new(RefCell::new(StringTriple::new( name.to_string(), None, )))), ); node_namespaces.push_back(Value::Hash(Rc::new(RefCell::new(ns_map)))); new_namespaces.insert(uri.to_string(), name.to_string()); } map.insert( "namespaces".to_string(), Value::List(Rc::new(RefCell::new(node_namespaces))), ); current_namespaces = &new_namespaces; } let tag_name = node.tag_name(); let tag_name_str = tag_name.name().to_string(); let tag_name_ns = tag_name.namespace(); let key = match tag_name_ns { Some(tag_ns) => { let ns_prefix_opt = current_namespaces.get(tag_ns); if ns_prefix_opt.is_none() { self.print_error("invalid XML namespace"); return Value::Null; } let ns_prefix = ns_prefix_opt.unwrap(); if !ns_prefix.eq("") { format!("{}:{}", ns_prefix, tag_name_str) } else { tag_name_str } } None => tag_name_str, }; map.insert( "key".to_string(), Value::String(Rc::new(RefCell::new(StringTriple::new(key, None)))), ); if node.is_text() { let text_opt = node.text(); match text_opt { None => {} Some(s) => { map.insert( "text".to_string(), Value::String(Rc::new(RefCell::new(StringTriple::new( s.to_string(), None, )))), ); } } return Value::Hash(Rc::new(RefCell::new(map))); } let mut attr_map = new_hash_indexmap(); for attr in node.attributes() { attr_map.insert( attr.name().to_string(), Value::String(Rc::new(RefCell::new(StringTriple::new( attr.value().to_string(), None, )))), ); } map.insert( "attributes".to_string(), Value::Hash(Rc::new(RefCell::new(attr_map))), ); let mut child_nodes = VecDeque::new(); for child_node in node.children() { let child_node_value = self.convert_from_xml(&child_node, current_namespaces); child_nodes.push_back(child_node_value); } map.insert( "value".to_string(), Value::List(Rc::new(RefCell::new(child_nodes))), ); Value::Hash(Rc::new(RefCell::new(map))) } /// Takes an XML string, converts it into a hash, and puts the /// result onto the stack. pub fn core_from_xml(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("from-xml requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); if !value_rr.is_generator() { let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let doc_res = roxmltree::Document::parse(s); let doc; match doc_res { Err(e) => { let err_str = format!("unable to parse XML: {}", e); self.print_error(&err_str); return 0; } Ok(d) => { doc = d; } } let namespaces = HashMap::new(); let xml_rr = self.convert_from_xml(&doc.root_element(), &namespaces); self.stack.push(xml_rr); 1 } _ => { self.print_error("from-xml argument must be string or generator"); 0 } } } else { self.stack.push(value_rr); self.stack .push(Value::String(Rc::new(RefCell::new(StringTriple::new( "".to_string(), None, ))))); let function_rr = self.string_to_callable("join").unwrap(); let res = self.call(OpCode::Call, function_rr); if !res { return 0; } self.core_from_xml() } } /// Takes a hash that is the result of calling `from-xml`, converts /// it into a string representation, and puts the result onto the /// stack. pub fn core_to_xml(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("to-xml requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let doc_opt = convert_to_xml(&value_rr); if doc_opt.is_none() { self.print_error("unable to convert value to XML"); return 0; } self.stack .push(Value::String(Rc::new(RefCell::new(StringTriple::new( doc_opt.unwrap(), None, ))))); 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_sort.rs
src/vm/vm_sort.rs
use std::cmp::Ordering; use crate::chunk::Value; use crate::vm::*; impl VM { /// Sorts the elements of a list or generator using behaviour per /// the default cmp operation. pub fn core_sort(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sort requires one argument"); return 0; } let mut value_rr = self.stack.pop().unwrap(); if value_rr.is_generator() { self.stack.push(value_rr); let res = self.generator_to_list(); if res == 0 { return 0; } return self.core_sort(); } match value_rr { Value::List(ref mut lst) => { let mut all_strings = true; for e in lst.borrow().iter() { match e { Value::String(_) => {} _ => { all_strings = false; break; } } } /* If the list comprises strings only, then * short-circuit the call to opcode_cmp_inner. */ if all_strings { lst.borrow_mut() .make_contiguous() .sort_by(|a, b| match (a, b) { (Value::String(sp1), Value::String(sp2)) => { let s1 = &(sp1.borrow().string); let s2 = &(sp2.borrow().string); s1.cmp(s2) } _ => { eprintln!("expected string in sort!"); std::process::abort(); } }); } else { let mut success = true; lst.borrow_mut().make_contiguous().sort_by(|a, b| { let res = self.opcode_cmp_inner(b, a); if res == -2 { success = false; Ordering::Equal } else if res == 1 { Ordering::Greater } else if res == 0 { Ordering::Equal } else { Ordering::Less } }); if !success { self.print_error("unable to sort elements"); return 0; } } } _ => { self.print_error("unable to sort value"); return 0; } } self.stack.push(value_rr); 1 } /// Sorts the elements of a list or generator using behaviour per /// the provided predicate. pub fn core_sortp(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("sortp requires two arguments"); return 0; } let res = self.opcode_tofunction(); if res == 0 { return 0; } let fn_rr = self.stack.pop().unwrap(); let mut value_rr = self.stack.pop().unwrap(); if value_rr.is_generator() { self.stack.push(value_rr); let res = self.generator_to_list(); if res == 0 { return 0; } self.stack.push(fn_rr); return self.core_sortp(); } match value_rr { Value::List(ref mut lst) => { let mut success = true; lst.borrow_mut().make_contiguous().sort_by(|a, b| { if !success { return Ordering::Equal; } self.stack.push(a.clone()); self.stack.push(b.clone()); let res = self.call(OpCode::Call, fn_rr.clone()); if !res { success = false; return Ordering::Equal; } if self.stack.is_empty() { self.print_error("sortp predicate should return a value"); success = false; return Ordering::Equal; } let ret = self.stack.pop().unwrap(); match ret { Value::Int(n) => { if n == -1 { Ordering::Less } else if n == 0 { Ordering::Equal } else if n == 1 { Ordering::Greater } else { self.print_error("sortp predicate should return an int"); success = false; Ordering::Equal } } _ => { self.print_error("sortp predicate should return an int"); success = false; Ordering::Equal } } }); if !success { return 0; } } _ => { self.print_error("unable to sort value"); return 0; } } self.stack.push(value_rr); 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_basics.rs
src/vm/vm_basics.rs
use std::char; use std::{thread, time}; use num_bigint::BigInt; use num_traits::FromPrimitive; use num_traits::Num; use num_traits::ToPrimitive; use rand::Rng; use unicode_segmentation::UnicodeSegmentation; use crate::chunk::Value; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; impl VM { /// Remove the top element from the stack. pub fn opcode_drop(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("drop requires one argument"); return 0; } self.stack.pop(); 1 } /// Remove all elements from the stack. #[allow(unused_variables)] pub fn opcode_clear(&mut self) -> i32 { self.stack.clear(); 1 } /// Take the top element from the stack, duplicate it, and add it /// onto the stack. pub fn opcode_dup(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("dup requires one argument"); return 0; } self.stack.push(self.stack.last().unwrap().clone()); 1 } /// Take the second element from the top from the stack, duplicate /// it, and add it onto the stack. pub fn opcode_over(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("over requires two arguments"); return 0; } self.stack.push(self.stack[self.stack.len() - 2].clone()); 1 } /// Swap the top two elements from the stack. pub fn opcode_swap(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("swap requires two arguments"); return 0; } self.stack.swap(len - 1, len - 2); 1 } /// Rotate the top three elements from the stack: the top element /// becomes the second from top element, the second from top /// element becomes the third from top element, and the third from /// top element becomes the top element. pub fn opcode_rot(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("rot requires three arguments"); return 0; } let first_rr = self.stack.pop().unwrap(); let second_rr = self.stack.pop().unwrap(); let third_rr = self.stack.pop().unwrap(); self.stack.push(second_rr); self.stack.push(first_rr); self.stack.push(third_rr); 1 } /// Push the current depth of the stack onto the stack. #[allow(unused_variables)] pub fn opcode_depth(&mut self) -> i32 { self.stack.push(Value::Int(self.stack.len() as i32)); 1 } /// Adds the length of the topmost element onto the stack. /// Supports lists, hashes, sets, strings, and generators. pub fn core_len(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("len requires one argument"); return 0; } let lst_rr = self.stack.pop().unwrap(); match lst_rr { Value::List(lst) => { let len = lst.borrow().len(); self.stack.push(Value::Int(len as i32)); return 1; } Value::Hash(hsh) => { let len = hsh.borrow().len(); self.stack.push(Value::Int(len as i32)); return 1; } Value::Set(hsh) => { let len = hsh.borrow().len(); self.stack.push(Value::Int(len as i32)); return 1; } Value::String(st) => { let len = st.borrow().string.len(); self.stack.push(Value::Int(len as i32)); return 1; } _ => {} } self.stack.push(lst_rr); let mut len = 0; loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return 0; } let shift_res = self.opcode_shift(); if shift_res == 0 { return 0; } let value_rr = self.stack.pop().unwrap(); if let Value::Null = value_rr { self.stack.pop(); self.stack.push(Value::Int(len)); return 1; } len += 1; } } /// Checks whether the length of the topmost element is zero. /// Supports lists, hashes, sets, strings, and generators. pub fn core_empty(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("empty requires one argument"); return 0; } let lst_rr = self.stack.pop().unwrap(); match lst_rr { Value::List(lst) => { let len = lst.borrow().len(); self.stack.push(Value::Bool(len == 0)); return 1; } Value::Hash(hsh) => { let len = hsh.borrow().len(); self.stack.push(Value::Bool(len == 0)); return 1; } Value::Set(hsh) => { let len = hsh.borrow().len(); self.stack.push(Value::Bool(len == 0)); return 1; } Value::String(st) => { let len = st.borrow().string.len(); self.stack.push(Value::Bool(len == 0)); return 1; } _ => {} } self.stack.push(lst_rr); let mut len = 0; loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return 0; } let shift_res = self.opcode_shift(); if shift_res == 0 { return 0; } let value_rr = self.stack.pop().unwrap(); if let Value::Null = value_rr { self.stack.pop(); self.stack.push(Value::Bool(len == 0)); return 1; } len += 1; } } /// Adds a boolean onto the stack indicating whether the topmost /// element is a null value. pub fn opcode_isnull(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-null requires one argument"); return 0; } let i1_rr = self.stack.pop().unwrap(); let is_null = matches!(i1_rr, Value::Null); self.stack.push(Value::Bool(is_null)); 1 } pub fn opcode_dupisnull(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-null requires one argument"); return 0; } let i1_rr = self.stack.last().unwrap(); let is_null = matches!(i1_rr, Value::Null); self.stack.push(Value::Bool(is_null)); 1 } /// Adds a boolean onto the stack indicating whether the topmost /// element is a list. pub fn opcode_islist(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-list requires one argument"); return 0; } let i1_rr = self.stack.pop().unwrap(); let is_list = matches!(i1_rr, Value::List(_)); self.stack.push(Value::Bool(is_list)); 1 } /// Adds a boolean onto the stack indicating whether the topmost /// element can be called. (In the case of a string, this doesn't /// currently check that the string name maps to a function or /// core form, though.) pub fn opcode_iscallable(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-callable requires one argument"); return 0; } let i1_rr = self.stack.pop().unwrap(); let is_callable = matches!( i1_rr, Value::AnonymousFunction(_, _) | Value::CoreFunction(_) | Value::NamedFunction(_) | Value::String(_) ); self.stack.push(Value::Bool(is_callable)); 1 } /// Convert a value into a byte value. pub fn opcode_byte(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("byte requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); match value_rr { Value::Int(n) => { if n <= 255 { let nv = Value::Byte(n as u8); self.stack.push(nv); return 1; } } Value::BigInt(n) => { if n <= BigInt::from_u32(255).unwrap() { let nv = Value::Byte(n.to_u8().unwrap()); self.stack.push(nv); return 1; } } _ => { } } self.stack.push(Value::Null); return 1; } /// Convert a value into a string value. pub fn opcode_str(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("str requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); match value_rr { Value::IpSet(_) => {}, _ => { if value_rr.is_generator() { self.stack.push(value_rr); let res = self.generator_to_list(); if res == 0 { return 0; } return self.opcode_str(); } } } let is_string; { match value_rr { Value::String(_) => { is_string = true; } _ => { let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { self.stack.push(new_string_value(s.to_string())); return 1; } _ => { self.stack.push(Value::Null); return 1; } } } } } if is_string { self.stack.push(value_rr); } 1 } /// Convert a value into an integer/bigint value. pub fn opcode_int(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("int requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let is_int; { match value_rr { Value::Int(_) => { is_int = true; } Value::BigInt(_) => { is_int = true; } _ => { let value_opt = value_rr.to_int(); match value_opt { Some(n) => { self.stack.push(Value::Int(n)); return 1; } _ => { let value_opt = value_rr.to_bigint(); match value_opt { Some(n) => { self.stack.push(Value::BigInt(n)); return 1; } _ => { self.stack.push(Value::Null); return 1; } } } } } } } if is_int { self.stack.push(value_rr); } 1 } /// Convert a value into a bigint value. pub fn opcode_bigint(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("bigint requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let is_bigint; { match value_rr { Value::BigInt(_) => { is_bigint = true; } _ => { let value_opt = value_rr.to_bigint(); match value_opt { Some(n) => { self.stack.push(Value::BigInt(n)); return 1; } _ => { self.stack.push(Value::Null); return 1; } } } } } if is_bigint { self.stack.push(value_rr); } 1 } /// Convert a value into a floating-point value. pub fn opcode_flt(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("float requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let is_float; { match value_rr { Value::Float(_) => { is_float = true; } _ => { let value_opt = value_rr.to_float(); match value_opt { Some(n) => { self.stack.push(Value::Float(n)); return 1; } _ => { self.stack.push(Value::Null); return 1; } } } } } if is_float { self.stack.push(value_rr); } 1 } /// Convert a value into a boolean value. pub fn opcode_bool(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("bool requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let new_value = Value::Bool(value_rr.to_bool()); self.stack.push(new_value); 1 } /// Check whether a value is of boolean type. pub fn opcode_is_bool(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-bool requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Bool(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is of int type. pub fn opcode_is_int(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-int requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Int(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is of bigint type. pub fn opcode_is_bigint(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-bigint requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::BigInt(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is of byte type. pub fn opcode_is_byte(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-byte requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Byte(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is of string type. pub fn opcode_is_str(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-str requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::String(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is of floating-point type. pub fn opcode_is_flt(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-float requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Float(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is a set. pub fn opcode_is_set(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-set requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Set(_)); self.stack.push(Value::Bool(res)); 1 } /// Check whether a value is a hash. pub fn opcode_is_hash(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-hash requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let res = matches!(value_rr, Value::Hash(_)); self.stack.push(Value::Bool(res)); 1 } /// Get a random floating-point value. pub fn opcode_rand(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("rand requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt = value_rr.to_float(); match value_opt { Some(n) => { if n <= 0.0 { self.print_error("rand argument must be positive number"); return 0; } let mut rng = rand::thread_rng(); let rand_value = rng.gen_range(0.0..n); self.stack.push(Value::Float(rand_value)); } _ => { self.print_error("rand argument must be float"); return 0; } } 1 } /// Return a deep clone of the argument (compare dup). pub fn opcode_clone(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("clone requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let cloned_value_rr = value_rr.value_clone(); self.stack.push(cloned_value_rr); 1 } /// Converts a Unicode numeral into a character. pub fn core_chr(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("chr requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt = value_rr.to_int(); match value_opt { Some(n) => { let n_u32_opt: Result<u32, _> = n.try_into(); if n_u32_opt.is_err() { self.print_error("chr argument must be u32 integer"); return 0; } let c_opt = char::from_u32(n_u32_opt.unwrap()); if c_opt.is_none() { self.print_error("chr argument must be character"); return 0; } let c = c_opt.unwrap().to_string(); self.stack.push(new_string_value(c)); 1 } _ => { let value_bi_opt = value_rr.to_bigint(); if value_bi_opt.is_none() { self.print_error("chr argument must be integer"); return 0; } let value_bi = value_bi_opt.unwrap(); let value_bi_u32_opt = value_bi.to_u32(); if value_bi_u32_opt.is_none() { self.print_error("chr argument must be u32 integer"); return 0; } let n_u32 = value_bi_u32_opt.unwrap(); let c_opt = char::from_u32(n_u32); if c_opt.is_none() { self.print_error("chr argument must be integer"); return 0; } let c = c_opt.unwrap().to_string(); self.stack.push(new_string_value(c)); 1 } } } /// Converts a character into a Unicode numeral. pub fn core_ord(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ord requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("ord argument must be string"); return 0; } let value_str = value_opt.unwrap(); if value_str.chars().count() != 1 { self.print_error("ord argument must be one character in length"); return 0; } let c = value_str.chars().next().unwrap(); let n: u32 = c.try_into().unwrap(); let n_i32: Result<i32, _> = n.try_into(); if let Ok(n) = n_i32 { self.stack.push(Value::Int(n)); return 1; } self.stack.push(Value::BigInt(BigInt::from_u32(n).unwrap())); 1 } /// Converts an integer or bigint into a hex string. pub fn core_hex(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("hex requires one argument"); return 0; } let n_rr = self.stack.pop().unwrap(); let n_int_opt = n_rr.to_int(); if let Some(n) = n_int_opt { self.stack.push(new_string_value(format!("{:x}", n))); return 1; } let n_bi_opt = n_rr.to_bigint(); if let Some(n) = n_bi_opt { self.stack.push(new_string_value(format!("{:x}", n))); return 1; } if let Value::List(lst) = n_rr { let mut results = Vec::new(); for el_rr in lst.borrow().iter() { if let Value::Byte(b) = el_rr { results.push(format!("{:02x}", b)); } else { self.print_error("hex list argument element must be byte"); return 0; } } self.stack.push(new_string_value(results.join(""))); return 1; } self.print_error("hex argument must be integer"); 0 } /// Converts a hex string into an integer or bigint. pub fn core_unhex(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("unhex requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("unhex argument must be string"); return 0; } let value_str = value_opt.unwrap().replace("0x", ""); let n_i32: Result<i32, _> = i32::from_str_radix(&value_str, 16); if let Ok(n) = n_i32 { self.stack.push(Value::Int(n)); return 1; } let n_bi: Result<BigInt, _> = BigInt::from_str_radix(&value_str, 16); if let Ok(bi) = n_bi { self.stack.push(Value::BigInt(bi)); return 1; } self.print_error("unhex argument must be hexadecimal string"); 0 } pub fn core_oct(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("oct requires one argument"); return 0; } let n_rr = self.stack.pop().unwrap(); let n_int_opt = n_rr.to_int(); if let Some(n) = n_int_opt { self.stack.push(new_string_value(format!("{:o}", n))); return 1; } let n_bi_opt = n_rr.to_bigint(); if let Some(n) = n_bi_opt { self.stack.push(new_string_value(format!("{:o}", n))); return 1; } self.print_error("oct argument must be integer"); 0 } /// Converts an octal string into an integer or bigint. pub fn core_unoct(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("unoct requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("unoct argument must be string"); return 0; } let value_str = value_opt.unwrap(); let n_i32: Result<i32, _> = i32::from_str_radix(value_str, 8); if let Ok(n) = n_i32 { self.stack.push(Value::Int(n)); return 1; } let n_bi: Result<BigInt, _> = BigInt::from_str_radix(value_str, 8); if let Ok(bi) = n_bi { self.stack.push(Value::BigInt(bi)); return 1; } self.print_error("unoct argument must be string"); 0 } /// Converts a string to lowercase. pub fn core_lc(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("lc requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("lc argument must be string"); return 0; } let lc_str = value_opt.unwrap().to_lowercase(); self.stack.push(new_string_value(lc_str)); 1 } /// Converts the first character of a string to lowercase. pub fn core_lcfirst(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("lcfirst requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("lcfirst argument must be string"); return 0; } let vst = value_opt.unwrap(); if vst.is_empty() { self.stack.push(new_string_value(vst.to_string())); return 1; } let mut iter = vst.chars(); let mut new_st = iter.next().unwrap().to_lowercase().to_string(); for c in iter { new_st.push(c); } self.stack.push(new_string_value(new_st)); 1 } /// Converts a string to uppercase. pub fn core_uc(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("uc requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("uc argument must be string"); return 0; } let uc_str = value_opt.unwrap().to_uppercase(); self.stack.push(new_string_value(uc_str)); 1 } /// Converts the first character of a string to uppercase. pub fn core_ucfirst(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("ucfirst requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("ucfirst argument must be string"); return 0; } let vst = value_opt.unwrap(); if vst.is_empty() { self.stack.push(new_string_value(vst.to_string())); return 1; } let mut iter = vst.chars(); let mut new_st = iter.next().unwrap().to_uppercase().to_string(); for c in iter { new_st.push(c); } self.stack.push(new_string_value(new_st)); 1 } /// Reverses a list or a string. pub fn core_reverse(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("reverse requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); match value_rr { Value::List(lst) => { let mut rev_lst = VecDeque::new(); for e in lst.borrow().iter().rev() { rev_lst.push_back(e.clone()); } let new_lst = Value::List(Rc::new(RefCell::new(rev_lst))); self.stack.push(new_lst); 1 } _ => { let value_opt: Option<&str>; to_str!(value_rr, value_opt); if value_opt.is_none() { self.print_error("reverse argument must be list or string"); return 0; } let vst = value_opt.unwrap(); let rev: String = vst.graphemes(true).rev().collect(); self.stack.push(new_string_value(rev)); 1 } } } /// Pauses processing for the specified number of seconds. pub fn core_sleep(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sleep requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt = value_rr.to_float(); match value_opt { Some(mut f) => { loop { let to_sleep = if f < 0.05 { f } else { 0.05 }; f = f - to_sleep; let dur = time::Duration::from_secs_f64(to_sleep); thread::sleep(dur); if f == 0.0 { return 1; } if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } } } _ => { self.print_error("sleep argument must be float"); 0 } } } /// Inner function for reification. pub fn core_reify_inner(&mut self, value: Value) -> Option<Value> { match value { Value::List(list) => { let mut new_list = VecDeque::new(); let lb = list.borrow(); for v in lb.iter() { let new_v_opt = self.core_reify_inner(v.clone()); match new_v_opt { Some(new_v) => { new_list.push_back(new_v); } _ => { return None; } } } return Some(Value::List(Rc::new(RefCell::new(new_list)))); } Value::Hash(map) => { let mut new_map = new_hash_indexmap(); let mb = map.borrow(); for (k, v) in mb.iter() { let new_v_opt = self.core_reify_inner(v.clone()); match new_v_opt { Some(new_v) => { new_map.insert(k.to_string(), new_v); } _ => { return None; } } } return Some(Value::Hash(Rc::new(RefCell::new(new_map)))); } Value::Set(map) => { let mut new_map = new_set_indexmap(); let mb = map.borrow(); for (k, v) in mb.iter() { let new_v_opt = self.core_reify_inner(v.clone()); match new_v_opt { Some(new_v) => { new_map.insert(k.to_string(), new_v); } _ => { return None; } } } return Some(Value::Set(Rc::new(RefCell::new(new_map)))); } _ => {} } if value.is_generator() { self.stack.push(value); let mut new_list = VecDeque::new(); loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return None; }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_datetime.rs
src/vm/vm_datetime.rs
use std::convert::TryFrom; use std::fmt::Write; use std::str::FromStr; use chrono::format::{parse, Parsed, StrftimeItems}; use chrono::{DateTime, Duration, NaiveDateTime, TimeZone, Utc}; use chronoutil::RelativeDuration; use crate::vm::*; impl VM { /// Returns the current time as a date-time object, offset at UTC. pub fn core_now(&mut self) -> i32 { let date = chrono::offset::Utc::now(); let newdate = date.with_timezone(&self.utc_tz); self.stack.push(Value::DateTimeNT(newdate)); 1 } /// Returns the current time as a date-time object, offset at the /// local time zone. pub fn core_date(&mut self) -> i32 { let date = chrono::offset::Utc::now(); let newdate = date.with_timezone(&self.local_tz); self.stack.push(Value::DateTimeNT(newdate)); 1 } /// Takes a date-time object and returns the epoch time that /// corresponds to that object. pub fn core_to_epoch(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("to-epoch requires one argument"); return 0; } let dt_rr = self.stack.pop().unwrap(); match dt_rr { Value::DateTimeNT(dt) => { let epoch = dt.timestamp(); let epoch32 = i32::try_from(epoch).unwrap(); self.stack.push(Value::Int(epoch32)); 1 } Value::DateTimeOT(dt) => { let epoch = dt.timestamp(); let epoch32 = i32::try_from(epoch).unwrap(); self.stack.push(Value::Int(epoch32)); 1 } _ => { self.print_error("to-epoch argument must be date-time object"); 0 } } } /// Takes the epoch time (i.e. the number of seconds that have /// elapsed since 1970-01-01 00:00:00 UTC) and returns a date-time /// object (offset at UTC) that corresponds to that time. pub fn core_from_epoch(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("from-epoch requires one argument"); return 0; } let epoch_rr = self.stack.pop().unwrap(); let epoch_int_opt = epoch_rr.to_int(); match epoch_int_opt { Some(epoch_int) => { let epoch64 = i64::try_from(epoch_int).unwrap(); let naive = NaiveDateTime::from_timestamp_opt(epoch64, 0).unwrap(); let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive, Utc); let newdate = datetime.with_timezone(&self.utc_tz); self.stack.push(Value::DateTimeNT(newdate)); 1 } _ => { self.print_error("from-epoch argument must be integer"); 0 } } } /// Takes a date-time object and a named timezone (per the tz /// database) and returns a new date-time object offset at that /// timezone. pub fn core_set_tz(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("set-tz requires two arguments"); return 0; } let tz_rr = self.stack.pop().unwrap(); let tz_opt: Option<&str>; to_str!(tz_rr, tz_opt); let dt_rr = self.stack.pop().unwrap(); match (dt_rr, tz_opt) { (Value::DateTimeNT(dt), Some(s)) => { let tzr = chrono_tz::Tz::from_str(s); match tzr { Ok(tz) => { let newdate = dt.with_timezone(&tz); self.stack.push(Value::DateTimeNT(newdate)); 1 } _ => { self.print_error("second set-tz argument must be valid timezone"); 0 } } } (Value::DateTimeOT(dt), Some(s)) => { let tzr = chrono_tz::Tz::from_str(s); match tzr { Ok(tz) => { let newdate = dt.with_timezone(&tz); self.stack.push(Value::DateTimeNT(newdate)); 1 } _ => { self.print_error("second set-tz argument must be valid timezone"); 0 } } } (_, _) => { self.print_error("first set-tz argument must be date-time object"); 0 } } } /// The internal time-modification function. Takes a function name /// argument that is used only in error messages, so that this can /// be used by both +time and -time. fn addtime(&mut self, fn_name: &str) -> i32 { if self.stack.len() < 3 { let err_str = format!("{} requires three arguments", fn_name); self.print_error(&err_str); return 0; } let num_rr = self.stack.pop().unwrap(); let num_int_opt = num_rr.to_int(); let period_rr = self.stack.pop().unwrap(); let period_opt: Option<&str>; to_str!(period_rr, period_opt); let dt_rr = self.stack.pop().unwrap(); let mut rdur = None; let mut dur = None; match (period_opt, num_int_opt) { (Some("years"), Some(n)) => { rdur = Some(RelativeDuration::years(n)); } (Some("months"), Some(n)) => { rdur = Some(RelativeDuration::months(n)); } (Some("days"), Some(n)) => { dur = Some(Duration::days(i64::try_from(n).unwrap())); } (Some("hours"), Some(n)) => { dur = Some(Duration::hours(i64::try_from(n).unwrap())); } (Some("minutes"), Some(n)) => { dur = Some(Duration::minutes(i64::try_from(n).unwrap())); } (Some("seconds"), Some(n)) => { dur = Some(Duration::seconds(i64::try_from(n).unwrap())); } ( Some("years") | Some("months") | Some("days") | Some("hours") | Some("minutes") | Some("seconds"), _, ) => { let err_str = format!("third {} argument must be integer", fn_name); self.print_error(&err_str); return 0; } (..) => { let err_str = format!("second {} argument must be time unit", fn_name); self.print_error(&err_str); return 0; } } match (dt_rr, dur, rdur) { (Value::DateTimeNT(dt), Some(d), _) => { let ndt = dt + d; self.stack.push(Value::DateTimeNT(ndt)); 1 } (Value::DateTimeNT(dt), _, Some(d)) => { let ndt = dt + d; self.stack.push(Value::DateTimeNT(ndt)); 1 } (Value::DateTimeOT(dt), Some(d), _) => { let ndt = dt + d; self.stack.push(Value::DateTimeOT(ndt)); 1 } (Value::DateTimeOT(dt), _, Some(d)) => { let ndt = dt + d; self.stack.push(Value::DateTimeOT(ndt)); 1 } (Value::DateTimeNT(_) | Value::DateTimeOT(_), _, _) => { let err_str = format!("second {} argument must be time unit", fn_name); self.print_error(&err_str); 0 } (..) => { let err_str = format!("second {} argument must be date-time object", fn_name); self.print_error(&err_str); 0 } } } /// Takes a date-time object, a period (one of years, months, days, /// minutes, hours, or seconds) and a count as its arguments. /// Adds the specified number of periods to the date-time object /// and returns the result as a new date-time object. pub fn core_addtime(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("+time requires three arguments"); return 0; } self.addtime("+time") } /// Takes a date-time object, a period (one of years, months, days, /// minutes, hours, or seconds) and a count as its arguments. /// Subtracts the specified number of periods to the date-time /// object and returns the result as a new date-time object. pub fn core_subtime(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("-time requires three arguments"); return 0; } let num_rr = self.stack.pop().unwrap(); let num_int_opt = num_rr.to_int(); match num_int_opt { Some(n) => { self.stack.push(Value::Int(-n)); self.addtime("-time") } _ => { self.print_error("third -time argument must be integer"); 0 } } } /// Takes a date-time object and a strftime pattern as its /// arguments. Returns the stringification of the date per the /// pattern. pub fn core_strftime(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("strftime requires two arguments"); return 0; } let pat_rr = self.stack.pop().unwrap(); let pat_opt: Option<&str>; to_str!(pat_rr, pat_opt); let dt_rr = self.stack.pop().unwrap(); match (dt_rr, pat_opt) { (Value::DateTimeNT(dt), Some(s)) => { let mut buffer = String::new(); let res = write!(buffer, "{}", dt.format(s)); match res { Ok(_) => { self.stack.push(new_string_value(buffer)); 1 } Err(_) => { self.print_error("second strftime argument is invalid"); 0 } } } (Value::DateTimeOT(dt), Some(s)) => { let ss = dt.format(s); self.stack.push(new_string_value(ss.to_string())); 1 } (_, Some(_)) => { self.print_error("first strftime argument must be date-time object"); 0 } (..) => { self.print_error("second strftime argument must be string"); 0 } } } /// The internal strptime function, used by both core_strptime and /// core_strptimez. fn strptime(&self, pattern: &str, value: &str) -> Option<Parsed> { let mut parsed = Parsed::new(); let si = StrftimeItems::new(pattern); let res = parse(&mut parsed, value, si); match res { Ok(_) => { if parsed.year.is_none() { parsed.set_year(1970).unwrap(); } if parsed.month.is_none() { parsed.set_month(1).unwrap(); } if parsed.day.is_none() { parsed.set_day(1).unwrap(); } if parsed.hour_div_12.is_none() { parsed.set_hour(0).unwrap(); } if parsed.hour_mod_12.is_none() { parsed.set_hour(0).unwrap(); } if parsed.minute.is_none() { parsed.set_minute(0).unwrap(); } if parsed.second.is_none() { parsed.set_second(0).unwrap(); } if parsed.offset.is_none() { parsed.set_offset(0).unwrap(); } Some(parsed) } Err(e) => { let err_str = format!("unable to parse date-time string: {}", e); self.print_error(&err_str); None } } } /// Takes a datetime string and a strftime pattern as its /// arguments. Returns the parsed datetime string as a date-time /// object. The parsed datetime defaults to 1970-01-01 00:00:00, /// with components got via the strftime pattern applied on top of /// the default. pub fn core_strptime(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("strptime requires two arguments"); return 0; } let pat_rr = self.stack.pop().unwrap(); let pat_opt: Option<&str>; to_str!(pat_rr, pat_opt); let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match (str_opt, pat_opt) { (Some(st), Some(pat)) => { let parsed_opt = self.strptime(pat, st); match parsed_opt { Some(parsed) => { let dt_res = parsed.to_datetime().unwrap(); self.stack.push(Value::DateTimeOT(dt_res)); 1 } _ => 0, } } (Some(_), _) => { self.print_error("second strptime argument must be a string"); 0 } (..) => { self.print_error("first strptime argument must be a string"); 0 } } } /// Takes a datetime string, a strftime pattern, and a named /// timezone (per the tz database) as its arguments. Returns the /// parsed datetime string as a date-time object. The parsed /// datetime defaults to 1970-01-01 00:00:00, with components got /// via the strftime pattern applied on top of the default. pub fn core_strptimez(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("strptimez requires three arguments"); return 0; } let tz_rr = self.stack.pop().unwrap(); let tz_opt: Option<&str>; to_str!(tz_rr, tz_opt); let pat_rr = self.stack.pop().unwrap(); let pat_opt: Option<&str>; to_str!(pat_rr, pat_opt); let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match (str_opt, pat_opt, tz_opt) { (Some(st), Some(pat), Some(tzs)) => { let tzr = chrono_tz::Tz::from_str(tzs); match tzr { Ok(tz) => { let parsed_opt = self.strptime(pat, st); match parsed_opt { Some(parsed) => { let dt_res = parsed .to_naive_date() .unwrap() .and_time(parsed.to_naive_time().unwrap()); self.stack.push(Value::DateTimeNT( tz.from_local_datetime(&dt_res).unwrap(), )); 1 } _ => 0, } } _ => { self.print_error("third strptimez argument must be valid timezone"); 0 } } } (Some(_), Some(_), _) => { self.print_error("third strptimez argument must be string"); 0 } (Some(_), _, _) => { self.print_error("second strptimez argument must be string"); 0 } (..) => { self.print_error("first strptimez argument must be string"); 0 } } } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_env.rs
src/vm/vm_env.rs
use std::cell::RefCell; use std::env; use std::rc::Rc; use crate::hasher::new_hash_indexmap; use crate::vm::*; impl VM { /// Add a hash containing the data from the current environment to /// the stack. pub fn core_env(&mut self) -> i32 { let mut hsh = new_hash_indexmap(); for (key, value) in env::vars() { let value_str = new_string_value(value); hsh.insert(key, value_str); } let hsh_rr = Value::Hash(Rc::new(RefCell::new(hsh))); self.stack.push(hsh_rr); 1 } /// Takes an environment variable name as its argument. Puts the /// corresponding environment variable value onto the stack. If /// no such environment variable exists, puts null onto the stack. pub fn core_getenv(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("getenv requires one argument"); return 0; } let key_rr = self.stack.pop().unwrap(); let key_opt: Option<&str>; to_str!(key_rr, key_opt); match key_opt { Some(s) => { let value_res = env::var(s); match value_res { Ok(value) => { self.stack.push(new_string_value(value)); } _ => { /* Assume that inability to get an environment * variable means that the variable is not * set. */ self.stack.push(Value::Null); } } } _ => { self.print_error("getenv argument must be a string"); return 0; } } 1 } /// Takes an environment variable name and a value as its /// arguments. Sets the environment variable with the given name /// to have the given value. pub fn core_setenv(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("setenv requires two arguments"); return 0; } let value_rr = self.stack.pop().unwrap(); let key_rr = self.stack.pop().unwrap(); let key_opt: Option<&str>; to_str!(key_rr, key_opt); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match (key_opt, value_opt) { (Some(key_s), Some(value_s)) => { if key_s.is_empty() { self.print_error("first setenv argument must be a variable name"); return 0; } env::set_var(key_s, value_s); } (Some(_), _) => { self.print_error("second setenv argument must be a variable value"); return 0; } (_, _) => { self.print_error("first setenv argument must be a variable name"); return 0; } } 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_parallel.rs
src/vm/vm_parallel.rs
use std::os::fd::AsRawFd; use std::process::exit; use std::thread; use std::time; use epoll; use nix::sys::signal::Signal; use nix::sys::wait::waitpid; use nix::unistd::{fork, ForkResult}; use signal_hook::{consts::SIGTERM, iterator::Signals}; use std::fs::File; use std::io::Read; use std::io::Write; use nix::fcntl::fcntl; use nix::fcntl::FcntlArg::F_SETFL; use nix::fcntl::OFlag; use crate::chunk::{ChannelGenerator, ValueSD, value_to_valuesd, valuesd_to_value, read_valuesd, write_valuesd}; use crate::vm::*; /// The details for a subprocess created by way of pmap. pub struct Subprocess { /// The subprocess's process identifier. pub pid: nix::unistd::Pid, /// The filehandle for transmitting values to the subprocess. pub value_tx: std::fs::File, /// The filehandle for listening for requests from the subprocess /// for more values. pub reqvalue_rx: std::fs::File, } impl Subprocess { pub fn new(pid: nix::unistd::Pid, value_tx: std::fs::File, reqvalue_rx: std::fs::File) -> Subprocess { Subprocess { pid, value_tx, reqvalue_rx } } } fn make_pipe() -> Option<(std::fs::File, std::fs::File)> { let tx; let rx; match nix::unistd::pipe() { Ok((fd1, fd2)) => { fcntl(fd1.as_raw_fd(), F_SETFL(OFlag::O_NONBLOCK)).unwrap(); rx = File::from(fd1); tx = File::from(fd2); } Err(e) => { eprintln!("unable to create pipe: {}", e); return None; } } return Some((tx, rx)); } impl VM { /// Parallel map. pub fn core_pmap(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("pmap requires two arguments"); return 0; } return self.pmap_inner(4); } /// Parallel map with a specified number of processes. pub fn core_pmapn(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("pmapn requires three arguments"); return 0; } let procs_rr = self.stack.pop().unwrap(); let procs_int = procs_rr.to_int(); match procs_int { Some(n) => { if n < 1 { self.print_error("third pmapn argument must be positive integer"); return 0; } return self.pmap_inner(n as usize); } _ => { self.print_error("third pmapn argument must be integer"); return 0; } } } /// Core parallel map operation. pub fn pmap_inner(&mut self, procs: usize) -> i32 { let fn_rr = self.stack.pop().unwrap(); let gen_rr = self.stack.pop().unwrap(); /* For transmitting results back up (subprocesses to original * process). */ let (mut ptt_tx, ptt_rx) = make_pipe().unwrap(); unsafe { match fork() { Ok(ForkResult::Parent { child }) => { let cg_obj = ChannelGenerator::new(ptt_rx, child, gen_rr); let cg = Value::ChannelGenerator(Rc::new(RefCell::new(cg_obj))); self.stack.push(cg); self.child_processes.insert(child.as_raw() as u32, "parallel-operation".to_string()); return 1; } Ok(ForkResult::Child) => { let mut subprocesses = Vec::new(); for _ in 0..procs { let (value_tx, mut value_rx) = make_pipe().unwrap(); let (mut reqvalue_tx, reqvalue_rx) = make_pipe().unwrap(); match fork() { Ok(ForkResult::Parent { child }) => { subprocesses.push( Subprocess::new( child, value_tx, reqvalue_rx ) ); } Ok(ForkResult::Child) => { let sp_fn_rr = fn_rr.clone(); loop { /* The value used here doesn't matter, * as long as it's one byte in length. * */ match reqvalue_tx.write(b"1") { Ok(_) => {} Err(_) => { eprintln!("unable to send request byte"); exit(0); } } let mut vsd_res; let v; loop { vsd_res = read_valuesd(&mut value_rx); match vsd_res { None => { let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } Some(ValueSD::Null) => { exit(0); } _ => { v = valuesd_to_value(vsd_res.unwrap()); break; } } } self.stack.push(v); let res = self.call(OpCode::Call, sp_fn_rr.clone()); if !res || self.stack.is_empty() { let vsd = value_to_valuesd(Value::Null); write_valuesd(&mut ptt_tx, vsd); exit(0); } else { let nv = self.stack.pop().unwrap(); match nv { Value::Null => { let vsd = value_to_valuesd(Value::Null); write_valuesd(&mut ptt_tx, vsd); exit(0); } _ => {} } let vsd = value_to_valuesd(nv.clone()); match (&vsd, nv) { (&ValueSD::Null, Value::Null) => {} (&ValueSD::Null, _) => { self.print_error("unable to serialise value for pmap"); } _ => {} } write_valuesd(&mut ptt_tx, vsd); } } } Err(e) => { eprintln!("unable to fork: {}", e); exit(0); } } } let epoll_fd; let epoll_fd_res = epoll::create(true); match epoll_fd_res { Ok(epoll_fd_ok) => { epoll_fd = epoll_fd_ok; } Err(e) => { eprintln!("epoll create failed: {:?}", e); exit(0); } } for i in 0..procs { let fd = subprocesses.get(i).unwrap() .reqvalue_rx.as_raw_fd(); let res = epoll::ctl( epoll_fd, epoll::ControlOptions::EPOLL_CTL_ADD, fd, epoll::Event::new(epoll::Events::EPOLLIN, fd as u64) ); match res { Err(e) => { eprintln!("epoll ctl failed: {:?}", e); exit(0); } _ => {} } } let mut signals = Signals::new(&[SIGTERM]).unwrap(); let pids = subprocesses.iter().map(|e| e.pid).collect::<Vec<_>>(); thread::spawn(move || { for _ in signals.forever() { for i in pids.clone() { let res = nix::sys::signal::kill(i, Signal::SIGTERM); match res { Ok(_) => {} Err(nix::errno::Errno::ESRCH) => {} Err(e) => { eprintln!("unable to kill process: {}", e); } } } for i in pids { let res = waitpid(i, None); match res { /* Termination by way of the normal * process further down may have * happened by this time, so ignore * this error. */ Err(nix::errno::Errno::ECHILD) => {}, Err(e) => { eprintln!("unable to clean up process: {}", e); } _ => {} } } exit(0); } }); self.stack.push(gen_rr); let mut events = [epoll::Event::new(epoll::Events::empty(), 0); 50]; 'done: loop { let res = epoll::wait(epoll_fd, -1, &mut events); let n; match res { Err(e) => { /* Assuming that "Interrupted" is due * to ctrl-c, in which case there's no * need to show an error message. */ if !e.to_string().contains("Interrupted") { eprintln!("epoll wait failed: {:?}", e); } break 'done; } Ok(n_ok) => { n = n_ok; } } for i in 0..n { let event = events.get(i).unwrap(); for i in 0..procs { if subprocesses.get(i).unwrap().reqvalue_rx.as_raw_fd() == event.data as i32 { let subprocess = &mut subprocesses.get_mut(i).unwrap(); let mut size_buf = vec![0u8; 1]; let read_res = subprocess.reqvalue_rx.read_exact(&mut size_buf); if read_res.is_err() { break 'done; } read_res.unwrap(); let dup_res = self.opcode_dup(); if dup_res == 0 { break 'done; } let shift_res = self.opcode_shift(); if shift_res == 0 { break 'done; } let element_rr = self.stack.pop().unwrap(); match element_rr { Value::Null => { break 'done; } _ => { let vsd = value_to_valuesd(element_rr.clone()); match (&vsd, element_rr) { (&ValueSD::Null, Value::Null) => {} (&ValueSD::Null, _) => { self.print_error("unable to serialise value for pmap"); } _ => {} } write_valuesd(&mut subprocess.value_tx, vsd); } } break; } } } } self.stack.pop(); for i in 0..procs { write_valuesd(&mut subprocesses.get_mut(i).unwrap().value_tx, ValueSD::Null); } for i in 0..procs { let res = waitpid(subprocesses.get(i).unwrap().pid, None); match res { /* Termination by way of a signal may have * happened by this point, so ignore this * error. */ Err(nix::errno::Errno::ECHILD) => {}, Err(e) => { eprintln!("unable to clean up process: {}", e); } _ => {} } } write_valuesd(&mut ptt_tx, ValueSD::Null); exit(0); } Err(e) => { eprintln!("unable to fork: {}", e); exit(0); } } } } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_http.rs
src/vm/vm_http.rs
use std::cell::RefCell; use std::rc::Rc; use http::Method; use indexmap::IndexMap; use mime::Mime; use reqwest::blocking::{Client, Response, RequestBuilder}; use reqwest::header::CONTENT_TYPE; use std::sync::mpsc; use std::sync::mpsc::TryRecvError; use std::thread; use std::time; use url::Url; use crate::chunk::{Value, new_string_value}; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; impl VM { pub fn response_body_to_value(&mut self, response: Response) -> Value { let bytes_res = response.bytes(); match bytes_res { Ok(bytes) => { let s_res = String::from_utf8(bytes.to_vec()); match s_res { Ok(s) => { return new_string_value(s); } _ => { let mut lst = VecDeque::new(); for i in bytes { lst.push_back(Value::Byte(i)); } return Value::List(Rc::new(RefCell::new(lst))); } } } Err(e) => { let err_str = format!("unable to get response body: {}", e); self.print_error(&err_str); return Value::Null; } } } pub fn process_response(&mut self, response: Response) -> i32 { let headers = response.headers(); if let Some(content_type) = headers.get(CONTENT_TYPE) { if let Ok(ct_str) = content_type.to_str() { if let Ok(mct) = Mime::from_str(ct_str) { match (mct.subtype(), mct.suffix()) { (mime::JSON, _) | (_, Some(mime::JSON)) => { let text_res = response.text(); match text_res { Ok(text) => { self.stack.push(new_string_value(text)); return self.core_from_json(); } Err(e) => { let err_str = format!("unable to convert response to text: {}", e); self.print_error(&err_str); return 0; } } } (mime::XML, _) | (_, Some(mime::XML)) => { let text_res = response.text(); match text_res { Ok(text) => { self.stack.push(new_string_value(text)); return self.core_from_xml(); } Err(e) => { let err_str = format!("unable to convert response to text: {}", e); self.print_error(&err_str); return 0; } } } _ => {} } } } } let value = self.response_body_to_value(response); match value { Value::Null => { return 0; } _ => { self.stack.push(value); } } return 1; } pub fn send_request_simple(&mut self, url: &str) -> i32 { let client = Client::new(); let rb = client.request(Method::GET, url); let res = self.send_request(rb); match res { Some(response) => { return self.process_response(response); } _ => { return 0; } } } pub fn send_request(&mut self, mut rb: RequestBuilder) -> Option<Response> { rb = rb.header("User-Agent", format!("cosh/{}", env!("CARGO_PKG_VERSION"))); let (tx, rx) = mpsc::channel(); thread::spawn(move || { let response_res = rb.send(); let _ = tx.send(response_res); }); loop { let response_recv_res = rx.try_recv(); match response_recv_res { Ok(Ok(response)) => { return Some(response); } Ok(Err(e)) => { let err_str = format!("unable to send request: {}", e); self.print_error(&err_str); return None; } Err(TryRecvError::Disconnected) => { let err_str = format!("unable to send request: disconnected"); self.print_error(&err_str); return None; } Err(TryRecvError::Empty) => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return None; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } }; } pub fn core_http_get(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("http.get requires one argument"); return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { if !s.starts_with("http") { let s2 = "https://".to_owned() + s; self.send_request_simple(&s2) } else { self.send_request_simple(s) } } _ => { self.print_error("http.get argument must be a string"); 0 } } } pub fn core_http(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("http requires one argument"); return 0; } let args_rr = self.stack.pop().unwrap(); match args_rr { Value::Hash(map) => { let method; let url; let mapp = map.borrow(); let method_val_opt = mapp.get("method"); match method_val_opt { Some(method_val) => { let method_str_opt: Option<&str>; to_str!(method_val, method_str_opt); match method_str_opt { Some(method_str) => { let method_str_uc = method_str.to_ascii_uppercase(); let method_obj_opt = Method::from_str(&method_str_uc); match method_obj_opt { Ok(method_obj) => { method = method_obj; } _ => { self.print_error("HTTP method is invalid"); return 0; } } } _ => { self.print_error("HTTP method must be string"); return 0; } } } _ => { method = Method::GET; } } let url_val_opt = mapp.get("url"); match url_val_opt { Some(url_val) => { let url_str_opt: Option<&str>; to_str!(url_val, url_str_opt); match url_str_opt { Some(url_str) => { let url_obj_opt = if !url_str.starts_with("http") { let url_str2 = "https://".to_owned() + url_str; Url::parse(&url_str2) } else { Url::parse(url_str) }; match url_obj_opt { Ok(url_obj) => { url = url_obj; } _ => { self.print_error("HTTP URL is invalid"); return 0; } } } _ => { self.print_error("HTTP URL must be string"); return 0; } } } _ => { self.print_error("http hash argument must contain URL"); return 0; } } let raw_val_opt = mapp.get("raw"); let mut raw = false; match raw_val_opt { Some(raw_val) => { raw = raw_val.to_bool(); } _ => {} } let redirect_body_val_opt = mapp.get("redirect-body"); let mut redirect_body = false; match redirect_body_val_opt { Some(redirect_body_val) => { redirect_body = redirect_body_val.to_bool(); } _ => {} } let client = if redirect_body { // Create client that doesn't follow redirects Client::builder() .redirect(reqwest::redirect::Policy::none()) .build() .unwrap() } else { Client::new() }; let mut rb = client.request(method, url); let mut is_json = false; let mut is_xml = false; rb = rb.header("User-Agent", format!("cosh/{}", env!("CARGO_PKG_VERSION"))); let headers_val_opt = mapp.get("headers"); match headers_val_opt { Some(headers_val) => { match headers_val { Value::Hash(hmap) => { let hmapp = hmap.borrow(); for (k, v) in hmapp.iter() { let v_str_opt: Option<&str>; to_str!(v, v_str_opt); match v_str_opt { Some(v_str) => { rb = rb.header(k, v_str); if k.to_ascii_lowercase() == "content-type" { let ct_str_opt = Some(v_str); if let Some(ct_str) = ct_str_opt { if let Ok(mct) = Mime::from_str(ct_str) { match (mct.subtype(), mct.suffix()) { (mime::JSON, _) | (_, Some(mime::JSON)) => { is_json = true; } (mime::XML, _) | (_, Some(mime::XML)) => { is_xml = true; } _ => {} } } } } } _ => { self.print_error("HTTP header value must be string"); return 0; } } } } _ => { self.print_error("HTTP headers must be hash"); return 0; } } } _ => {} } let body_val_opt = mapp.get("body"); match body_val_opt { Some(body_val) => { if is_json { self.stack.push(body_val.clone()); let res = self.core_to_json(); if res == 0 { return res; } let body_val_encoded = self.stack.pop().unwrap(); let body_str_opt: Option<&str>; to_str!(body_val_encoded, body_str_opt); match body_str_opt { Some(body_str) => { rb = rb.body(body_str.to_string()); } _ => { self.print_error("unable to process body"); return 0; } } } else if is_xml { self.stack.push(body_val.clone()); let res = self.core_to_xml(); if res == 0 { return res; } let body_val_encoded = self.stack.pop().unwrap(); let body_str_opt: Option<&str>; to_str!(body_val_encoded, body_str_opt); match body_str_opt { Some(body_str) => { rb = rb.body(body_str.to_string()); } _ => { self.print_error("unable to process body"); return 0; } } } else { let body_str_opt: Option<&str>; to_str!(body_val, body_str_opt); match body_str_opt { Some(body_str) => { rb = rb.body(body_str.to_string()); } _ => { self.print_error("unable to process body"); return 0; } } } } _ => {} } let response_res = self.send_request(rb); match response_res { Some(response) => { if raw { let mut headers = new_hash_indexmap(); for (k, v) in response.headers().iter() { headers.insert(k.to_string(), new_string_value((*v).to_str().unwrap().to_string())); } let mut result = new_hash_indexmap(); result.insert("headers".to_string(), Value::Hash(Rc::new(RefCell::new(headers)))); result.insert("code".to_string(), Value::Int(response.status().as_u16() as i32)); let value = self.response_body_to_value(response); result.insert("body".to_string(), value); let hv = Value::Hash(Rc::new(RefCell::new(result))); self.stack.push(hv); } else { self.process_response(response); } 1 } _ => { 0 } } } _ => { self.print_error("http argument must be hash"); 0 } } } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_regex.rs
src/vm/vm_regex.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use regex::Regex; use crate::chunk::Value; use crate::vm::*; lazy_static! { static ref RE_ADJUST: Regex = Regex::new(r"\\([\d+])").unwrap(); } impl VM { /// Takes a value that can be stringified and a regex string as /// its arguments. Tests whether the value matches as against the /// regex and puts a boolean onto the stack accordingly. pub fn core_m(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("m requires two arguments"); return 0; } let regex_rr = self.stack.pop().unwrap(); let regex_opt = self.gen_regex(regex_rr); if regex_opt.is_none() { return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match (regex_opt, str_opt) { (Some((regex, _)), Some(s)) => { let res = regex.is_match(s); self.stack.push(Value::Bool(res)); } (_, Some(_)) => { self.print_error("first m argument must be string"); return 0; } (_, _) => { self.print_error("second m argument must be string"); return 0; } } 1 } /// Takes a value that can be stringified, a regex string, and a /// replacement string as its arguments. Runs a /// search-and-replace against the string based on the regex, and /// puts the resulting string onto the stack. pub fn core_s(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("s requires three arguments"); return 0; } let repl_rr = self.stack.pop().unwrap(); let repl_str_rr_opt = VM::to_string_value(repl_rr); if repl_str_rr_opt.is_none() { self.print_error("third s argument must be a string"); return 0; } let repl_str_rr = repl_str_rr_opt.unwrap(); let regex_rr = self.stack.pop().unwrap(); let regex_opt = self.gen_regex(regex_rr); if regex_opt.is_none() { return 0; } let repl_str_opt: Option<&str>; to_str!(repl_str_rr, repl_str_opt); let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match (repl_str_opt, regex_opt, str_opt) { (Some(repl_str), Some((regex, global)), Some(s)) => { let updated_repl = RE_ADJUST.replace_all(repl_str, "$${$1}"); let updated_repl_str = updated_repl.to_string(); let updated_str = if global { regex.replace_all(s, &updated_repl_str[..]) } else { regex.replace(s, &updated_repl_str[..]) }; self.stack.push(new_string_value(updated_str.to_string())); } (_, Some(_), Some(_)) => { self.print_error("third s argument must be string"); return 0; } (_, _, Some(_)) => { self.print_error("second s argument must be string"); return 0; } (_, _, _) => { self.print_error("first s argument must be string"); return 0; } } 1 } /// Takes a value that can be stringified and a regex string as /// its arguments. Gets the regex captures from the value, puts /// them into a list, and then puts that list onto the stack. pub fn core_c(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("c requires two arguments"); return 0; } let regex_rr = self.stack.pop().unwrap(); let regex_opt = self.gen_regex(regex_rr); if regex_opt.is_none() { return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match (regex_opt, str_opt) { (Some((regex, global)), Some(s)) => { if global { let captures = regex.captures_iter(s); let mut lst = VecDeque::new(); for capture in captures { let mut sublst = VecDeque::new(); for subcapture in capture.iter() { sublst.push_back( new_string_value( subcapture.unwrap().as_str().to_string() ) ); } lst.push_back(Value::List(Rc::new(RefCell::new(sublst)))); } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } else { let captures = regex.captures(s); let mut lst = VecDeque::new(); if let Some(capture) = captures { for subcapture in capture.iter() { lst.push_back( new_string_value( subcapture.unwrap().as_str().to_string() ) ); } } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } } (Some(_), _) => { self.print_error("first c argument must be string"); return 0; } (_, _) => { self.print_error("second c argument must be string"); return 0; } } 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_hash.rs
src/vm/vm_hash.rs
use std::cell::RefCell; use std::rc::Rc; use crate::chunk::{HashWithIndex, Value, new_string_value}; use crate::vm::*; impl VM { /// Takes a hash or list (or generator) and a key string or list /// index (or list of keys/indexes) as its arguments. Puts the /// specified value (or list of values) onto the stack, or the /// null value if the specified value (or list of values) doesn't /// exist. pub fn core_get(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("get requires two arguments"); return 0; } let specifier_rr = self.stack.pop().unwrap(); let object_rr = self.stack.pop().unwrap(); if object_rr.is_generator() { self.stack.push(object_rr); let res = self.generator_to_list(); if res == 0 { return 0; } self.stack.push(specifier_rr); return self.core_get(); } let specifier_opt: Option<&str>; to_str!(specifier_rr.clone(), specifier_opt); match (object_rr.clone(), specifier_opt) { (Value::Hash(map), Some(s)) => { let mapp = map.borrow(); let v = mapp.get(s); match v { Some(r) => { self.stack.push(r.clone()); } None => { let pos = s.chars().position(|c| c == '.'); match pos { Some(n) => { let first_key = &s[..n]; let first_opt = mapp.get(first_key); match first_opt { Some(first) => { let rest_specifier = &s[n+1..]; let rest_specifier_value = new_string_value(rest_specifier.to_string()); self.stack.push(first.clone()); self.stack.push(rest_specifier_value); return self.core_get(); } _ => { self.stack.push(Value::Null); } } } _ => { self.stack.push(Value::Null); } } } } } (Value::Hash(map), None) => { match specifier_rr { Value::List(lst) => { let mapb = map.borrow(); let mut results = VecDeque::new(); for e in lst.borrow().iter() { let e_opt: Option<&str>; to_str!(e, e_opt); if let Some(s) = e_opt { let v = mapb.get(s); match v { Some(r) => { results.push_back(r.clone()); } None => { let sv = new_string_value(s.to_string()); self.stack.push(object_rr.clone()); self.stack.push(sv); let res = self.core_get(); if res == 1 { results.push_back(self.stack.pop().unwrap()); } else { results.push_back(Value::Null); } } } } else { self.print_error("second get argument must be list of strings"); return 0; } } let newlst = Value::List(Rc::new(RefCell::new(results))); self.stack.push(newlst); return 1; } _ => { self.print_error("second get argument must be field specifier"); return 0; } } } (Value::List(lst), _) => { let num_int_opt = specifier_rr.to_int(); if let Some(n) = num_int_opt { if let Some(s) = specifier_opt { let pos = s.chars().position(|c| c == '.'); if pos.is_none() { if lst.borrow().len() <= (n as usize) { self.stack.push(Value::Null); return 1; } let element = lst.borrow()[n as usize].clone(); self.stack.push(element); return 1; } } } match specifier_rr { Value::List(ilst) => { let lstb = lst.borrow(); let mut results = VecDeque::new(); for e in ilst.borrow().iter() { let e_opt = e.to_int(); if let Some(n) = e_opt { if lstb.len() <= (n as usize) { results.push_back(Value::Null); } else { results.push_back(lstb[n as usize].clone()); } } else { self.stack.push(object_rr.clone()); self.stack.push(e.clone()); let res = self.core_get(); if res == 1 { results.push_back(self.stack.pop().unwrap()); } else { return 0; } } } let newlst = Value::List(Rc::new(RefCell::new(results))); self.stack.push(newlst); return 1; } _ => { if let Some(s) = specifier_opt { let pos = s.chars().position(|c| c == '.'); match pos { Some(n) => { let first_key = &s[..n]; match first_key.parse::<usize>() { Ok(nn) => { let lstb = lst.borrow(); if lstb.len() <= nn { self.stack.push(Value::Null); } else { let rest_specifier = &s[n+1..]; let rest_specifier_value = new_string_value(rest_specifier.to_string()); self.stack.push(lstb[nn].clone()); self.stack.push(rest_specifier_value); let res = self.core_get(); if res == 1 { return 1; } else { return 0; } } } _ => { self.print_error("second get argument must be field specifier"); return 0; } } } _ => { self.print_error("second get argument must be field specifier"); return 0; } } } else { self.print_error("second get argument must be field specifier"); return 0; } } } } (Value::Set(set), _) => { let num_int_opt = specifier_rr.to_int(); if let Some(n) = num_int_opt { if let Some(s) = specifier_opt { let pos = s.chars().position(|c| c == '.'); if pos.is_none() { if set.borrow().len() <= (n as usize) { self.stack.push(Value::Null); return 1; } let element = set.borrow()[n as usize].clone(); self.stack.push(element); return 1; } } } match specifier_rr { Value::List(ilst) => { let setb = set.borrow(); let mut results = VecDeque::new(); for e in ilst.borrow().iter() { let e_opt = e.to_int(); if let Some(n) = e_opt { if setb.len() <= (n as usize) { results.push_back(Value::Null); } else { results.push_back(setb[n as usize].clone()); } } else { self.stack.push(object_rr.clone()); self.stack.push(e.clone()); let res = self.core_get(); if res == 1 { results.push_back(self.stack.pop().unwrap()); } else { return 0; } } } let newlst = Value::List(Rc::new(RefCell::new(results))); self.stack.push(newlst); return 1; } _ => { self.print_error("second get argument must be field specifier"); return 0; } } } (Value::IpSet(set), _) => { let num_int_opt = specifier_rr.to_int(); if let Some(n) = num_int_opt { if let Some(s) = specifier_opt { let pos = s.chars().position(|c| c == '.'); if pos.is_none() { self.stack.push(set.borrow().get(n as usize)); return 1; } } } match specifier_rr { Value::List(ilst) => { let setb = set.borrow(); let mut results = VecDeque::new(); for e in ilst.borrow().iter() { let e_opt = e.to_int(); if let Some(n) = e_opt { self.stack.push(setb.get(n as usize)); } else { self.stack.push(object_rr.clone()); self.stack.push(e.clone()); let res = self.core_get(); if res == 1 { results.push_back(self.stack.pop().unwrap()); } else { return 0; } } } let newlst = Value::List(Rc::new(RefCell::new(results))); self.stack.push(newlst); return 1; } _ => { self.print_error("second get argument must be field specifier"); return 0; } } } _ => { self.print_error("first get argument must be list/hash/set"); return 0; } } 1 } /// Takes a set or hash value and a key string or element value as /// its arguments. For a hash, removes the value recorded against /// the hash key from the hash. For a set, removes the element /// from the set. pub fn core_delete(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("delete requires two arguments"); return 0; } let key_str_rr = self.stack.pop().unwrap(); let key_str_opt: Option<&str>; to_str!(key_str_rr, key_str_opt); if key_str_opt.is_none() { self.print_error("second delete argument must be string"); return 0; } let key_str = key_str_opt.unwrap(); let object_rr = self.stack.pop().unwrap(); match object_rr { Value::Hash(map) => { let mut mapp = map.borrow_mut(); mapp.remove(key_str); } Value::Set(map) => { let mut mapp = map.borrow_mut(); mapp.remove(key_str); } _ => { self.print_error("first delete argument must be set/hash"); return 0; } } 1 } /// Takes a set or hash value and a key string or element value as /// its arguments. Returns a boolean indicating whether the set /// or hash value contains the specified key/element. pub fn core_exists(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("exists requires two arguments"); return 0; } let key_str_rr = self.stack.pop().unwrap(); let key_str_opt: Option<&str>; to_str!(key_str_rr, key_str_opt); if key_str_opt.is_none() { self.print_error("second exists argument must be string"); return 0; } let key_str = key_str_opt.unwrap(); let object_rr = self.stack.pop().unwrap(); match object_rr { Value::Hash(map) => { let mapp = map.borrow(); let res = mapp.contains_key(key_str); self.stack.push(Value::Bool(res)); } Value::Set(map) => { let mapp = map.borrow(); let res = mapp.contains_key(key_str); self.stack.push(Value::Bool(res)); } _ => { self.print_error("first exists argument must be set/hash"); return 0; } } 1 } /// Takes a hash value, a key string, and a value as its /// arguments. Puts the value into the hash against the specified /// key, and puts the updated hash back onto the stack. pub fn core_set(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("set requires three arguments"); return 0; } let val_rr = self.stack.pop().unwrap(); let specifier_rr = self.stack.pop().unwrap(); let specifier_opt: Option<&str>; to_str!(specifier_rr.clone(), specifier_opt); let mut object_rr = self.stack.pop().unwrap(); { match (&mut object_rr, specifier_opt) { (Value::Hash(map), Some(s)) => { map.borrow_mut().insert(s.to_string(), val_rr); } (Value::Hash(_), None) => { self.print_error("second set argument must be key string"); } (Value::List(lst), _) => { let num_int_opt = specifier_rr.to_int(); match num_int_opt { Some(n) => { if lst.borrow().len() <= (n as usize) { self.print_error("second set argument must fall within list bounds"); return 0; } lst.borrow_mut()[n as usize] = val_rr; } _ => { if let Some(s) = specifier_opt { let pos = s.chars().position(|c| c == '.'); match pos { Some(n) => { let first_key = &s[..n]; match first_key.parse::<usize>() { Ok(nn) => { let lstb = lst.borrow(); if lstb.len() <= nn { self.print_error("second set argument must fall within list bounds"); return 0; } else { let rest_specifier = &s[n+1..]; let rest_specifier_value = new_string_value(rest_specifier.to_string()); let nested_element = lstb[nn].clone(); drop(lstb); // Release the borrow before recursive call self.stack.push(nested_element); self.stack.push(rest_specifier_value); self.stack.push(val_rr); let res = self.core_set(); if res == 1 { if self.stack.is_empty() { return 0; } let updated_element = self.stack.pop().unwrap(); lst.borrow_mut()[nn] = updated_element; } else { return 0; } } } _ => { self.print_error("second set argument must be field specifier"); } } } _ => { self.print_error("second set argument must be field specifier"); } } } else { self.print_error("second set argument must be field specifier"); } } } } _ => { self.print_error("first set argument must be list/hash"); return 0; } } } self.stack.push(object_rr); 1 } /// Takes a hash value and returns a generator over the keys of /// the hash. pub fn core_keys(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("keys requires one argument"); return 0; } let hash_rr = self.stack.pop().unwrap(); let is_hash; { match hash_rr { Value::Hash(_) => { is_hash = true; } _ => { self.print_error("keys argument must be hash"); return 0; } } } if is_hash { self.stack.push(Value::KeysGenerator(Rc::new(RefCell::new( HashWithIndex::new(0, hash_rr), )))); } 1 } /// Takes a hash value and returns a generator over the values of /// the hash. pub fn core_values(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("values requires one argument"); return 0; } let hash_rr = self.stack.pop().unwrap(); let is_hash; { match hash_rr { Value::Hash(_) => { is_hash = true; } _ => { self.print_error("values argument must be hash"); return 0; } } } if is_hash { self.stack.push(Value::ValuesGenerator(Rc::new(RefCell::new( HashWithIndex::new(0, hash_rr), )))); } 1 } /// Takes a hash value and returns a generator over the key-value /// pairs from that hash. pub fn core_each(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("each requires one argument"); return 0; } let hash_rr = self.stack.pop().unwrap(); let is_hash; { match hash_rr { Value::Hash(_) => { is_hash = true; } _ => { self.print_error("each argument must be hash"); return 0; } } } if is_hash { self.stack.push(Value::EachGenerator(Rc::new(RefCell::new( HashWithIndex::new(0, hash_rr), )))); } 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_digest.rs
src/vm/vm_digest.rs
use sha1::{Digest, Sha1}; use sha2::{Sha256, Sha512}; use crate::chunk::Value; use crate::vm::*; impl VM { /// Takes a string as its single argument. Hashes the string /// using the MD5 algorithm and adds the result to the stack. pub fn core_md5(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("md5 requires one argument"); return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { let digest = md5::compute(s.as_bytes()); let mut byte_list = VecDeque::new(); for byte in digest.into_iter() { byte_list.push_back(Value::Byte(byte)); } self.stack.push(Value::List(Rc::new(RefCell::new(byte_list)))); } _ => { self.print_error("md5 argument must be string"); return 0; } } 1 } /// Takes a string as its single argument. Hashes the string /// using the SHA1 algorithm and adds the result to the stack. pub fn core_sha1(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sha1 requires one argument"); return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { let mut hasher = Sha1::new(); hasher.update(s.as_bytes()); let digest = hasher.finalize(); let mut byte_list = VecDeque::new(); for byte in digest.into_iter() { byte_list.push_back(Value::Byte(byte)); } self.stack.push(Value::List(Rc::new(RefCell::new(byte_list)))); } _ => { self.print_error("sha1 argument must be string"); return 0; } } 1 } /// Takes a string as its single argument. Hashes the string /// using the SHA256 algorithm and adds the result to the stack. pub fn core_sha256(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sha256 requires one argument"); return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { let mut hasher = Sha256::new(); hasher.update(s.as_bytes()); let digest = hasher.finalize(); let mut byte_list = VecDeque::new(); for byte in digest.into_iter() { byte_list.push_back(Value::Byte(byte)); } self.stack.push(Value::List(Rc::new(RefCell::new(byte_list)))); } _ => { self.print_error("sha1 argument must be string"); return 0; } } 1 } /// Takes a string as its single argument. Hashes the string /// using the SHA512 algorithm and adds the result to the stack. pub fn core_sha512(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sha512 requires one argument"); return 0; } let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { let mut hasher = Sha512::new(); hasher.update(s.as_bytes()); let digest = hasher.finalize(); let mut byte_list = VecDeque::new(); for byte in digest.into_iter() { byte_list.push_back(Value::Byte(byte)); } self.stack.push(Value::List(Rc::new(RefCell::new(byte_list)))); } _ => { self.print_error("sha1 argument must be string"); return 0; } } 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_dns.rs
src/vm/vm_dns.rs
use std::cell::RefCell; use std::net::SocketAddr; use std::rc::Rc; use std::sync::mpsc; use std::sync::mpsc::TryRecvError; use std::thread; use std::time; use hickory_client::client::Client; use hickory_client::client::SyncClient; use hickory_client::op::ResponseCode; use hickory_client::rr::Record; use hickory_client::rr::RecordType; use hickory_client::udp::UdpClientConnection; use crate::chunk::{Value, new_string_value}; use crate::hasher::{new_hash_indexmap, new_set_indexmap, CoshIndexMap}; use crate::vm::*; impl VM { /// Add the given string to the map as a bigint, unless it can't /// be parsed, in which case add it as a string. pub fn add_bi(&mut self, map: &mut CoshIndexMap<String, Value>, key: &str, value: &str) { let bi_opt = value.parse::<num_bigint::BigInt>(); match bi_opt { Ok(bi) => { map.insert(key.to_string(), Value::BigInt(bi)); } _ => { map.insert(key.to_string(), new_string_value(value.to_string())); } } } /// Add the given string to the map as an int, unless it can't /// be parsed, in which case add it as a string. pub fn add_int(&mut self, map: &mut CoshIndexMap<String, Value>, key: &str, value: &str) { let int_opt = value.parse::<i32>(); match int_opt { Ok(int) => { map.insert(key.to_string(), Value::Int(int)); } _ => { map.insert(key.to_string(), new_string_value(value.to_string())); } } } /// Convert the DNS record into a hash. pub fn record_to_value(&mut self, record: &Record) -> Value { let mut record_map = new_hash_indexmap(); record_map.insert( "name".to_string(), new_string_value(record.name().to_string()) ); record_map.insert( "ttl".to_string(), Value::BigInt(record.ttl().try_into().unwrap()) ); record_map.insert( "class".to_string(), new_string_value("IN".to_string()) ); record_map.insert( "type".to_string(), new_string_value(record.record_type().to_string()) ); match record.data() { Some(d) => { record_map.insert( "rdata".to_string(), new_string_value(d.to_string()) ); } _ => {} } let mut sdata_map = new_hash_indexmap(); match record.record_type() { RecordType::A => { sdata_map.insert( "address".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::AAAA => { sdata_map.insert( "address".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::NS => { sdata_map.insert( "nsdname".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::CNAME => { sdata_map.insert( "cname".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::PTR => { sdata_map.insert( "ptrdname".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::TXT => { sdata_map.insert( "txtdata".to_string(), new_string_value(record.data().unwrap().to_string()) ); } RecordType::MX => { let rdstr = record.data().unwrap().to_string(); let parts: Vec<&str> = rdstr.split_whitespace().collect(); sdata_map.insert( "preference".to_string(), new_string_value(parts.get(0).unwrap().to_string()) ); sdata_map.insert( "exchange".to_string(), new_string_value(parts.get(1).unwrap().to_string()) ); } RecordType::SOA => { let rdstr = record.data().unwrap().to_string(); let parts: Vec<&str> = rdstr.split_whitespace().collect(); sdata_map.insert( "mname".to_string(), new_string_value(parts.get(0).unwrap().to_string()) ); sdata_map.insert( "rname".to_string(), new_string_value(parts.get(1).unwrap().to_string()) ); self.add_bi(&mut sdata_map, "serial", parts.get(2).unwrap()); self.add_bi(&mut sdata_map, "refresh", parts.get(3).unwrap()); self.add_bi(&mut sdata_map, "retry", parts.get(4).unwrap()); self.add_bi(&mut sdata_map, "expire", parts.get(5).unwrap()); self.add_bi(&mut sdata_map, "minimum", parts.get(6).unwrap()); } RecordType::DS => { let rdstr = record.data().unwrap().to_string(); let parts: Vec<&str> = rdstr.split_whitespace().collect(); self.add_int(&mut sdata_map, "keytag", parts.get(0).unwrap()); self.add_int(&mut sdata_map, "algorithm", parts.get(1).unwrap()); self.add_int(&mut sdata_map, "digtype", parts.get(2).unwrap()); sdata_map.insert( "digest".to_string(), new_string_value(parts.get(3).unwrap().to_string()) ); } RecordType::DNSKEY => { let rdstr = record.data().unwrap().to_string(); let parts: Vec<&str> = rdstr.split_whitespace().collect(); self.add_int(&mut sdata_map, "flags", parts.get(0).unwrap()); self.add_int(&mut sdata_map, "protocol", parts.get(1).unwrap()); self.add_int(&mut sdata_map, "algorithm", parts.get(2).unwrap()); sdata_map.insert( "keybin".to_string(), new_string_value(parts.get(3).unwrap().to_string()) ); } _ => {} } if sdata_map.len() > 0 { record_map.insert( "sdata".to_string(), Value::Hash(Rc::new(RefCell::new(sdata_map))) ); } return Value::Hash(Rc::new(RefCell::new(record_map))); } /// Query for DNS records at a specific server. pub fn core_dnsat(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("dnsat requires three arguments"); return 0; } let type_rr = self.stack.pop().unwrap(); let query_rr = self.stack.pop().unwrap(); let server_rr = self.stack.pop().unwrap(); let type_opt: Option<&str>; to_str!(type_rr, type_opt); let query_opt: Option<&str>; to_str!(query_rr, query_opt); let server_opt: Option<&str>; to_str!(server_rr, server_opt); match (type_opt, query_opt, server_opt) { (Some(type_str), Some(query), Some(server)) => { let addr_opt = std::net::IpAddr::from_str(server); let addr_to_use = match addr_opt { Ok(std::net::IpAddr::V4(addr)) => { SocketAddr::new(std::net::IpAddr::V4(addr), 53) } Ok(std::net::IpAddr::V6(addr)) => { SocketAddr::new(std::net::IpAddr::V6(addr), 53) } Err(_) => { self.print_error("unable to parse IP address"); return 0; } }; let query_so = query.to_string(); let type_str_so = type_str.to_string(); let uc_type_str = type_str_so.to_uppercase(); let record_type_opt = hickory_client::rr::RecordType::from_str(&uc_type_str); if let Err(_) = record_type_opt { self.print_error("invalid DNS record type"); return 0; } let record_type = record_type_opt.unwrap(); let name_opt = hickory_client::rr::Name::from_ascii(query_so); if let Err(_) = name_opt { self.print_error("invalid DNS name"); return 0; } let name = name_opt.unwrap(); let (tx, rx) = mpsc::channel(); thread::spawn(move || { let client = SyncClient::new( UdpClientConnection::new(addr_to_use).unwrap() ); let res = client.query( &name, hickory_client::rr::DNSClass::IN, record_type ); let _ = tx.send(res); }); let resp; loop { let response_recv_res = rx.try_recv(); match response_recv_res { Ok(Ok(response)) => { resp = response; break; } Ok(Err(e)) => { let err_str = format!("unable to send request: {}", e); self.print_error(&err_str); return 0; } Err(TryRecvError::Disconnected) => { let err_str = format!("unable to send request: disconnected"); self.print_error(&err_str); return 0; } Err(TryRecvError::Empty) => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } } let mut header_map = new_hash_indexmap(); header_map.insert( "opcode".to_string(), new_string_value(resp.op_code().to_string().to_uppercase()) ); let status_str = match resp.response_code() { ResponseCode::NoError => "NOERROR", ResponseCode::FormErr => "FORMERR", ResponseCode::ServFail => "SERVFAIL", ResponseCode::NXDomain => "NXDOMAIN", ResponseCode::NotImp => "NOTIMP", ResponseCode::Refused => "REFUSED", ResponseCode::YXDomain => "YXDOMAIN", ResponseCode::YXRRSet => "YXRRSET", ResponseCode::NXRRSet => "NXRRSET", ResponseCode::NotAuth => "NOTAUTH", ResponseCode::NotZone => "NOTZONE", _ => "UNKNOWN" }; header_map.insert( "status".to_string(), new_string_value(status_str.to_string()) ); header_map.insert( "id".to_string(), Value::Int(resp.id() as i32) ); let mut question_map = new_hash_indexmap(); question_map.insert( "name".to_string(), new_string_value(query.to_string()) ); question_map.insert( "type".to_string(), new_string_value("IN".to_string()) ); question_map.insert( "class".to_string(), new_string_value(type_str.to_string()) ); let mut answer_lst = VecDeque::new(); for record in resp.answers() { answer_lst.push_back(self.record_to_value(&record)); } let mut authority_lst = VecDeque::new(); for record in resp.name_servers() { if record.record_type() == RecordType::SOA { authority_lst.push_back(self.record_to_value(&record)); } } let mut additional_lst = VecDeque::new(); for record in resp.additionals() { additional_lst.push_back(self.record_to_value(&record)); } let mut res_map = new_hash_indexmap(); res_map.insert( "header".to_string(), Value::Hash(Rc::new(RefCell::new(header_map))) ); res_map.insert( "question".to_string(), Value::Hash(Rc::new(RefCell::new(question_map))) ); if answer_lst.len() > 0 { res_map.insert( "answer".to_string(), Value::List(Rc::new(RefCell::new(answer_lst))) ); } if authority_lst.len() > 0 { res_map.insert( "authority".to_string(), Value::List(Rc::new(RefCell::new(authority_lst))) ); } if additional_lst.len() > 0 { res_map.insert( "additional".to_string(), Value::List(Rc::new(RefCell::new(additional_lst))) ); } self.stack.push(Value::Hash(Rc::new(RefCell::new(res_map)))); return 1; } _ => { self.print_error("dns requires two string arguments"); return 0; } } } /// Query for DNS records at the default server. pub fn core_dns(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("dns requires three arguments"); return 0; } let type_rr = self.stack.pop().unwrap(); let query_rr = self.stack.pop().unwrap(); self.refresh_dns_servers_if_necessary(); let server_addr = self.dns_servers.get(0); if let None = server_addr { self.print_error("unable to find default server for dns"); return 0; } let server_rr = new_string_value(server_addr.unwrap().to_string()); self.stack.push(server_rr); self.stack.push(query_rr); self.stack.push(type_rr); return self.core_dnsat(); } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_system.rs
src/vm/vm_system.rs
use nix::sys::signal::Signal; use nix::unistd::{Group, Pid, User}; use std::cell::RefCell; use std::collections::HashSet; use std::collections::VecDeque; use std::convert::TryFrom; use std::env; use std::fs; use std::io; use std::os::unix::fs::MetadataExt; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::rc::Rc; use std::time::SystemTime; use chrono::{DateTime, NaiveDateTime, Utc}; use indexmap::IndexMap; use num::FromPrimitive; use num_bigint::BigInt; use sysinfo::CpuRefreshKind; use utime::*; use crate::chunk::Value; use crate::hasher::{new_hash_indexmap, CoshIndexMap}; use crate::vm::*; impl VM { /// From https://stackoverflow.com/a/65192210. fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<u64> { fs::create_dir_all(&dst)?; for entry in fs::read_dir(src)? { let entry = entry?; let ty = entry.file_type()?; if ty.is_dir() { VM::copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?; } else { std::fs::copy(entry.path(), dst.as_ref().join(entry.file_name()))?; } } Ok(1) } /// Takes a value that can be stringified as its single argument. /// Removes the file corresponding to that path. pub fn core_rm(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("rm requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let ss = VM::expand_tilde(s); let res = std::fs::remove_file(ss); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to remove file: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("rm argument must be a string"); return 0; } } 1 } /// Takes a value that can be stringified as its single argument. /// Removes the file corresponding to that path. Unlike core_rm, /// this will not report an error if the file does not exist. pub fn core_rmf(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("rmf requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let ss = VM::expand_tilde(s); let path = Path::new(&ss); if path.exists() { let res = std::fs::remove_file(ss); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to remove file: {}", e); self.print_error(&err_str); return 0; } } } } _ => { self.print_error("rmf argument must be a string"); return 0; } } 1 } /// Takes a value that can be stringified as its single argument. /// Removes the file/directory corresponding to that path. If the /// path maps to a directory, then the contents of the directory /// will be removed as well. Unlike core_rm, this will not report /// an error if the file does not exist. pub fn core_rmrf(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("rmrf requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let ss = VM::expand_tilde(s); let path = Path::new(&ss); if path.exists() { let res = std::fs::remove_dir_all(ss); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to remove file/directory: {}", e); self.print_error(&err_str); return 0; } } } } _ => { self.print_error("rmrf argument must be a string"); return 0; } } 1 } /// Takes two values that can be stringified as its arguments. /// Copies the file corresponding to the first path to the second /// path. pub fn core_cp(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("cp requires two arguments"); return 0; } let dst_rr = self.stack.pop().unwrap(); let dst_opt: Option<&str>; to_str!(dst_rr, dst_opt); let src_rr = self.stack.pop().unwrap(); let src_opt: Option<&str>; to_str!(src_rr, src_opt); match (src_opt, dst_opt) { (Some(src), Some(dst)) => { let srcs = VM::expand_tilde(src); let dsts = VM::expand_tilde(dst); let src_meta_opt = fs::metadata(&srcs); let use_copy_dir = match src_meta_opt { Ok(src_meta) => { src_meta.is_dir() } _ => { self.print_error("unable to stat file"); return 0; } }; let dst_meta_opt = fs::metadata(&dsts); let dst_path = if !dst_meta_opt.is_err() { let dst_meta = dst_meta_opt.unwrap(); if dst_meta.is_dir() { let src_path = Path::new(&srcs); let file_name = src_path.file_name(); match file_name { Some(s) => { format!("{}/{}", dsts, s.to_str().unwrap()) } None => { self.print_error("unable to copy directory to directory"); return 0; } } } else { dsts.to_string() } } else { dsts.to_string() }; let res = if use_copy_dir { VM::copy_dir_all(srcs, dst_path) } else { std::fs::copy(srcs, dst_path) }; match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to copy file: {}", e); self.print_error(&err_str); return 0; } } } (Some(_), _) => { self.print_error("second cp argument must be string"); return 0; } _ => { self.print_error("first cp argument must be string"); return 0; } } 1 } /// Takes two values that can be stringified as its arguments. /// Moves the file corresponding to the first path to the second /// path. pub fn core_mv(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("mv requires two arguments"); return 0; } let dst_rr = self.stack.pop().unwrap(); let dst_opt: Option<&str>; to_str!(dst_rr, dst_opt); let src_rr = self.stack.pop().unwrap(); let src_opt: Option<&str>; to_str!(src_rr, src_opt); match (src_opt, dst_opt) { (Some(src), Some(dst)) => { let srcs = VM::expand_tilde(src); let dsts = VM::expand_tilde(dst); let src_meta_opt = fs::metadata(&srcs); let dst_meta_opt = fs::metadata(&dsts); let dst_is_dir = !dst_meta_opt.is_err() && dst_meta_opt.unwrap().is_dir(); let dst_path = Path::new(&dsts); let dst_path_exists = dst_path.exists(); let dsts_dev_str = if !dst_path_exists { match dst_path.parent() { Some(s) => { let ss = s.to_str().unwrap(); if ss == "" { ".".to_string() } else { ss.to_string() } } _ => { ".".to_string() } } } else { dsts.clone() }; let dst_dev_meta_opt = fs::metadata(&dsts_dev_str); if src_meta_opt.is_err() { self.print_error("unable to stat file"); return 0; } if dst_dev_meta_opt.is_err() { self.print_error("unable to stat file"); return 0; } let src_meta = src_meta_opt.unwrap(); let dst_dev_meta = dst_dev_meta_opt.unwrap(); if src_meta.dev() == dst_dev_meta.dev() { let real_dst; if dst_is_dir { let src_path = Path::new(&srcs); let file_name = src_path.file_name(); real_dst = format!("{}/{}", dsts_dev_str, file_name.unwrap().to_str().unwrap()); } else { real_dst = dsts; } let res = std::fs::rename(srcs, real_dst); return match res { Ok(_) => 1, Err(e) => { let err_str = format!("unable to rename: {}", e); self.print_error(&err_str); 0 } }; } self.stack.push(new_string_value(src.to_string())); self.stack.push(new_string_value(dst.to_string())); let res = self.core_cp(); if res == 0 { return 0; } let src_meta_opt = fs::metadata(&srcs); match src_meta_opt { Ok(src_meta) => { let res = if src_meta.is_dir() { std::fs::remove_dir_all(srcs) } else { std::fs::remove_file(srcs) }; match res { Ok(_) => 1, Err(e) => { let err_str = format!("unable to remove original file: {}", e); self.print_error(&err_str); 0 } } } Err(e) => { let err_str = format!("unable to stat file: {}", e); self.print_error(&err_str); 0 } } } (Some(_), _) => { self.print_error("second mv argument must be string"); 0 } _ => { self.print_error("first mv argument must be string"); 0 } } } /// Takes two values that can be stringified as its arguments. /// Renames the file with the first path such that it has the /// second path. (The two paths have to be on the same filesystem /// for this to work correctly. If they aren't, see core_mv.) pub fn core_rename(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("rename requires two arguments"); return 0; } let dst_rr = self.stack.pop().unwrap(); let dst_opt: Option<&str>; to_str!(dst_rr, dst_opt); let src_rr = self.stack.pop().unwrap(); let src_opt: Option<&str>; to_str!(src_rr, src_opt); match (src_opt, dst_opt) { (Some(src), Some(dst)) => { let srcs = VM::expand_tilde(src); let dsts = VM::expand_tilde(dst); let res = std::fs::rename(srcs, dsts); match res { Ok(_) => 1, Err(e) => { let err_str = format!("unable to rename file: {}", e); self.print_error(&err_str); 0 } } } (Some(_), _) => { self.print_error("second rename argument must be string"); 0 } _ => { self.print_error("first rename argument must be string"); 0 } } } /// Takes two values that can be stringified as its arguments. /// Creates a symbolic link from the second path to the first /// path. pub fn core_link(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("link requires two arguments"); return 0; } let dst_rr = self.stack.pop().unwrap(); let dst_opt: Option<&str>; to_str!(dst_rr, dst_opt); let src_rr = self.stack.pop().unwrap(); let src_opt: Option<&str>; to_str!(src_rr, src_opt); match (src_opt, dst_opt) { (Some(src), Some(dst)) => { let mut srcs = VM::expand_tilde(src); if !srcs.starts_with("/") { let current_dir_res = std::env::current_dir(); match current_dir_res { Ok(current_dir) => { srcs = format!("{}/{}", current_dir.to_str().unwrap(), srcs); } _ => {} } } let dsts = VM::expand_tilde(dst); let dst_meta_opt = fs::metadata(&dsts); let dst_path = if !dst_meta_opt.is_err() { let dst_meta = dst_meta_opt.unwrap(); if dst_meta.is_dir() { let src_path = Path::new(&srcs); let file_name = src_path.file_name(); match file_name { Some(s) => { format!("{}/{}", dsts, s.to_str().unwrap()) } None => { self.print_error("unable to copy directory to directory"); return 0; } } } else { dsts.to_string() } } else { dsts.to_string() }; let res = std::os::unix::fs::symlink(srcs, dst_path); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to create symbolic link: {}", e); self.print_error(&err_str); return 0; } } } (Some(_), _) => { self.print_error("second link argument must be string"); return 0; } _ => { self.print_error("first link argument must be string"); return 0; } } 1 } /// Takes a value that can be stringified as its single argument. /// Changes the current working directory to that directory. If /// no arguments are provided, then this changes the current /// working directory to the user's home directory. pub fn core_cd(&mut self) -> i32 { if self.stack.is_empty() { let home_res = std::env::var("HOME"); match home_res { Ok(home) => { let res = env::set_current_dir(&home); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to cd to home: {}", e); self.print_error(&err_str); return 0; } } } Err(e) => { let err_str = format!("unable to cd to home: {}", e); self.print_error(&err_str); return 0; } } } else { let dir_rr = self.stack.pop().unwrap(); let dir_opt: Option<&str>; to_str!(dir_rr, dir_opt); match dir_opt { Some(dir) => { let dirs = VM::expand_tilde(dir); let path_dir = Path::new(&dirs); let res = env::set_current_dir(&path_dir); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to cd: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("cd argument must be a string"); return 0; } } } 1 } /// Puts the string representation of the current working /// directory onto the stack. pub fn core_cwd(&mut self) -> i32 { let current_dir_res = std::env::current_dir(); match current_dir_res { Ok(current_dir) => { self.stack .push(new_string_value(current_dir.to_str().unwrap().to_string())); } Err(e) => { let err_str = format!("unable to cwd: {}", e); self.print_error(&err_str); return 0; } } 1 } /// Takes a value that can be stringified as its single argument. /// Creates the file if it doesn't exist, and updates its /// modification timestamp to the current time if it does exist, /// similarly to touch(1). pub fn core_touch(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("touch requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_opt: Option<&str>; to_str!(path_rr, path_opt); match path_opt { Some(path_str) => { let path_strs = VM::expand_tilde(path_str); let path = Path::new(&path_strs); if !path.exists() { let res = fs::write(&path_strs, ""); match res { Ok(_) => {} Err(e) => { let err_str = format!("unable to write file: {}", e); self.print_error(&err_str); return 0; } } } else { let times_res = get_file_times(&path_strs); match times_res { Ok((accessed, _)) => { let mtime = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs(); let sft_res = set_file_times(&path_strs, accessed, mtime as i64); match sft_res { Ok(_) => {} Err(e) => { let err_str = format!("unable to write file: {}", e); self.print_error(&err_str); return 0; } } } Err(e) => { let err_str = format!("unable to write file: {}", e); self.print_error(&err_str); return 0; } } } } _ => { self.print_error("touch argument must be a string"); return 0; } } 1 } /// Takes a value that can be stringified and a boolean indicating /// whether to use the link itself or its target (if the value is /// a link) as its arguments. Puts a hash onto the stack /// containing the metadata of the associated file, where "dev" is /// the device number, "ino" is the inode, "mode" is the file /// mode, "nlink" is the number of hard links to the file, "uid" /// is the user ID of the owner, "gid" is the group ID of the /// owner, "rdev" is the device ID (for special files), "size" is /// the total size in bytes, "atime"/"ctime"/"mtime" are various /// file modification times, "blksize" is the block size, and /// "blocks" is the number of blocks allocated to the file. fn stat_inner(&mut self, use_symlink: bool) -> i32 { if self.stack.is_empty() { self.print_error("stat requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_opt: Option<&str>; to_str!(path_rr, path_opt); match path_opt { Some(s) => { let ss = VM::expand_tilde(s); let meta_res = if use_symlink { fs::symlink_metadata(&ss) } else { fs::metadata(&ss) }; match meta_res { Ok(meta) => { let mut map = new_hash_indexmap(); map.insert( "dev".to_string(), Value::BigInt(BigInt::from_u64(meta.dev()).unwrap()), ); map.insert( "ino".to_string(), Value::BigInt(BigInt::from_u64(meta.ino()).unwrap()), ); map.insert( "mode".to_string(), Value::BigInt(BigInt::from_u32(meta.mode()).unwrap()), ); map.insert( "nlink".to_string(), Value::BigInt(BigInt::from_u64(meta.nlink()).unwrap()), ); map.insert( "uid".to_string(), Value::BigInt(BigInt::from_u32(meta.uid()).unwrap()), ); map.insert( "gid".to_string(), Value::BigInt(BigInt::from_u32(meta.gid()).unwrap()), ); map.insert( "rdev".to_string(), Value::BigInt(BigInt::from_u64(meta.rdev()).unwrap()), ); map.insert( "size".to_string(), Value::BigInt(BigInt::from_u64(meta.size()).unwrap()), ); map.insert( "atime".to_string(), Value::BigInt(BigInt::from_i64(meta.atime()).unwrap()), ); map.insert( "mtime".to_string(), Value::BigInt(BigInt::from_i64(meta.mtime()).unwrap()), ); map.insert( "ctime".to_string(), Value::BigInt(BigInt::from_i64(meta.ctime()).unwrap()), ); map.insert( "blksize".to_string(), Value::BigInt(BigInt::from_u64(meta.blksize()).unwrap()), ); map.insert( "blocks".to_string(), Value::BigInt(BigInt::from_u64(meta.blocks()).unwrap()), ); self.stack.push(Value::Hash(Rc::new(RefCell::new(map)))); } Err(e) => { let err_str = format!("unable to stat file: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("stat argument must be a string"); return 0; } } 1 } /// See stat_inner. pub fn core_stat(&mut self) -> i32 { self.stat_inner(false) } /// See stat_inner. pub fn core_lstat(&mut self) -> i32 { self.stat_inner(true) } fn convert_process(tz: &chrono_tz::Tz, users: &sysinfo::Users, process: &sysinfo::Process) -> CoshIndexMap<String, Value> { let pid = process.pid(); let mut map = new_hash_indexmap(); map.insert( "pid".to_string(), Value::BigInt(BigInt::from_i32(pid.as_u32().try_into().unwrap()).unwrap()), ); let user_id_opt = process.user_id(); match user_id_opt { Some(user_id) => { map.insert( "uid".to_string(), Value::BigInt(BigInt::from_u32(**user_id).unwrap()), ); match users.get_user_by_id(user_id) { None => {} Some(user) => { map.insert( "user".to_string(), new_string_value(user.name().to_string()) ); } }; } None => { map.insert( "uid".to_string(), Value::Null, ); } } let group_id_opt = process.group_id(); match group_id_opt { Some(group_id) => { map.insert( "gid".to_string(), Value::BigInt(BigInt::from_u32(*group_id).unwrap()), ); } None => { map.insert( "gid".to_string(), Value::Null, ); } } map.insert( "name".to_string(), new_string_value(process.name().to_string()) ); map.insert( "cmd".to_string(), new_string_value(process.cmd().join(" ")) ); map.insert( "cpu".to_string(), Value::Float(process.cpu_usage().into()) ); map.insert( "mem".to_string(), Value::BigInt(BigInt::from_u64(process.memory().into()).unwrap()) ); map.insert( "vmem".to_string(), Value::BigInt(BigInt::from_u64(process.virtual_memory().into()).unwrap()) ); map.insert( "runtime".to_string(), Value::BigInt(BigInt::from_u64(process.run_time()).unwrap()) ); let s = format!("{}", process.status()); map.insert( "status".to_string(), new_string_value(s) ); let epoch64 = i64::try_from(process.start_time()).unwrap(); let naive = NaiveDateTime::from_timestamp_opt(epoch64, 0).unwrap(); let datetime: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive, Utc); let newdate = datetime.with_timezone(tz); map.insert( "start".to_string(), Value::DateTimeNT(newdate) ); return map; } /// Puts the process information for a single process onto the /// stack. Each hash has elements for "uid", "user" (if /// available), "gid", "name", "cmd", "cpu", "mem", "vmem", /// "runtime", "status", and "start". pub fn core_pss(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("pss requires one argument"); return 0; } self.instantiate_sys(); let sysopt = &mut self.sys; let sys = &mut sysopt.as_mut().unwrap(); let usersopt = &mut self.users; let users = &mut usersopt.as_mut().unwrap(); let pid_rr = self.stack.pop().unwrap(); let pid_int_opt = pid_rr.to_int(); match pid_int_opt { Some(pid_int) => { let pid = sysinfo::Pid::from(pid_int as usize); let res = sys.refresh_process(pid); if !res { self.print_error("unable to find process"); return 0; } let process = sys.process(pid).unwrap(); let tz = self.local_tz; let map = VM::convert_process(&tz, users, &process); self.stack.push(Value::Hash(Rc::new(RefCell::new(map)))); return 1; } _ => { self.print_error("pss argument must be pid"); return 0; } } } /// Puts current process information onto the stack, in the form /// of a list of hashes. Each hash has elements for "pid", "uid", /// and "name". #[allow(unused_variables)] pub fn core_ps(&mut self) -> i32 { self.instantiate_sys(); let sysopt = &mut self.sys; let sys = &mut sysopt.as_mut().unwrap(); sys.refresh_processes(); let usersopt = &mut self.users; let users = &mut usersopt.as_mut().unwrap(); users.refresh_list(); /* Using the same approach as in nushell for calculating CPU * usage. */ sys.refresh_cpu_specifics(CpuRefreshKind::everything()); std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL * 2); sys.refresh_cpu_specifics(CpuRefreshKind::new().with_cpu_usage()); /* refresh_processes does not remove processes that have * since completed, which is why these extra steps are * necessary. */ let mut pids = Vec::new(); for pid in sys.processes().keys() { pids.push(*pid); } let mut actual_pids = HashSet::new(); for pid in pids { if sys.refresh_process(pid) { actual_pids.insert(pid); } } let mut lst = VecDeque::new(); for (pid, process) in sys.processes() { if !actual_pids.contains(pid) { continue; } let tz = self.local_tz; let map = VM::convert_process(&tz, users, process); lst.push_back(Value::Hash(Rc::new(RefCell::new(map)))) } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); 1 } /// Takes a process identifier and a signal name as its arguments. /// Sends the relevant signal to the process. pub fn core_kill(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("kill requires two arguments"); return 0; } let sig_rr = self.stack.pop().unwrap(); let sig_opt: Option<&str>; to_str!(sig_rr, sig_opt); let pid_rr = self.stack.pop().unwrap(); let pid_int_opt = pid_rr.to_int(); match (pid_int_opt, sig_opt) { (Some(pid), Some(sig)) => { let sig_lc = sig.to_lowercase(); let sig_obj = match &sig_lc[..] { "hup" => Signal::SIGHUP,
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_arithmetic.rs
src/vm/vm_arithmetic.rs
use num::FromPrimitive; use num::ToPrimitive; use num::Integer; use num_bigint::BigInt; use num_traits::Signed; use crate::chunk::Value; use crate::vm::*; /// Convert an i32 to a bigint value. fn int_to_bigint(i: i32) -> Value { Value::BigInt(BigInt::from_i32(i).unwrap()) } /// Convert an i32 to a floating-point value. fn int_to_float(i: i32) -> Value { Value::Float(FromPrimitive::from_i32(i).unwrap()) } /// Add two integers together and return the result value. Promote to /// bigint if the value cannot be stored in an i32. fn add_ints(n1: i32, n2: i32) -> Value { match n1.checked_add(n2) { Some(n3) => Value::Int(n3), None => { let n1_bigint = BigInt::from_i32(n1).unwrap(); Value::BigInt(n1_bigint + n2) } } } /// Subtract one integer from another and return the result value. /// Promote to bigint if the value cannot be stored in an i32. fn subtract_ints(n1: i32, n2: i32) -> Value { match n2.checked_sub(n1) { Some(n3) => Value::Int(n3), None => { let n2_bigint = BigInt::from_i32(n2).unwrap(); Value::BigInt(n2_bigint - n1) } } } /// Multiply two integers together and return the result value. /// Promote to bigint if the value cannot be stored in an i32. fn multiply_ints(n1: i32, n2: i32) -> Value { match n1.checked_mul(n2) { Some(n3) => Value::Int(n3), None => { let n1_bigint = BigInt::from_i32(n1).unwrap(); Value::BigInt(n1_bigint * n2) } } } /// Divide one integer by another and return the result value. Promote /// to bigint if the value cannot be stored in an i32. fn divide_ints(n1: i32, n2: i32) -> Value { match n2.checked_div(n1) { Some(n3) => Value::Int(n3), None => { let n2_bigint = BigInt::from_i32(n2).unwrap(); Value::BigInt(n2_bigint / n1) } } } /// Divide one integer by another and return the remainder. Promote /// to bigint if the value cannot be stored in an i32. fn remainder_ints(n1: i32, n2: i32) -> Value { match n2.checked_rem(n1) { Some(n3) => Value::Int(n3), None => { let n2_bigint = BigInt::from_i32(n2).unwrap(); let n1_bigint = BigInt::from_i32(n1).unwrap(); let (_, remainder) = n2_bigint.div_rem(&n1_bigint); Value::BigInt(remainder) } } } impl VM { /// Helper function for adding two values together and placing the /// result onto the stack. Returns an integer indicating whether /// the values were able to be added together. fn opcode_add_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { let n3 = Value::BigInt(n1 + n2); self.stack.push(n3); 1 } (Value::BigInt(_), Value::Int(n2)) => self.opcode_add_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_add_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { self.stack.push(add_ints(*n1, *n2)); 1 } (Value::Float(n1), Value::Float(n2)) => { self.stack.push(Value::Float(n1 + n2)); 1 } (Value::Int(n1), Value::Float(_)) => self.opcode_add_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_add_inner(v1, &int_to_float(*n2)), (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(add_ints(n1, n2)); return 1; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::BigInt(n1 + n2)); return 1; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::Float(n1 + n2)); return 1; } 0 } } } /// Takes two values as its arguments, adds them together, and /// places the result onto the stack. pub fn opcode_add(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("+ requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let mut done = false; if let (Value::Int(n1), Value::Int(ref mut n2)) = (&v1_rr, self.stack.get_mut(len - 2).unwrap()) { let v3 = add_ints(*n1, *n2); if let Value::Int(n3) = v3 { *n2 = n3; done = true; } } if !done { let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_add_inner(&v1_rr, &v2_rr); if res == 0 { self.print_error("+ requires two numbers"); return 0; } } 1 } /// Helper function for subtracting two values and placing the /// result onto the stack. Returns an integer indicating whether /// the values were able to be subtracted. fn opcode_subtract_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { let n3 = Value::BigInt(n2 - n1); self.stack.push(n3); 1 } (Value::BigInt(_), Value::Int(n2)) => { self.opcode_subtract_inner(v1, &int_to_bigint(*n2)) } (Value::Int(n1), Value::BigInt(_)) => { self.opcode_subtract_inner(&int_to_bigint(*n1), v2) } (Value::Int(n1), Value::Int(n2)) => { self.stack.push(subtract_ints(*n1, *n2)); 1 } (Value::Float(n1), Value::Float(n2)) => { self.stack.push(Value::Float(n2 - n1)); 1 } (Value::Int(n1), Value::Float(_)) => self.opcode_subtract_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_subtract_inner(v1, &int_to_float(*n2)), (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(subtract_ints(n1, n2)); return 1; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::BigInt(n2 - n1)); return 1; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::Float(n2 - n1)); return 1; } 0 } } } /// Takes two values as its arguments, subtracts them, and places /// the result onto the stack. pub fn opcode_subtract(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("- requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let mut done = false; if let (Value::Int(n1), Value::Int(ref mut n2)) = (&v1_rr, self.stack.get_mut(len - 2).unwrap()) { let v3 = subtract_ints(*n1, *n2); if let Value::Int(n3) = v3 { *n2 = n3; done = true; } } if !done { let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_subtract_inner(&v1_rr, &v2_rr); if res == 0 { self.print_error("- requires two numbers"); return 0; } } 1 } /// Helper function for multiplying two values together and /// placing the result onto the stack. Returns an integer /// indicating whether the values were able to be multiplied /// together. fn opcode_multiply_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { let n3 = Value::BigInt(n1 * n2); self.stack.push(n3); 1 } (Value::BigInt(_), Value::Int(n2)) => { self.opcode_multiply_inner(v1, &int_to_bigint(*n2)) } (Value::Int(n1), Value::BigInt(_)) => { self.opcode_multiply_inner(&int_to_bigint(*n1), v2) } (Value::Int(n1), Value::Int(n2)) => { self.stack.push(multiply_ints(*n1, *n2)); 1 } (Value::Float(n1), Value::Float(n2)) => { self.stack.push(Value::Float(n1 * n2)); 1 } (Value::Int(n1), Value::Float(_)) => self.opcode_multiply_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_multiply_inner(v1, &int_to_float(*n2)), (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(multiply_ints(n1, n2)); return 1; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::BigInt(n1 * n2)); return 1; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::Float(n1 * n2)); return 1; } 0 } } } /// Takes two values as its arguments, multiplies them together, /// and places the result onto the stack. pub fn opcode_multiply(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("* requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let mut done = false; if let (Value::Int(n1), Value::Int(ref mut n2)) = (&v1_rr, self.stack.get_mut(len - 2).unwrap()) { let v3 = multiply_ints(*n1, *n2); if let Value::Int(n3) = v3 { *n2 = n3; done = true; } } if !done { let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_multiply_inner(&v1_rr, &v2_rr); if res == 0 { self.print_error("* requires two numbers"); return 0; } } 1 } /// Helper function for dividing two values and placing the result /// onto the stack. Returns an integer indicating whether the /// values were able to be divided. fn opcode_divide_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { let n3 = Value::BigInt(n2 / n1); self.stack.push(n3); 1 } (Value::BigInt(_), Value::Int(n2)) => self.opcode_divide_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_divide_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { self.stack.push(divide_ints(*n1, *n2)); 1 } (Value::Float(n1), Value::Float(n2)) => { self.stack.push(Value::Float(n2 / n1)); 1 } (Value::Int(n1), Value::Float(_)) => self.opcode_divide_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_divide_inner(v1, &int_to_float(*n2)), (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(divide_ints(n1, n2)); return 1; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::BigInt(n2 / n1)); return 1; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(Value::Float(n2 / n1)); return 1; } 0 } } } /// Takes two values as its arguments, subtracts them, and places /// the result onto the stack. pub fn opcode_divide(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("/ requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let mut done = false; if let (Value::Int(n1), Value::Int(ref mut n2)) = (&v1_rr, self.stack.get_mut(len - 2).unwrap()) { let v3 = divide_ints(*n1, *n2); if let Value::Int(n3) = v3 { *n2 = n3; done = true; } } if !done { let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_divide_inner(&v1_rr, &v2_rr); if res == 0 { self.print_error("/ requires two numbers"); return 0; } } 1 } /// Helper function for dividing two values and placing the /// remainder onto the stack. Returns an integer indicating /// whether the values were able to be divided. fn opcode_remainder_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { let (_, remainder) = n2.div_rem(&n1); self.stack.push(Value::BigInt(remainder)); 1 } (Value::BigInt(_), Value::Int(n2)) => self.opcode_remainder_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_remainder_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { self.stack.push(remainder_ints(*n1, *n2)); 1 } (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { self.stack.push(remainder_ints(n1, n2)); return 1; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { let (_, remainder) = n2.div_rem(&n1); self.stack.push(Value::BigInt(remainder)); return 1; } 0 } } } /// Takes two values as its arguments, subtracts them, and places /// the result onto the stack. pub fn opcode_remainder(&mut self) -> i32 { let len = self.stack.len(); if len < 2 { self.print_error("% requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let mut done = false; if let (Value::Int(n1), Value::Int(ref mut n2)) = (&v1_rr, self.stack.get_mut(len - 2).unwrap()) { let v3 = remainder_ints(*n1, *n2); if let Value::Int(n3) = v3 { *n2 = n3; done = true; } } if !done { let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_remainder_inner(&v1_rr, &v2_rr); if res == 0 { self.print_error("% requires two numbers"); return 0; } } 1 } /// Helper function for checking whether two values are equal. /// Returns 1 if they are equal, 0 if they are not, and -1 if they /// cannot be compared. pub fn opcode_eq_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::IpSet(s1), Value::IpSet(s2)) => { if *s1.borrow() == *s2.borrow() { 1 } else { 0 } } (Value::BigInt(n1), Value::BigInt(n2)) => { if n1 == n2 { 1 } else { 0 } } (Value::BigInt(_), Value::Int(n2)) => self.opcode_eq_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_eq_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { if n1 == n2 { 1 } else { 0 } } (Value::Int(n1), Value::Float(_)) => self.opcode_eq_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_eq_inner(v1, &int_to_float(*n2)), (Value::Float(n1), Value::Float(n2)) => { if n1 == n2 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeNT(d2)) => { if d1 == d2 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeOT(d2)) => { if d1 == d2 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeNT(d2)) => { if d1 == d2 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeOT(d2)) => { if d1 == d2 { 1 } else { 0 } } (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n1 == n2 { 1 } else { 0 }; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n1 == n2 { 1 } else { 0 }; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n1 == n2 { 1 } else { 0 }; } let i1_str_opt: Option<&str>; to_str!(v1, i1_str_opt); let i2_str_opt: Option<&str>; to_str!(v2, i2_str_opt); if let (Some(n1), Some(n2)) = (i1_str_opt, i2_str_opt) { return if n1 == n2 { 1 } else { 0 }; } -1 } } } /// Takes two values as its arguments, compares them for equality, /// and places the result onto the stack. pub fn opcode_eq(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("= requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_eq_inner(&v1_rr, &v2_rr); if res == 1 { self.stack.push(Value::Bool(true)); } else if res == 0 { self.stack.push(Value::Bool(false)); } else { self.print_error("= requires two comparable values"); return 0; } 1 } /// Helper function for checking whether one value is greater than /// another. Returns 1 if it is, 0 if it isn't, and -1 if the two /// values cannot be compared. pub fn opcode_gt_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { if n2 > n1 { 1 } else { 0 } } (Value::BigInt(_), Value::Int(n2)) => self.opcode_gt_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_gt_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { if n2 > n1 { 1 } else { 0 } } (Value::Int(n1), Value::Float(_)) => self.opcode_gt_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_gt_inner(v1, &int_to_float(*n2)), (Value::Float(n1), Value::Float(n2)) => { if n2 > n1 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeNT(d2)) => { if d2 > d1 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeOT(d2)) => { if d2 > d1 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeOT(d2)) => { if d2 > d1 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeNT(d2)) => { if d2 > d1 { 1 } else { 0 } } (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 > n1 { 1 } else { 0 }; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 > n1 { 1 } else { 0 }; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 > n1 { 1 } else { 0 }; } let i1_str_opt: Option<&str>; to_str!(v1, i1_str_opt); let i2_str_opt: Option<&str>; to_str!(v2, i2_str_opt); if let (Some(n1), Some(n2)) = (i1_str_opt, i2_str_opt) { return if n2 > n1 { 1 } else { 0 }; } 0 } } } /// Takes two values as its arguments, checks whether the first is /// greater than the second, and places the result onto the stack. pub fn opcode_gt(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("> requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_gt_inner(&v1_rr, &v2_rr); if res == 1 { self.stack.push(Value::Bool(true)); } else if res == 0 { self.stack.push(Value::Bool(false)); } else { self.print_error("> requires two comparable values"); return 0; } 1 } /// Helper function for checking whether one value is less than /// another. Returns 1 if it is, 0 if it isn't, and -1 if the two /// values cannot be compared. pub fn opcode_lt_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => { if n2 < n1 { 1 } else { 0 } } (Value::BigInt(_), Value::Int(n2)) => self.opcode_lt_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_lt_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => { if n2 < n1 { 1 } else { 0 } } (Value::Int(n1), Value::Float(_)) => self.opcode_lt_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_lt_inner(v1, &int_to_float(*n2)), (Value::Float(n1), Value::Float(n2)) => { if n2 < n1 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeNT(d2)) => { if d2 < d1 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeOT(d2)) => { if d2 < d1 { 1 } else { 0 } } (Value::DateTimeNT(d1), Value::DateTimeOT(d2)) => { if d2 < d1 { 1 } else { 0 } } (Value::DateTimeOT(d1), Value::DateTimeNT(d2)) => { if d2 < d1 { 1 } else { 0 } } (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 < n1 { 1 } else { 0 }; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 < n1 { 1 } else { 0 }; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return if n2 < n1 { 1 } else { 0 }; } let i1_str_opt: Option<&str>; to_str!(v1, i1_str_opt); let i2_str_opt: Option<&str>; to_str!(v2, i2_str_opt); if let (Some(n1), Some(n2)) = (i1_str_opt, i2_str_opt) { return if n2 < n1 { 1 } else { 0 }; } -1 } } } /// Takes two values as its arguments, checks whether the first is /// less than the second, and places the result onto the stack. pub fn opcode_lt(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("< requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_lt_inner(&v1_rr, &v2_rr); if res == 1 { self.stack.push(Value::Bool(true)); } else if res == 0 { self.stack.push(Value::Bool(false)); } else { self.print_error("< requires two comparable values"); return 0; } 1 } /// Helper function for comparing two values. Return 1 if the /// second value is greater than the first, 0 if the two values /// are equal, -1 if the second value is less than the first, and /// -2 if the two values cannot be compared. pub fn opcode_cmp_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::BigInt(n1), Value::BigInt(n2)) => n2.cmp(n1) as i32, (Value::BigInt(_), Value::Int(n2)) => self.opcode_cmp_inner(v1, &int_to_bigint(*n2)), (Value::Int(n1), Value::BigInt(_)) => self.opcode_cmp_inner(&int_to_bigint(*n1), v2), (Value::Int(n1), Value::Int(n2)) => n2.cmp(n1) as i32, (Value::Int(n1), Value::Float(_)) => self.opcode_cmp_inner(&int_to_float(*n1), v2), (Value::Float(_), Value::Int(n2)) => self.opcode_cmp_inner(v1, &int_to_float(*n2)), (Value::Float(n1), Value::Float(n2)) => n2.partial_cmp(n1).unwrap() as i32, (Value::DateTimeNT(d1), Value::DateTimeNT(d2)) => d2.cmp(d1) as i32, (Value::DateTimeOT(d1), Value::DateTimeOT(d2)) => d2.cmp(d1) as i32, (Value::DateTimeNT(d1), Value::DateTimeOT(d2)) => { if d2 < d1 { -1 } else if d2 == d1 { 0 } else { -1 } } (Value::DateTimeOT(d1), Value::DateTimeNT(d2)) => { if d2 < d1 { -1 } else if d2 == d1 { 0 } else { -1 } } (_, _) => { let n1_opt = v1.to_int(); let n2_opt = v2.to_int(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return n2.cmp(&n1) as i32; } let n1_opt = v1.to_bigint(); let n2_opt = v2.to_bigint(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return n2.cmp(&n1) as i32; } let n1_opt = v1.to_float(); let n2_opt = v2.to_float(); if let (Some(n1), Some(n2)) = (n1_opt, n2_opt) { return n2.partial_cmp(&n1).unwrap() as i32; } let i1_str_opt: Option<&str>; to_str!(v1, i1_str_opt); let i2_str_opt: Option<&str>; to_str!(v2, i2_str_opt); if let (Some(n1), Some(n2)) = (i1_str_opt, i2_str_opt) { return n2.cmp(n1) as i32; } -2 } } } /// Takes two values as its arguments, compares them, and places /// the result on the stack (-1 for less than, 0 for equal, and 1 /// for greater than). pub fn opcode_cmp(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("<=> requires two arguments"); return 0; } let v1_rr = self.stack.pop().unwrap(); let v2_rr = self.stack.pop().unwrap(); let res = self.opcode_cmp_inner(&v1_rr, &v2_rr); if res == 1 || res == 0 || res == -1 { self.stack.push(Value::Int(res)); } else { self.print_error("<=> requires two comparable values"); return 0; } 1 } /// Get the square root of a number. pub fn core_sqrt(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("sqrt requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); let f_opt = value_rr.to_float(); match f_opt { Some(f) => { let fs = f.sqrt(); self.stack.push(Value::Float(fs)); 1 } None => { self.print_error("sqrt argument must be float"); 0 } } } /// Helper function for exponentiation. fn core_exp_inner(&mut self, v1: &Value, v2: &Value) -> i32 { match (v1, v2) { (Value::Int(n), Value::Int(exp)) => { if *exp < 0 { self.print_error("second exp argument cannot be negative"); return 0; }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_db.rs
src/vm/vm_db.rs
use crate::chunk::{DBConnectionMySQL, DBStatementMySQL, DBConnectionPostgres, DBStatementPostgres, DBConnectionSQLite, DBStatementSQLite, Value}; use crate::hasher::new_hash_indexmap; use crate::vm::*; use chrono::Utc; use ipnet::{Ipv4Net, Ipv6Net}; use num_bigint::BigInt; use num_traits::FromPrimitive; use std::future::Future; use std::ptr::null; use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; use std::time; use std::thread; use sqlx::{Column, Row, TypeInfo}; use sqlx::types::ipnetwork::IpNetwork::{V4, V6}; use sqlx::types::mac_address; use sqlx::types::uuid; fn wake(_data: *const ()) {} fn noop(_data: *const ()) {} static VTABLE: RawWakerVTable = RawWakerVTable::new(|data| RawWaker::new(data, &VTABLE), wake, wake, noop); macro_rules! cancellable_block_on { ($self:expr, $future:expr, $result:expr) => { let waker = RawWaker::new(null(), &VTABLE); let waker = unsafe { Waker::from_raw(waker) }; let mut cx = Context::from_waker(&waker); let mut task = Box::pin($future); loop { match task.as_mut().poll(&mut cx) { Poll::Ready(output) => { $result = Some(output); break; } Poll::Pending => { if !$self.running.load(Ordering::SeqCst) { $self.running.store(true, Ordering::SeqCst); $self.stack.clear(); $result = None; break; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } }; }; } impl VM { /// Takes a database type, hostname, database name, username, and /// password as its arguments, and returns a database connection /// for the specified database. /// (The database handling here would be simpler if Any were used, /// but its type support for the different database engines is a bit /// patchy.) pub fn core_db_conn(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("db.conn requires at least two arguments"); return 0; } let dbtype = self.stack.pop().unwrap(); let host = self.stack.pop().unwrap(); let dbtype_str_opt: Option<&str>; to_str!(dbtype, dbtype_str_opt); let host_str_opt: Option<&str>; to_str!(host, host_str_opt); match (dbtype_str_opt, host_str_opt) { (Some(dbtype_str), Some(host_str)) => { match dbtype_str { "mysql" => { if self.stack.len() < 3 { self.print_error("db.conn requires five arguments for MySQL"); return 0; } let db = self.stack.pop().unwrap(); let pass = self.stack.pop().unwrap(); let user = self.stack.pop().unwrap(); let db_str_opt: Option<&str>; to_str!(db, db_str_opt); let pass_str_opt: Option<&str>; to_str!(pass, pass_str_opt); let user_str_opt: Option<&str>; to_str!(user, user_str_opt); match (db_str_opt, user_str_opt, pass_str_opt) { (Some(db_str), Some(user_str), Some(pass_str)) => { let url = format!("{}://{}:{}@{}/{}", dbtype_str, user_str, pass_str, host_str, db_str); let future = async { return sqlx::Pool::connect(&url).await; }; let res; cancellable_block_on!(self, future, res); match res { Some(Ok(pool)) => { let dbc = DBConnectionMySQL::new(pool); let dbcv = Value::DBConnectionMySQL(Rc::new(RefCell::new(dbc))); self.stack.push(dbcv); return 1; } Some(Err(e)) => { let err_str = format!("unable to connect to database: {}", e); self.print_error(&err_str); return 0; } None => { return 0; } } } _ => { self.print_error("db.conn arguments must be strings"); return 0; } } } "postgresql" => { if self.stack.len() < 3 { self.print_error("db.conn requires five arguments for PostgreSQL"); return 0; } let db = self.stack.pop().unwrap(); let pass = self.stack.pop().unwrap(); let user = self.stack.pop().unwrap(); let db_str_opt: Option<&str>; to_str!(db, db_str_opt); let pass_str_opt: Option<&str>; to_str!(pass, pass_str_opt); let user_str_opt: Option<&str>; to_str!(user, user_str_opt); match (db_str_opt, user_str_opt, pass_str_opt) { (Some(db_str), Some(user_str), Some(pass_str)) => { let url = format!("{}://{}:{}@{}/{}", dbtype_str, user_str, pass_str, host_str, db_str); let future = async { return sqlx::Pool::connect(&url).await; }; let res; cancellable_block_on!(self, future, res); match res { Some(Ok(pool)) => { let dbc = DBConnectionPostgres::new(pool); let dbcv = Value::DBConnectionPostgres(Rc::new(RefCell::new(dbc))); self.stack.push(dbcv); return 1; } Some(Err(e)) => { let err_str = format!("unable to connect to database: {}", e); self.print_error(&err_str); return 0; } None => { return 0; } } } _ => { self.print_error("db.conn arguments must be strings"); return 0; } } } "sqlite" => { let url = format!("{}://{}", dbtype_str, host_str); let future = async { return sqlx::Pool::connect(&url).await; }; let res; cancellable_block_on!(self, future, res); match res { Some(Ok(pool)) => { let dbc = DBConnectionSQLite::new(pool); let dbcv = Value::DBConnectionSQLite(Rc::new(RefCell::new(dbc))); self.stack.push(dbcv); return 1; } Some(Err(e)) => { let err_str = format!("unable to connect to database: {}", e); self.print_error(&err_str); return 0; } None => { return 0; } } } _ => { self.print_error("invalid database type"); return 0; } } } _ => { self.print_error("db.conn arguments must be strings"); return 0; } } } /// Takes an SQL string and a database connection as its /// arguments. Returns a statement object that can be used to /// execute the query and fetch the associated results. /// (For now, this does not actually prepare the query, so as to /// avoid lifetime issues. It may be updated later to support /// that.) pub fn core_db_prep(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("db.prep requires two arguments"); return 0; } let sql = self.stack.pop().unwrap(); let dbcv = self.stack.pop().unwrap(); let sql_str_opt: Option<&str>; to_str!(sql, sql_str_opt); match (dbcv, sql_str_opt) { (Value::DBConnectionMySQL(dbc), Some(sql_str)) => { let dbs = DBStatementMySQL::new(dbc.borrow().pool.clone(), sql_str.to_string()); let dbsv = Value::DBStatementMySQL(Rc::new(RefCell::new(dbs))); self.stack.push(dbsv); return 1; } (Value::DBConnectionPostgres(dbc), Some(sql_str)) => { let dbs = DBStatementPostgres::new(dbc.borrow().pool.clone(), sql_str.to_string()); let dbsv = Value::DBStatementPostgres(Rc::new(RefCell::new(dbs))); self.stack.push(dbsv); return 1; } (Value::DBConnectionSQLite(dbc), Some(sql_str)) => { let dbs = DBStatementSQLite::new(dbc.borrow().pool.clone(), sql_str.to_string()); let dbsv = Value::DBStatementSQLite(Rc::new(RefCell::new(dbs))); self.stack.push(dbsv); return 1; } (Value::DBConnectionMySQL(_), _) => { self.print_error("second db.prep argument must be string"); return 0; } (Value::DBConnectionPostgres(_), _) => { self.print_error("second db.prep argument must be string"); return 0; } (Value::DBConnectionSQLite(_), _) => { self.print_error("second db.prep argument must be string"); return 0; } _ => { self.print_error("first db.prep argument must be database connection"); return 0; } } } fn get_inputs(&mut self, lst: Rc<RefCell<VecDeque<Value>>>) -> Option<Vec<String>> { let mut inputs = Vec::new(); { let lstb = lst.borrow(); for param in lstb.iter() { match param { Value::String(s) => { inputs.push(s.borrow().string.clone()); continue; } _ => {} } let param_str_opt: Option<&str>; to_str!(param, param_str_opt); match param_str_opt { Some(s) => { inputs.push(s.to_string()); } _ => { self.print_error("unable to process db.exec parameter"); return None; } } } } return Some(inputs); } fn db_exec_mysql(&mut self, dbsv: &mut Rc<RefCell<DBStatementMySQL>>, lst: Rc<RefCell<VecDeque<Value>>>) -> i32 { let inputs_opt = self.get_inputs(lst); if let None = inputs_opt { return 0; } let inputs = inputs_opt.unwrap(); let future = async { let mut dbsvb = dbsv.borrow_mut(); let pool = &mut dbsvb.pool; let mut conn = pool.acquire().await.unwrap(); let query = dbsvb.query.clone(); let mut query_obj = sqlx::query(&query); for i in inputs { query_obj = query_obj.bind(i); } return query_obj.fetch_all(&mut conn).await; }; let res; cancellable_block_on!(self, future, res); match res { Some(Ok(raw_records)) => { let mut records = VecDeque::new(); for raw_record in raw_records { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let mut ret_record = new_hash_indexmap(); for column in raw_record.columns() { let name = column.name(); let index = column.ordinal(); let type_info = column.type_info(); if type_info.is_null() { ret_record.insert( name.to_string(), Value::Null ); continue; } match type_info.name() { "BOOLEAN" => { let final_value_res = raw_record.get::<Option<bool>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(b) => { ret_record.insert( name.to_string(), Value::Bool(b) ); } } } "VARCHAR" | "CHAR" | "TINYTEXT" | "TEXT" | "MEDIUMTEXT" | "LONGTEXT" | "ENUM" => { let final_value_res = raw_record.get::<Option<String>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(s) => { ret_record.insert( name.to_string(), new_string_value(s.to_string()) ); } } } "BINARY" | "VARBINARY" | "TINYBLOB" | "BLOB" | "MEDIUMBLOB" | "LONGBLOB" => { let bytes_res = raw_record.get::<Option<Vec<u8>>, usize>(index); match bytes_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(bytes) => { let mut lst = VecDeque::new(); for i in bytes { lst.push_back(Value::Byte(i)); } ret_record.insert( name.to_string(), Value::List(Rc::new(RefCell::new(lst))) ); } } } "DATE" => { let final_value_res = raw_record.get::<Option<chrono::NaiveDate>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), new_string_value(final_value.to_string()) ); } } } "TIME" => { let final_value_res = raw_record.get::<Option<chrono::NaiveTime>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), new_string_value(final_value.to_string()) ); } } } "DATETIME" => { let dt_res = raw_record.get::<Option<chrono::NaiveDateTime>, usize>(index); match dt_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(dt) => { let final_value = dt.and_local_timezone(self.utc_tz).unwrap(); ret_record.insert( name.to_string(), Value::DateTimeNT(final_value) ); } } } "TIMESTAMP" => { let dt_res = raw_record.get::<Option<chrono::DateTime<Utc>>, usize>(index); match dt_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(dt) => { let final_value = dt.with_timezone(&self.utc_tz); ret_record.insert( name.to_string(), Value::DateTimeNT(final_value) ); } } } "TINYINT" | "SMALLINT" | "MEDIUMINT" | "INT" => { let final_value_res = raw_record.get::<Option<i32>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::Int(final_value) ); } } } "BIGINT" => { let final_value_res = raw_record.get::<Option<i64>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::BigInt(BigInt::from_i64(final_value).unwrap()) ); } } } "TINYINT UNSIGNED" | "SMALLINT UNSIGNED" | "MEDIUMINT UNSIGNED" => { let final_value_res = raw_record.get::<Option<i32>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::Int(final_value) ); } } } "INT UNSIGNED" => { let final_value_res = raw_record.get::<Option<u32>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::BigInt(BigInt::from_u32(final_value).unwrap()) ); } } } "BIGINT UNSIGNED" => { let final_value_res = raw_record.get::<Option<u64>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::BigInt(BigInt::from_u64(final_value).unwrap()) ); } } } "FLOAT" => { let final_value_res = raw_record.get::<Option<f32>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::Float(final_value as f64) ); } } } "DOUBLE" => { let final_value_res = raw_record.get::<Option<f64>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), Value::Float(final_value as f64) ); } } } "DECIMAL" => { let final_value_res = raw_record.get::<Option<rust_decimal::Decimal>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(final_value) => { ret_record.insert( name.to_string(), new_string_value(final_value.to_string()) ); } } } "JSON" => { let final_value_res = raw_record.get::<Option<serde_json::Value>, usize>(index); match final_value_res { None => { ret_record.insert( name.to_string(), Value::Null ); } Some(s) => { self.stack.push(new_string_value(s.to_string())); let res = self.core_from_json(); if res == 1 { ret_record.insert( name.to_string(), self.stack.pop().unwrap() ); } else { return 0; } } } } _ => { let err_str = format!("unable to process database field type '{}'", type_info.name()); self.print_error(&err_str); return 0; } } } records.push_back(Value::Hash(Rc::new(RefCell::new(ret_record)))); } self.stack.push(Value::List(Rc::new(RefCell::new(records)))); return 1; } Some(Err(e)) => { let err_str = format!("unable to execute query: {}", e); self.print_error(&err_str); return 0; } None => { return 0; } } } fn db_exec_postgres(&mut self, dbsv: &mut Rc<RefCell<DBStatementPostgres>>, lst: Rc<RefCell<VecDeque<Value>>>) -> i32 { let inputs_opt = self.get_inputs(lst); if let None = inputs_opt { return 0; } let inputs = inputs_opt.unwrap(); let future = async { let mut dbsvb = dbsv.borrow_mut(); let pool = &mut dbsvb.pool; let mut conn = pool.acquire().await.unwrap(); let query = dbsvb.query.clone(); let mut query_obj = sqlx::query(&query); for i in inputs { query_obj = query_obj.bind(i); } return query_obj.fetch_all(&mut conn).await; }; let res; cancellable_block_on!(self, future, res); match res { Some(Ok(raw_records)) => { let mut records = VecDeque::new(); for raw_record in raw_records { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let mut ret_record = new_hash_indexmap(); for column in raw_record.columns() { let name = column.name(); let index = column.ordinal(); let type_info = column.type_info(); if type_info.is_null() { ret_record.insert( name.to_string(), Value::Null ); continue; }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_net.rs
src/vm/vm_net.rs
use std::cell::RefCell; use std::io::BufWriter; use std::net::TcpStream; use std::rc::Rc; use std::sync::mpsc; use std::sync::mpsc::TryRecvError; use std::thread; use std::time; use ipnetwork::IpNetwork::{V4, V6}; use netstat2::*; use num::FromPrimitive; use num_bigint::BigInt; use pnet::datalink; use sysinfo::Uid; use crate::chunk::{Value, new_string_value, BufReaderWithBuffer}; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; impl VM { pub fn core_ifconfig(&mut self) -> i32 { let interfaces = datalink::interfaces(); let mut lst = VecDeque::new(); for interface in interfaces { let mut map = new_hash_indexmap(); map.insert( "name".to_string(), new_string_value(interface.name) ); match interface.mac { Some(m) => { map.insert( "mac".to_string(), new_string_value(m.to_string()) ); } _ => {} } let mut iplst = VecDeque::new(); for ip in interface.ips { match ip { V4(network) => { let ipaddr = new_string_value(network.ip().to_string()); self.stack.push(ipaddr); let res = self.core_ip(); if res != 1 { return 0; } let ipaddr_obj = self.stack.pop().unwrap(); let netaddr = format!("{}/{}", network.network().to_string(), network.prefix().to_string()); self.stack.push(new_string_value(netaddr)); let res = self.core_ip(); if res != 1 { return 0; } let netaddr_obj = self.stack.pop().unwrap(); let mut netmap = new_hash_indexmap(); netmap.insert("ip".to_string(), ipaddr_obj); netmap.insert("network".to_string(), netaddr_obj); iplst.push_back(Value::Hash(Rc::new(RefCell::new(netmap)))); } V6(network) => { let ipaddr = new_string_value(network.ip().to_string()); self.stack.push(ipaddr); let res = self.core_ip(); if res != 1 { return 0; } let ipaddr_obj = self.stack.pop().unwrap(); let netaddr = format!("{}/{}", network.network().to_string(), network.prefix().to_string()); self.stack.push(new_string_value(netaddr)); let res = self.core_ip(); if res != 1 { return 0; } let netaddr_obj = self.stack.pop().unwrap(); let mut netmap = new_hash_indexmap(); netmap.insert("ip".to_string(), ipaddr_obj); netmap.insert("network".to_string(), netaddr_obj); iplst.push_back(Value::Hash(Rc::new(RefCell::new(netmap)))); } } } map.insert("ips".to_string(), Value::List(Rc::new(RefCell::new(iplst)))); map.insert("flags".to_string(), Value::BigInt( BigInt::from_u32(interface.flags.try_into().unwrap()).unwrap() )); lst.push_back(Value::Hash(Rc::new(RefCell::new(map)))); } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); 1 } pub fn core_netstat(&mut self) -> i32 { let af_flags = AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6; let proto_flags = ProtocolFlags::TCP | ProtocolFlags::UDP; let sockets_info = get_sockets_info(af_flags, proto_flags).unwrap(); { self.instantiate_sys(); let usersopt = &mut self.users; let users = &mut usersopt.as_mut().unwrap(); users.refresh_list(); } let mut lst = VecDeque::new(); for si in sockets_info { let mut map = new_hash_indexmap(); match si.protocol_socket_info { ProtocolSocketInfo::Tcp(tcp_si) => { map.insert("type".to_string(), new_string_value("tcp".to_string())); let local_addr = tcp_si.local_addr.to_string(); self.stack.push(new_string_value(local_addr)); let res = self.core_ip(); if res != 1 { return 0; } map.insert("local_addr".to_string(), self.stack.pop().unwrap()); map.insert("local_port".to_string(), Value::Int(tcp_si.local_port.into())); let remote_addr = tcp_si.remote_addr.to_string(); self.stack.push(new_string_value(remote_addr)); let res = self.core_ip(); if res != 1 { return 0; } map.insert("remote_addr".to_string(), self.stack.pop().unwrap()); map.insert("remote_port".to_string(), Value::Int(tcp_si.remote_port.into())); map.insert("state".to_string(), new_string_value(tcp_si.state.to_string())); } ProtocolSocketInfo::Udp(udp_si) => { map.insert("type".to_string(), new_string_value("udp".to_string())); let local_addr = udp_si.local_addr.to_string(); self.stack.push(new_string_value(local_addr)); let res = self.core_ip(); if res != 1 { return 0; } map.insert("local_addr".to_string(), self.stack.pop().unwrap()); map.insert("local_port".to_string(), Value::Int(udp_si.local_port.into())); } } let usersopt = &mut self.users; let users = &mut usersopt.as_mut().unwrap(); map.insert("inode".to_string(), Value::BigInt( BigInt::from_u32(si.inode.try_into().unwrap()).unwrap() )); map.insert("uid".to_string(), Value::BigInt( BigInt::from_u32(si.uid.try_into().unwrap()).unwrap() )); match users.get_user_by_id(&Uid::try_from(usize::try_from(si.uid).unwrap()).unwrap()) { None => {} Some(user) => { map.insert( "user".to_string(), new_string_value(user.name().to_string()) ); } }; let mut pids = VecDeque::new(); for pid in si.associated_pids { pids.push_back(Value::BigInt(BigInt::from_u32(pid).unwrap())); } map.insert("pids".to_string(), Value::List(Rc::new(RefCell::new(pids)))); lst.push_back(Value::Hash(Rc::new(RefCell::new(map)))); } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); 1 } pub fn core_socket(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("socket requires two arguments"); return 0; } let port_rr = self.stack.pop().unwrap(); let host_rr = self.stack.pop().unwrap(); let port_opt = port_rr.to_int(); let port_int; match port_opt { Some(port) => { port_int = port; } _ => { self.print_error("port number must be an integer"); return 0; } }; let host_str_opt: Option<&str>; to_str!(host_rr.clone(), host_str_opt); let host_str; match host_str_opt { Some(host) => { host_str = host; } _ => { self.print_error("host must be a string"); return 0; } } let conn_str = format!("{}:{}", host_str, port_int); let (tx, rx) = mpsc::channel(); thread::spawn(move || { let stream_res = TcpStream::connect(conn_str); let _ = tx.send(stream_res); }); let stream; loop { let stream_recv_res = rx.try_recv(); match stream_recv_res { Ok(Ok(stream_value)) => { stream = stream_value; break; } Ok(Err(e)) => { let err_str = format!("unable to connect to host: {}", e); self.print_error(&err_str); return 0; } Err(TryRecvError::Disconnected) => { let err_str = format!("unable to connect to host: disconnected"); self.print_error(&err_str); return 0; } Err(TryRecvError::Empty) => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } }; stream.set_nonblocking(true).unwrap(); let tsw = Value::TcpSocketWriter(Rc::new(RefCell::new(BufWriter::new(stream.try_clone().unwrap())))); let tsr = Value::TcpSocketReader(Rc::new(RefCell::new(BufReaderWithBuffer::new(BufReader::new(stream))))); self.stack.push(tsr); self.stack.push(tsw); return 1; } pub fn core_nc(&mut self) -> i32 { if self.stack.len() < 3 { self.print_error("nc requires three arguments"); return 0; } let res = self.core_socket(); if res == 0 { return 0; } let tsw_rr = self.stack.pop().unwrap(); let tsr_rr = self.stack.pop().unwrap(); let input_rr = self.stack.pop().unwrap(); if input_rr.is_shiftable() { self.stack.push(input_rr); loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return 0; } let shift_res = self.opcode_shift(); if shift_res == 0 { return 0; } let element_rr = self.stack.pop().unwrap(); match element_rr { Value::Null => { break; } _ => { self.stack.push(tsw_rr.clone()); self.stack.push(element_rr); let res = self.core_writeline(); if res == 0 { return 0; } } } }; self.stack.pop().unwrap(); } else { self.stack.push(tsw_rr); self.stack.push(input_rr); let res = self.core_writeline(); if res == 0 { return 0; } } self.stack.push(tsr_rr); return 1; } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_list.rs
src/vm/vm_list.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::mem; use std::rc::Rc; use std::sync::atomic::Ordering; use std::thread; use std::time; use crate::chunk::{IpSet, Value, ValueSD, valuesd_to_value, read_valuesd, new_string_value}; use crate::hasher::new_set_indexmap; use crate::vm::VM; impl VM { /// Takes a list or a set and a value as its arguments. Pushes /// the value onto the list/set and places the updated list/set /// onto the stack. #[allow(clippy::redundant_clone)] pub fn opcode_push(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("push requires two arguments"); return 0; } let element_rr = self.stack.pop().unwrap(); let mut lst_rr = self.stack.pop().unwrap(); { match lst_rr { Value::List(ref mut lst) => { lst.borrow_mut().push_back(element_rr); } Value::Set(ref mut map) => { { let mb = map.borrow(); if !mb.is_empty() { let (_, val) = mb.iter().next().unwrap(); if !val.variants_equal(&element_rr) { self.print_error( "second push argument type does not match first argument set", ); return 0; } } } /* Disallow set creation for IP * addresses or IP sets: users should * just use IP sets in those cases. */ match element_rr { Value::IpSet(_) | Value::Ipv4(_) | Value::Ipv6(_) | Value::Ipv4Range(_) | Value::Ipv6Range(_) => { self.print_error( "second push argument cannot be an IP address object (see ips)", ); return 0; } _ => {} } let element_str_opt: Option<&str>; to_str!(element_rr.clone(), element_str_opt); match element_str_opt { None => { self.print_error("second push argument cannot be added to set"); return 0; } Some(s) => { map.borrow_mut().insert(s.to_string(), element_rr); } } } _ => { self.print_error("first push argument must be list/set"); return 0; } } } self.stack.push(lst_rr); 1 } /// Takes a list and a value as its arguments. Pushes the value /// onto the start of the list and places the updated list onto /// the stack. pub fn core_unshift(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("unshift requires two arguments"); return 0; } let element_rr = self.stack.pop().unwrap(); let mut lst_rr = self.stack.pop().unwrap(); { match lst_rr { Value::List(ref mut lst) => { lst.borrow_mut().push_front(element_rr); } _ => { self.print_error("first unshift argument must be list"); return 0; } } } self.stack.push(lst_rr); 1 } /// Takes a list as its single argument. Pops a value from the /// end of the list and places that value onto the stack. pub fn opcode_pop(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("pop requires one argument"); return 0; } let mut lst_rr = self.stack.pop().unwrap(); let element_rr = match lst_rr { Value::List(ref mut lst) => { let element_rr_opt = lst.borrow_mut().pop_back(); match element_rr_opt { Some(element_rr) => element_rr, None => Value::Null, } } _ => { self.print_error("pop argument must be list"); return 0; } }; self.stack.push(element_rr); 1 } pub fn opcode_shift_inner(&mut self, shiftable_rr: &mut Value) -> i32 { let mut repush = false; let mut stack_len = 0; let mut new_stack_len = 0; match *shiftable_rr { Value::Generator(ref mut generator_object_) => { let mut new_i = 0; { let mut generator_object = generator_object_.borrow_mut(); let index = generator_object.index; { let gen_args = &mut generator_object.gen_args; stack_len = self.stack.len(); let mut is_empty = false; if gen_args.len() == 1 { let gen_arg_rr = &gen_args[0]; match gen_arg_rr { Value::Null => { is_empty = true; } _ => { is_empty = false; } } } if is_empty { gen_args.pop(); self.stack.push(Value::Int(0)); } else { let gen_args_len = gen_args.len(); if gen_args_len > 0 { while !gen_args.is_empty() { self.stack.push(gen_args.pop().unwrap()); } self.stack.push(Value::Int(gen_args_len as i32)); } } } let current_index = index; if current_index == generator_object.chunk.borrow().data.len() { /* At end of function: push null. */ self.stack.push(Value::Null); } else { /* todo: need a generator-specific run function, * to avoid the stuffing around here. */ let local_vars_stack = generator_object.local_vars_stack.clone(); let chunk = generator_object.chunk.clone(); let call_stack_chunks = &mut generator_object.call_stack_chunks; mem::swap(call_stack_chunks, &mut self.call_stack_chunks); let plvs_stack = self.local_var_stack.clone(); self.local_var_stack = local_vars_stack; let backup_chunk = self.chunk.clone(); self.chunk = chunk; let i = self.i; self.i = index; let res = self.run_inner(); self.i = i; self.chunk = backup_chunk; self.local_var_stack = plvs_stack; mem::swap(call_stack_chunks, &mut self.call_stack_chunks); match res { 0 => { return 0; } i => { new_i = i; new_stack_len = self.stack.len(); repush = true; } } } } generator_object_.borrow_mut().index = new_i; } Value::List(ref mut lst) => { if lst.borrow().len() > 0 { let value_rr = lst.borrow_mut().pop_front().unwrap(); self.stack.push(value_rr); } else { self.stack.push(Value::Null); } } Value::Set(ref mut hsh) => { if hsh.borrow().len() > 0 { /* todo: shift_remove_index takes O(n), which is * unpleasant, but necessary for uniformity with * how lists are processed. There is probably a * more appropriate structure that can be used for * sets. */ let (_, value_rr) = hsh.borrow_mut().shift_remove_index(0).unwrap(); self.stack.push(value_rr); } else { self.stack.push(Value::Null); } } Value::IpSet(ref mut ipset) => { self.stack.push(ipset.borrow_mut().shift()); return 1; } Value::CommandGenerator(ref mut command_generator) => { let mut cg = command_generator.borrow_mut(); if cg.get_bytes { let bytes_res = cg.read_bytes(); match bytes_res { None => { self.stack.push(Value::Null); } Some(bytes) => { let lst: VecDeque<Value> = bytes.iter().map(|b| Value::Byte(*b)).collect(); self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } } } else if cg.get_combined { let str_opt = cg.read_line_combined(); match str_opt { None => { self.stack.push(Value::Null); } Some((i, s)) => { let mut lst = VecDeque::new(); lst.push_back(Value::Int(i)); lst.push_back(new_string_value(s)); self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } } } else { let str_opt = cg.read_line(); match str_opt { None => { self.stack.push(Value::Null); } Some(s) => { self.stack.push(new_string_value(s)); } } } return 1; } Value::KeysGenerator(ref mut hwi) => { { let hash_rr = &hwi.borrow().h; match hash_rr { Value::Hash(map) => { let mapb = map.borrow(); let kv = mapb.get_index(hwi.borrow().i); match kv { Some((k, _)) => { self.stack.push( new_string_value(k.to_string()) ); } None => { self.stack.push(Value::Null); } } } _ => { eprintln!("keys generator does not contain a hash!"); std::process::abort(); } } } let el = hwi.borrow().i + 1; hwi.borrow_mut().i = el; } Value::ValuesGenerator(ref mut hwi) => { { let hash_rr = &hwi.borrow().h; match hash_rr { Value::Hash(map) => { let mapb = map.borrow(); let kv = mapb.get_index(hwi.borrow().i); match kv { Some((_, v)) => { self.stack.push(v.clone()); } None => { self.stack.push(Value::Null); } } } _ => { eprintln!("values generator does not contain a hash!"); std::process::abort(); } } } let el = hwi.borrow().i + 1; hwi.borrow_mut().i = el; } Value::EachGenerator(ref mut hwi) => { { let hash_rr = &hwi.borrow().h; match hash_rr { Value::Hash(map) => { let mapb = map.borrow(); let kv = mapb.get_index(hwi.borrow().i); match kv { Some((k, v)) => { let mut lst = VecDeque::new(); lst.push_back(new_string_value(k.to_string())); lst.push_back(v.clone()); self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } None => { self.stack.push(Value::Null); } } } _ => { eprintln!("each generator does not contain a hash!"); std::process::abort(); } } } let el = hwi.borrow().i + 1; hwi.borrow_mut().i = el; } Value::MultiGenerator(ref mut genlist_rr) => { let mut genlist = genlist_rr.borrow_mut(); loop { if genlist.len() == 0 { self.stack.push(Value::Null); break; } else { let next = genlist.front_mut().unwrap(); self.opcode_shift_inner(next); if self.stack.is_empty() { return 0; } match self.stack[self.stack.len() - 1] { Value::Null => { self.stack.pop(); genlist.pop_front(); continue; } _ => { break; } } } } } Value::HistoryGenerator(ref mut hist_gen_rr) => { match &self.readline { None => { self.stack.push(Value::Null); } Some(rl_rr) => { let hist_int = *hist_gen_rr.borrow(); let rl_rrb = rl_rr.borrow(); let hist_line_opt = rl_rrb.history().get(hist_int as usize); match hist_line_opt { Some(s) => { self.stack.push( new_string_value(s.to_string()) ); *hist_gen_rr.borrow_mut() += 1; } None => { self.stack.push(Value::Null); } } } } } Value::ChannelGenerator(ref mut cg) => { if cg.borrow().finished { self.stack.push(Value::Null); return 1; } let mut finished = false; let mut vsd; loop { vsd = read_valuesd(&mut cg.borrow_mut().rx); match vsd { None => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } Some(ValueSD::Null) => { finished = true; break; } _ => { break; } } } self.stack.push(valuesd_to_value(vsd.unwrap())); if finished { cg.borrow_mut().finished = true; } } Value::FileReader(ref mut brwb) => { let str_res = brwb.borrow_mut().readline(); match str_res { Some(v) => { self.stack.push(v); } _ => { self.stack.push(Value::Null); } } } Value::TcpSocketReader(ref mut brwb) => { loop { let str_res = brwb.borrow_mut().readline(); match str_res { Some(v) => { self.stack.push(v); return 1; } _ => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } } } _ => { self.print_error("shift argument does not support shift"); return 0; } } if repush && new_stack_len == stack_len { self.stack.push(Value::Null); } 1 } /// Takes a shiftable object as its single argument. Shifts an /// element from that object and puts it onto the stack. pub fn opcode_shift(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("shift requires one argument"); return 0; } let mut shiftable_rr = self.stack.pop().unwrap(); self.opcode_shift_inner(&mut shiftable_rr) } /// Takes an arbitrary value as its single argument. Places a /// boolean onto the stack indicating whether the argument can be /// shifted. pub fn opcode_isshiftable(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-shiftable requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); self.stack.push(Value::Bool(value_rr.is_shiftable())); 1 } /// Takes two sets as its arguments and returns their union. pub fn core_union(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("union requires two arguments"); return 0; } let set2_rr = self.stack.pop().unwrap(); let set1_rr = self.stack.pop().unwrap(); match (set1_rr, set2_rr) { (Value::Set(s1), Value::Set(s2)) => { let mut new_hsh = new_set_indexmap(); for (k, v) in s1.borrow().iter() { new_hsh.insert(k.clone(), v.value_clone()); } for (k, v) in s2.borrow().iter() { new_hsh.insert(k.clone(), v.value_clone()); } let set = Value::Set(Rc::new(RefCell::new(new_hsh))); self.stack.push(set); } (Value::IpSet(ipset1), Value::IpSet(ipset2)) => { let ipset1_ipv4 = &ipset1.borrow().ipv4; let ipset1_ipv6 = &ipset1.borrow().ipv6; let ipset2_ipv4 = &ipset2.borrow().ipv4; let ipset2_ipv6 = &ipset2.borrow().ipv6; let new_ipv4 = ipset1_ipv4.merge(ipset2_ipv4); let new_ipv6 = ipset1_ipv6.merge(ipset2_ipv6); let new_ipset = IpSet::new(new_ipv4, new_ipv6); self.stack .push(Value::IpSet(Rc::new(RefCell::new(new_ipset)))); return 1; } (Value::Set(_), _) => { self.print_error("second union argument must be set"); return 0; } (_, _) => { self.print_error("first union argument must be set"); return 0; } } 1 } /// Takes two sets as its arguments and returns their /// intersection. pub fn core_isect(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("isect requires two arguments"); return 0; } let set2_rr = self.stack.pop().unwrap(); let set1_rr = self.stack.pop().unwrap(); match (set1_rr, set2_rr) { (Value::Set(s1), Value::Set(s2)) => { let mut new_hsh = new_set_indexmap(); for (k, v) in s1.borrow().iter() { if s2.borrow().get(k).is_some() { new_hsh.insert(k.clone(), v.value_clone()); } } let set = Value::Set(Rc::new(RefCell::new(new_hsh))); self.stack.push(set); } (Value::IpSet(ipset1), Value::IpSet(ipset2)) => { let ipset1_ipv4 = &ipset1.borrow().ipv4; let ipset1_ipv6 = &ipset1.borrow().ipv6; let ipset2_ipv4 = &ipset2.borrow().ipv4; let ipset2_ipv6 = &ipset2.borrow().ipv6; let new_ipv4 = ipset1_ipv4.intersect(ipset2_ipv4); let new_ipv6 = ipset1_ipv6.intersect(ipset2_ipv6); let new_ipset = IpSet::new(new_ipv4, new_ipv6); self.stack .push(Value::IpSet(Rc::new(RefCell::new(new_ipset)))); return 1; } (Value::Set(_), _) => { self.print_error("second isect argument must be set"); return 0; } (_, _) => { self.print_error("first isect argument must be set"); return 0; } } 1 } /// Takes two sets as its arguments and returns their /// difference. pub fn core_diff(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("diff requires two arguments"); return 0; } let set2_rr = self.stack.pop().unwrap(); let set1_rr = self.stack.pop().unwrap(); match (set1_rr, set2_rr) { (Value::Set(s1), Value::Set(s2)) => { let mut new_hsh = new_set_indexmap(); for (k, v) in s1.borrow().iter() { if s2.borrow().get(k).is_none() { new_hsh.insert(k.clone(), v.value_clone()); } } let set = Value::Set(Rc::new(RefCell::new(new_hsh))); self.stack.push(set); } (Value::IpSet(ipset1), Value::IpSet(ipset2)) => { let ipset1_ipv4 = &ipset1.borrow().ipv4; let ipset1_ipv6 = &ipset1.borrow().ipv6; let ipset2_ipv4 = &ipset2.borrow().ipv4; let ipset2_ipv6 = &ipset2.borrow().ipv6; let new_ipv4 = ipset1_ipv4.exclude(ipset2_ipv4); let new_ipv6 = ipset1_ipv6.exclude(ipset2_ipv6); let new_ipset = IpSet::new(new_ipv4, new_ipv6); self.stack .push(Value::IpSet(Rc::new(RefCell::new(new_ipset)))); return 1; } (Value::Set(_), _) => { self.print_error("second diff argument must be set"); return 0; } (_, _) => { self.print_error("first diff argument must be set"); return 0; } } 1 } /// Takes two sets as its arguments and returns their /// symmetric difference. pub fn core_symdiff(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("symdiff requires two arguments"); return 0; } let set2_rr = self.stack.pop().unwrap(); let set1_rr = self.stack.pop().unwrap(); match (set1_rr, set2_rr) { (Value::Set(s1), Value::Set(s2)) => { let mut new_hsh = new_set_indexmap(); for (k, v) in s1.borrow().iter() { if s2.borrow().get(k).is_none() { new_hsh.insert(k.clone(), v.value_clone()); } } for (k, v) in s2.borrow().iter() { if s1.borrow().get(k).is_none() { new_hsh.insert(k.clone(), v.value_clone()); } } let set = Value::Set(Rc::new(RefCell::new(new_hsh))); self.stack.push(set); } (Value::IpSet(ipset1), Value::IpSet(ipset2)) => { let ipset1_ipv4 = &ipset1.borrow().ipv4; let ipset1_ipv6 = &ipset1.borrow().ipv6; let ipset2_ipv4 = &ipset2.borrow().ipv4; let ipset2_ipv6 = &ipset2.borrow().ipv6; let ipv4_is = ipset1_ipv4.intersect(ipset2_ipv4); let ipv6_is = ipset1_ipv6.intersect(ipset2_ipv6); let new_ipv4 = ipset1_ipv4.merge(ipset2_ipv4).exclude(&ipv4_is); let new_ipv6 = ipset1_ipv6.merge(ipset2_ipv6).exclude(&ipv6_is); let new_ipset = IpSet::new(new_ipv4, new_ipv6); self.stack .push(Value::IpSet(Rc::new(RefCell::new(new_ipset)))); return 1; } (Value::Set(_), _) => { self.print_error("second symdiff argument must be set"); return 0; } (_, _) => { self.print_error("first symdiff argument must be set"); return 0; } } 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_yaml.rs
src/vm/vm_yaml.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::convert::TryFrom; use std::rc::Rc; use indexmap::IndexMap; use num_bigint::ToBigInt; use crate::chunk::Value; use crate::hasher::{new_hash_indexmap, new_set_indexmap}; use crate::vm::*; /// Converts a serde_yaml object into a value. fn convert_from_yaml(v: &serde_yaml::value::Value) -> Value { match v { serde_yaml::value::Value::Null => Value::Null, serde_yaml::value::Value::Bool(true) => Value::Bool(true), serde_yaml::value::Value::Bool(false) => Value::Bool(false), serde_yaml::value::Value::Number(n) => { if n.is_i64() { let n_uw = n.as_i64().unwrap(); let n2_res = i32::try_from(n_uw); match n2_res { Ok(n2) => Value::Int(n2), _ => Value::BigInt(n_uw.to_bigint().unwrap()), } } else if n.is_u64() { let n_uw = n.as_u64().unwrap(); let n2_res = i32::try_from(n_uw); match n2_res { Ok(n2) => Value::Int(n2), _ => Value::BigInt(n_uw.to_bigint().unwrap()), } } else { Value::Float(n.as_f64().unwrap()) } } serde_yaml::value::Value::String(s) => new_string_value(s.to_string()), serde_yaml::value::Value::Sequence(lst) => Value::List(Rc::new(RefCell::new( lst.iter().map(convert_from_yaml).collect::<VecDeque<_>>(), ))), serde_yaml::value::Value::Mapping(map) => { let mut result = new_hash_indexmap(); for (k, v) in map.iter() { let k_value = convert_from_yaml(k); let k_value_opt: Option<&str>; to_str!(k_value, k_value_opt); result.insert(k_value_opt.unwrap().to_string(), convert_from_yaml(v)); } Value::Hash(Rc::new(RefCell::new(result))) }, _ => Value::Null } } /// Convert a value into a YAML string. fn convert_to_yaml(v: &Value) -> String { match v { Value::Null => "null".to_string(), Value::Bool(true) => "true".to_string(), Value::Bool(false) => "false".to_string(), Value::Byte(n) => n.to_string(), Value::Int(n) => n.to_string(), Value::Float(f) => f.to_string(), Value::String(st) => { format!("\"{}\"", &st.borrow().string) } Value::List(lst) => { let s = lst .borrow() .iter() .map(convert_to_yaml) .collect::<Vec<_>>() .join(","); format!("[{}]", s) } Value::Hash(vm) => { let s = vm .borrow() .iter() .map(|(k, v_rr)| format!("\"{}\":{}", k, convert_to_yaml(v_rr))) .collect::<Vec<_>>() .join(","); format!("{{{}}}", s) } _ => { let s_opt = v.to_string(); match s_opt { Some(s) => { format!("\"{}\"", s) } None => { let type_str = v.type_string(); let s = format!("\"v[{}]\"", type_str); s } } } } } impl VM { /// Takes a YAML string, converts it into a hash, and puts the /// result onto the stack. pub fn core_from_yaml(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("from-yaml requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); if !value_rr.is_generator() { let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { let doc_res = serde_yaml::from_str(s); let doc; match doc_res { Err(e) => { let err_str = format!("from-yaml argument is not valid YAML: {}", e); self.print_error(&err_str); return 0; } Ok(d) => { doc = d; } } let yaml_rr = convert_from_yaml(&doc); self.stack.push(yaml_rr); 1 } _ => { self.print_error("from-yaml argument must be string or generator"); 0 } } } else { self.stack.push(value_rr); self.stack.push(new_string_value("".to_string())); let function_rr = self.string_to_callable("join").unwrap(); let res = self.call(OpCode::Call, function_rr); if !res { return 0; } self.core_from_yaml() } } /// Takes a hash, converts it into a YAML string representation, /// and puts the result onto the stack. pub fn core_to_yaml(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("to-yaml requires one argument"); return 0; } let value_rr = self.stack.pop().unwrap(); self.stack.push(new_string_value(convert_to_yaml(&value_rr))); 1 } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_io.rs
src/vm/vm_io.rs
use std::cell::RefCell; use std::fs::metadata; use std::fs::symlink_metadata; use std::fs::File; use std::io::BufReader; use std::io::BufWriter; use std::io::Write; use std::rc::Rc; use std::thread; use std::time; use lazy_static::lazy_static; use nix::unistd::AccessFlags; use regex::Regex; use tempfile::{NamedTempFile, TempDir}; use crate::chunk::{Value, BufReaderWithBuffer}; use crate::vm::*; lazy_static! { static ref TRAILING_SLASHES: Regex = Regex::new("/*$").unwrap(); } impl VM { /// Takes a file path and a mode string (either 'r' or 'w') as its /// arguments, and puts a FileReader or FileWriter object on the /// stack as appropriate. pub fn opcode_open(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("open requires two arguments"); return 0; } let rw_rr = self.stack.pop().unwrap(); let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match rw_rr { Value::String(st) => match st.borrow().string.as_ref() { "r" => match path_str_opt { Some(s) => { let ss = VM::expand_tilde(s); let metadata_res = metadata(ss.clone()); match metadata_res { Ok(metadata) => { let is_dir = metadata.is_dir(); if !is_dir { let file_res = File::open(ss); match file_res { Ok(file) => { self.stack.push(Value::FileReader(Rc::new(RefCell::new( BufReaderWithBuffer::new( BufReader::new(file) ) )))); } Err(e) => { let err_str = format!("unable to open file: {}", e); self.print_error(&err_str); return 0; } } } else { let err_str = format!("unable to open file: is a directory"); self.print_error(&err_str); return 0; } } Err(e) => { let err_str = format!("unable to open file: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("path for open must be a string"); return 0; } }, "w" => match path_str_opt { Some(s) => { let ss = VM::expand_tilde(s); let file_res = File::create(ss); match file_res { Ok(file) => { self.stack.push(Value::FileWriter(Rc::new(RefCell::new( BufWriter::new(file), )))); } Err(e) => { let err_str = format!("unable to open file: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("path for open must be a string"); return 0; } }, _ => { self.print_error("mode for open must be 'r' or 'w'"); return 0; } }, _ => { self.print_error("mode for open must be 'r' or 'w'"); return 0; } } 1 } /// Takes a FileReader object as its single argument. Reads one /// line from that object and places it onto the stack (including /// the ending newline). pub fn opcode_readline(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("readline requires one argument"); return 0; } let mut file_reader_rr = self.stack.pop().unwrap(); match file_reader_rr { Value::FileReader(ref mut brwb) => { let str_res = brwb.borrow_mut().readline(); match str_res { Some(v) => { self.stack.push(v); } _ => { return 0; } } } Value::TcpSocketReader(ref mut brwb) => { loop { let str_res = brwb.borrow_mut().readline(); match str_res { Some(v) => { self.stack.push(v); return 1; } _ => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } } } _ => { self.print_error("readline argument must be a file reader"); return 0; } } 1 } /// Takes a FileReader object as its single argument. Reads the /// specified number of bytes from the object and places the list /// of bytes onto the stack. pub fn opcode_read(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("read requires two arguments"); return 0; } let bytes_rr = self.stack.pop().unwrap(); let file_reader_rr = self.stack.pop().unwrap(); let bytes_opt = bytes_rr.to_int(); match (file_reader_rr, bytes_opt) { (Value::FileReader(ref mut brwb), Some(n)) => { let lst_res = brwb.borrow_mut().read(n as usize); match lst_res { Some(lst) => { self.stack.push(lst); } None => { return 0; } } } (Value::TcpSocketReader(ref mut brwb), Some(n)) => { loop { let lst_res = brwb.borrow_mut().read(n as usize); match lst_res { Some(lst) => { self.stack.push(lst); return 1; } _ => { if !self.running.load(Ordering::SeqCst) { self.running.store(true, Ordering::SeqCst); self.stack.clear(); return 0; } let dur = time::Duration::from_secs_f64(0.05); thread::sleep(dur); } } } } (Value::FileReader(_), _) => { self.print_error("second read argument must be an integer"); return 0; } _ => { self.print_error("first read argument must be a file reader"); return 0; } } 1 } /// Takes a FileWriter object and a list of bytes as its /// arguments. Writes the bytes to the file. pub fn core_write(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("write requires two arguments"); return 0; } let bytes_rr = self.stack.pop().unwrap(); let mut file_writer = self.stack.pop().unwrap(); match bytes_rr { Value::List(lst) => { let mut bytes = Vec::new(); for v in lst.borrow().iter() { match v { Value::Byte(b) => { bytes.push(*b); } _ => { self.print_error("second write argument must be list of bytes"); return 0; } } } match file_writer { Value::FileWriter(ref mut line_writer) => { let res = line_writer.borrow_mut().write_all(&bytes); match res { Ok(_) => { return 1; } Err(e) => { let err_str = format!("unable to write to file: {}", e); self.print_error(&err_str); return 0; } } } Value::TcpSocketWriter(ref mut line_writer) => { let res = line_writer.borrow_mut().write_all(&bytes); match res { Ok(_) => { line_writer.borrow_mut().flush().unwrap(); return 1; } Err(e) => { let err_str = format!("unable to write to socket: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("first write argument must be a file writer"); return 0; } } } _ => { self.print_error("second write argument must be a string"); return 0; } }; } /// Takes a FileWriter object and a line as its arguments. Writes /// the line to the file. pub fn core_writeline(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("writeline requires two arguments"); return 0; } let line_rr = self.stack.pop().unwrap(); let line_str_opt: Option<&str>; to_str!(line_rr, line_str_opt); match line_str_opt { Some(s) => { if !s.is_empty() { let mut file_writer = self.stack.pop().unwrap(); match file_writer { Value::FileWriter(ref mut line_writer) => { let res = line_writer.borrow_mut().write_all(s.as_bytes()); match res { Ok(_) => { return 1; } Err(e) => { let err_str = format!("unable to write to file: {}", e); self.print_error(&err_str); return 0; } } } Value::TcpSocketWriter(ref mut line_writer) => { let res = line_writer.borrow_mut().write_all(s.as_bytes()); match res { Ok(_) => { line_writer.borrow_mut().flush().unwrap(); return 1; } Err(e) => { let err_str = format!("unable to write to socket: {}", e); self.print_error(&err_str); return 0; } } } _ => { self.print_error("first writeline argument must be a file writer"); return 0; } } } } _ => { self.print_error("second writeline argument must be a string"); return 0; } }; 1 } /// Takes a FileReader or FileWriter object as its single /// argument. Closes the object, if required. pub fn core_close(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("close requires one argument"); return 0; } let mut file_rr = self.stack.pop().unwrap(); match file_rr { Value::FileReader(_) => { // No action required. 1 } Value::FileWriter(ref mut line_writer) => { let res = line_writer.borrow_mut().flush(); match res { Ok(_) => 1, Err(e) => { let err_str = format!("unable to flush data: {}", e); self.print_error(&err_str); 0 } } } _ => { self.print_error("close argument must be a file reader or writer"); 0 } } } /// Takes a directory path as its single argument. Opens the /// directory and places a DirectoryHandle object for the /// directory onto the stack. pub fn core_opendir(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("opendir requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let ss = VM::expand_tilde(s); let ss2 = TRAILING_SLASHES.replace_all(&ss, "").to_string(); let dir_handle_res = std::fs::read_dir(ss2); match dir_handle_res { Ok(dir_handle) => { self.stack .push(Value::DirectoryHandle(Rc::new(RefCell::new(dir_handle)))); 1 } Err(e) => { let err_str = format!("unable to open directory: {}", e); self.print_error(&err_str); 0 } } } _ => { self.print_error("opendir argument must be a string"); 0 } } } /// Takes a DirectoryHandle object as its single argument. Reads /// the next entry from the corresponding handle and places it /// onto the stack. pub fn core_readdir(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("readdir requires one argument"); return 0; } let mut dir_handle_rr = self.stack.pop().unwrap(); let entry_value = match dir_handle_rr { Value::DirectoryHandle(ref mut dir_handle) => { let entry_opt = dir_handle.borrow_mut().next(); match entry_opt { Some(s) => { let path = s.unwrap().path(); new_string_value(path.to_str().unwrap().to_string()) } None => Value::Null, } } _ => { self.print_error("readdir argument must be a directory handle"); return 0; } }; self.stack.push(entry_value); 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path maps to a directory. pub fn core_is_dir(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-dir requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let metadata_res = metadata(s); match metadata_res { Ok(metadata) => { let is_dir = metadata.is_dir(); self.stack.push(Value::Bool(is_dir)); } _ => { self.stack.push(Value::Bool(false)); } } } _ => { self.print_error("is-dir argument must be a string"); return 0; } } 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path maps to a file. pub fn core_is_file(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-file requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let metadata_res = metadata(s); match metadata_res { Ok(metadata) => { let is_file = metadata.is_file(); self.stack.push(Value::Bool(is_file)); } _ => { self.stack.push(Value::Bool(false)); } } } _ => { self.print_error("is-file argument must be a string"); return 0; } } 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path maps to a symbolic link. pub fn core_is_link(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-link requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let metadata_res = symlink_metadata(s); match metadata_res { Ok(metadata) => { let is_link = metadata.is_symlink(); self.stack.push(Value::Bool(is_link)); } _ => { self.stack.push(Value::Bool(false)); } } } _ => { self.print_error("is-link argument must be a string"); return 0; } } 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path is readable. pub fn core_is_r(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-r requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let is_readable = nix::unistd::access(s, AccessFlags::R_OK).is_ok(); self.stack.push(Value::Bool(is_readable)); } _ => { self.print_error("is-r argument must be a string"); return 0; } } 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path is writable. pub fn core_is_w(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-w requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let is_writable = nix::unistd::access(s, AccessFlags::W_OK).is_ok(); self.stack.push(Value::Bool(is_writable)); } _ => { self.print_error("is-w argument must be a string"); return 0; } } 1 } /// Takes a path as its single argument. Places a boolean onto /// the stack indicating whether the path is executable. pub fn core_is_x(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("is-x requires one argument"); return 0; } let path_rr = self.stack.pop().unwrap(); let path_str_opt: Option<&str>; to_str!(path_rr, path_str_opt); match path_str_opt { Some(s) => { let is_executable = nix::unistd::access(s, AccessFlags::X_OK).is_ok(); self.stack.push(Value::Bool(is_executable)); } _ => { self.print_error("is-x argument must be a string"); return 0; } } 1 } /// Puts a path and a FileReader on the stack for a new temporary /// file. pub fn opcode_tempfile(&mut self) -> i32 { let file_res = NamedTempFile::new(); match file_res { Ok(ntf) => match ntf.keep() { Ok((file, path)) => { self.stack .push(new_string_value(path.to_str().unwrap().to_string())); self.stack .push(Value::FileWriter(Rc::new(RefCell::new(BufWriter::new( file, ))))); 1 } Err(e) => { let err_str = format!("unable to open temporary file: {}", e); self.print_error(&err_str); 0 } }, Err(e) => { let err_str = format!("unable to open temporary file: {}", e); self.print_error(&err_str); 0 } } } /// Puts a path on the stack for a new temporary directory. pub fn opcode_tempdir(&mut self) -> i32 { let dir = TempDir::new(); match dir { Ok(td) => { let path = td.into_path(); self.stack .push(new_string_value(path.to_str().unwrap().to_string())); 1 } Err(e) => { let err_str = format!("unable to open temporary directory: {}", e); self.print_error(&err_str); 0 } } } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/src/vm/vm_string.rs
src/vm/vm_string.rs
use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; use lazy_static::lazy_static; use regex::Regex; use crate::chunk::Value; use crate::vm::*; lazy_static! { static ref CAPTURE_NUM: Regex = Regex::new("\\{(\\d+)\\}").unwrap(); static ref CAPTURE_WITHOUT_NUM: Regex = Regex::new("\\{\\}").unwrap(); } impl VM { /// Takes two string/list arguments, appends them together, and /// adds the resulting string/list back onto the stack. pub fn core_append(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("++ requires two arguments"); return 0; } let v2 = self.stack.pop().unwrap(); let mut v1 = self.stack.pop().unwrap(); if v1.is_shiftable() && v2.is_shiftable() { match v1 { Value::MultiGenerator(ref mut genlist) => { match v2 { Value::MultiGenerator(ref genlist_v2) => { if Rc::ptr_eq(genlist, genlist_v2) { self.print_error("++ cannot be used to append generator to itself"); return 0; } } _ => {} } genlist.borrow_mut().push_back(v2); self.stack.push(v1); } _ => { let mut genlist = VecDeque::new(); genlist.push_back(v1); genlist.push_back(v2); let mg = Value::MultiGenerator(Rc::new(RefCell::new(genlist))); self.stack.push(mg); } } } else { match (v1.clone(), v2.clone()) { (Value::Hash(hs1_ref), Value::Hash(hs2_ref)) => { let mut hsh = hs1_ref.borrow().clone(); for (k, v) in hs2_ref.borrow().iter() { hsh.insert(k.clone(), v.clone()); } let res = Value::Hash(Rc::new(RefCell::new(hsh))); self.stack.push(res); } (_, _) => { let v1_str_opt: Option<&str>; to_str!(v1, v1_str_opt); let v2_str_opt: Option<&str>; to_str!(v2, v2_str_opt); match (v1_str_opt, v2_str_opt) { (Some(s1), Some(s2)) => { let s3 = format!("{}{}", s1, s2); self.stack.push(new_string_value(s3)); } (Some(_), _) => { self.print_error("second ++ argument must be string"); return 0; } (_, _) => { self.print_error("first ++ argument must be string"); return 0; } } } } } 1 } /// Takes a string and a separator as its arguments. Splits the /// string using the separator, treated as a regex, and puts the /// resulting list onto the stack. pub fn core_splitr(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("splitr requires two arguments"); return 0; } let regex_rr = self.stack.pop().unwrap(); let regex_opt = self.gen_regex(regex_rr); if regex_opt.is_none() { return 0; } let list_str_rr = self.stack.pop().unwrap(); let list_str_opt: Option<&str>; to_str!(list_str_rr, list_str_opt); match (regex_opt, list_str_opt) { (Some((regex, _)), Some(list_str)) => { let elements = regex.split(list_str); let mut final_elements = VecDeque::new(); for e in elements { final_elements.push_back(new_string_value(e.to_string())); } self.stack .push(Value::List(Rc::new(RefCell::new(final_elements)))); } (Some(_), _) => { self.print_error("first splitr argument must be string"); return 0; } _ => { self.print_error("second splitr argument must be string"); return 0; } } 1 } /// Takes a string and a separator as its arguments. Splits the /// string using the separator, and puts the resulting list onto /// the stack. Quotation by way of the double-quote character is /// taken into account. pub fn core_split(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("split requires two arguments"); return 0; } let separator_rr = self.stack.pop().unwrap(); let list_str_rr = self.stack.pop().unwrap(); let separator_opt: Option<&str>; to_str!(separator_rr, separator_opt); let list_str_opt: Option<&str>; to_str!(list_str_rr, list_str_opt); match (separator_opt, list_str_opt) { (Some(separator), Some(list_str)) => { let elements = list_str.split(separator); /* The final set of separated elements. */ let mut final_elements = Vec::new(); /* A list containing a partially-complete element, if * applicable. */ let mut buffer = Vec::new(); for e in elements { let mut e_str = e.to_string(); if !buffer.is_empty() { if !e_str.is_empty() { if e_str.ends_with('\"') { buffer.push(e_str); let mut new_str = buffer.join(separator); if !new_str.is_empty() { if new_str.starts_with('\"') { new_str.remove(0); } if !new_str.is_empty() && new_str.ends_with('\"') { new_str.remove(new_str.len() - 1); } } final_elements.push(new_str.to_string()); buffer.clear(); } else { buffer.push(e_str); } } } else if !e_str.is_empty() && e_str.starts_with('\"') && !e_str.ends_with('\"') { buffer.push(e_str); } else { if !e_str.is_empty() { if e_str.starts_with('\"') { e_str.remove(0); } if !e_str.is_empty() && e_str.ends_with('\"') { e_str.remove(e_str.len() - 1); } } final_elements.push(e_str); } } if !buffer.is_empty() { self.print_error("first split argument has syntax error"); return 0; } let mut lst = VecDeque::new(); for e in final_elements.iter() { lst.push_back(new_string_value(e.to_string())); } self.stack.push(Value::List(Rc::new(RefCell::new(lst)))); } (Some(_), _) => { self.print_error("first split argument must be string"); return 0; } _ => { self.print_error("second split argument must be string"); return 0; } } 1 } /// Takes a shiftable object and a separator as its arguments. /// Joins the elements retrieved from the shiftable object by /// using the separator string between the elements, and puts the /// resulting joined string onto the stack. pub fn core_join(&mut self) -> i32 { if self.stack.len() < 2 { self.print_error("join requires two arguments"); return 0; } let separator_rr = self.stack.pop().unwrap(); let separator_opt: Option<&str>; to_str!(separator_rr, separator_opt); let esc_quotes = Regex::new(r#"""#).unwrap(); match separator_opt { Some(separator) => { // If the separator is an empty string, then matching // it against the values to determine whether they // need quoting won't work, so skip that in that case. let separator_is_empty_string = separator.is_empty(); let separator_regex_res = Regex::new(separator); let mut final_elements = Vec::new(); match separator_regex_res { Ok(_separator_regex) => { loop { let dup_res = self.opcode_dup(); if dup_res == 0 { return 0; } let shift_res = self.opcode_shift(); if shift_res == 0 { return 0; } let element_rr = self.stack.pop().unwrap(); match element_rr { Value::Null => { break; } Value::String(st) => { if !separator_is_empty_string && (st.borrow().string.contains(separator) || esc_quotes.is_match(&st.borrow().string)) { let s1 = &st.borrow(); let s2 = esc_quotes.replace_all(&s1.string, "\\\""); final_elements.push(format!("\"{}\"", s2)); } else { final_elements.push(st.borrow().string.to_string()); } } _ => { let element_s; let element_b; let element_str; let element_bk: Option<String>; let element_opt: Option<&str> = match element_rr { Value::String(st) => { element_s = st; element_b = element_s.borrow(); Some(&element_b.string) } _ => { element_bk = element_rr.to_string(); match element_bk { Some(s) => { element_str = s; Some(&element_str) } _ => None, } } }; match element_opt { Some(s) => { if !separator_is_empty_string && (s.contains(separator) || esc_quotes.is_match(s)) { let s2 = esc_quotes.replace_all(s, "\\\""); final_elements.push(format!("\"{}\"", s2)); } else { final_elements.push(s.to_string()); } } _ => { self.print_error("first join argument must be a generator over strings"); return 0; } } } } } } Err(_) => { self.print_error( "second join argument must be valid separator regular expression", ); return 0; } } let drop_res = self.opcode_drop(); if drop_res == 0 { return 0; } let final_str = final_elements.join(separator); self.stack.push(new_string_value(final_str)); } _ => { self.print_error("second join argument must be string"); return 0; } } 1 } pub fn fmt(&mut self, quoted: bool) -> i32 { let str_rr = self.stack.pop().unwrap(); let str_opt: Option<&str>; to_str!(str_rr, str_opt); match str_opt { Some(s) => { let mut updated_str = String::new(); let mut escaping = false; let mut in_substitution = false; let mut substitution_index: Option<usize> = None; let mut stack_cache = Vec::<Option<String>>::new(); for c in s.chars() { if c == '\\' { if escaping { updated_str.push('\\'); escaping = false; } else { escaping = true; } } else if c == '{' { if escaping { updated_str.push('{'); escaping = false; } else if in_substitution { self.print_error("fmt string contains invalid element reference"); return 0; } else { in_substitution = true; } } else if c == '}' { if escaping { updated_str.push('}'); escaping = false; } else if !in_substitution { self.print_error("fmt string contains invalid element reference"); return 0; } else { in_substitution = false; match substitution_index { Some(n) => { if n >= self.stack.len() { self.print_error("fmt string contains invalid stack element reference"); return 0; } let sc_opt = stack_cache.get(n); match sc_opt { Some(Some(sc)) => { updated_str.push_str(sc); } _ => { let capture_el_rr_opt = self.stack.get(self.stack.len() - 1 - n); match capture_el_rr_opt { Some(capture_el_rr) => { let capture_el_str_opt: Option<&str>; to_str!(capture_el_rr, capture_el_str_opt); match capture_el_str_opt { Some(capture_el_str) => { stack_cache.resize(n as usize, None); stack_cache.insert(n as usize, Some(capture_el_str.to_string())); if quoted && capture_el_str.contains(char::is_whitespace) { updated_str.push_str("\""); updated_str.push_str(capture_el_str); updated_str.push_str("\""); } else { updated_str.push_str(capture_el_str); } } _ => { self.print_error("fmt string argument cannot be converted to string"); return 0; } } } None => { self.print_error("fmt string contains invalid stack element reference"); return 0; } } } } } _ => { if self.stack.is_empty() { self.print_error("fmt string has exhausted stack"); return 0; } let value_rr = self.stack.pop().unwrap(); let value_opt: Option<&str>; to_str!(value_rr, value_opt); match value_opt { Some(s) => { if quoted && s.contains(char::is_whitespace) { updated_str.push_str("\""); updated_str.push_str(s); updated_str.push_str("\""); } else { updated_str.push_str(s); } } _ => { self.print_error("fmt string argument cannot be converted to string"); return 0; } } } } } } else if in_substitution { let digit_opt = c.to_digit(10); match digit_opt { Some(n) => { substitution_index = Some(n as usize); } _ => { self.print_error("fmt index is not able to be parsed"); return 0; } } } else { if escaping { updated_str.push('\\'); } updated_str.push(c); escaping = false; } } self.stack.push(new_string_value(updated_str)); 1 } _ => { self.print_error("fmt argument must be a string"); 0 } } } /// Takes a format string as its argument, and substitutes into /// that string values from the stack, as required. pub fn core_fmt(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("fmt requires one argument"); return 0; } return self.fmt(false); } /// Takes a format string as its argument, and substitutes into /// that string quoted values from the stack, as required. pub fn core_fmtq(&mut self) -> i32 { if self.stack.is_empty() { self.print_error("fmtq requires one argument"); return 0; } return self.fmt(true); } }
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
false
tomhrr/cosh
https://github.com/tomhrr/cosh/blob/367a51684662fde5e9abff946538b08e60ea6ea9/tests/tests.rs
tests/tests.rs
extern crate assert_cmd; extern crate cosh; extern crate tempfile; use assert_cmd::Command; use std::env; use std::fs; use std::io::Write; use tempfile::NamedTempFile; #[test] fn add_file() { let mut file = NamedTempFile::new().unwrap(); writeln!(file, "1 2 +").unwrap(); let mut cmd = Command::cargo_bin("cosh").unwrap(); let path = file.path(); let assert = cmd.arg("--no-cosh-conf").arg(path).assert(); assert.success().stdout("3\n"); } fn basic_test(input: &str, output: &str) { let mut file = NamedTempFile::new().unwrap(); writeln!(file, "{}", input).unwrap(); let mut cmd = Command::cargo_bin("cosh").unwrap(); let path = file.path(); let assert = cmd.arg("--no-cosh-conf").arg(path).assert(); let output2 = format!("{}\n", output); assert.success().stdout(output2); } fn basic_test_no_rt(input: &str, output: &str) { let mut file = NamedTempFile::new().unwrap(); writeln!(file, "{}", input).unwrap(); let mut cmd = Command::cargo_bin("cosh").unwrap(); let path = file.path(); let assert = cmd.arg("--no-cosh-conf").arg("--no-rt").arg(path).assert(); let output2 = format!("{}\n", output); assert.success().stdout(output2); } fn basic_error_test(input: &str, output: &str) { let mut file = NamedTempFile::new().unwrap(); writeln!(file, "{}", input).unwrap(); let mut cmd = Command::cargo_bin("cosh").unwrap(); let path = file.path(); let assert = cmd.arg("--no-cosh-conf").arg(path).assert(); assert.success().stderr(output.to_owned() + "\n"); } fn basic_error_test_no_rt(input: &str, output: &str) { let mut file = NamedTempFile::new().unwrap(); writeln!(file, "{}", input).unwrap(); let mut cmd = Command::cargo_bin("cosh").unwrap(); let path = file.path(); let assert = cmd.arg("--no-cosh-conf").arg("--no-rt").arg(path).assert(); assert.success().stderr(output.to_owned() + "\n"); } #[test] fn add() { basic_test_no_rt("1 2 +;", "3"); } #[test] fn subtract() { basic_test("1 2 -;", "-1"); } #[test] fn divide() { basic_test("10 5 /;", "2"); } #[test] fn multiply() { basic_test("10 5 *;", "50"); } #[test] fn combination() { basic_test("10 5 *; 10 +; 20 -; 10 /", "4"); } #[test] fn fn_call() { basic_test(": asdf 1 2 + ; ,, asdf ;", "3"); } #[test] fn vars_basic() { basic_test("x var; 10 x !; x @; 5 +;", "15"); } #[test] fn vars_scoped() { basic_test( concat!( "x var; 10 x !; ", ": asdf x var; 15 x !; ", ": qwer x @; x var; 20 x !; x @; ,, ", "qwer; x @; ,, ", "asdf; x @;" ), "15\n20\n15\n10", ); } #[test] fn if_then() { basic_test("1 if; 2 then; 0 if; 3 then;", "2"); } #[test] fn if_then_multi() { basic_test("1 if; 2 3 4 then; 0 if; 3 then;", "2\n3\n4"); } #[test] fn if_then_else_multi() { basic_test( "1 if; 1 2 3 else; 4 5 6 then; 0 if; 1 2 3 else; 4 5 6 then;", "1\n2\n3\n4\n5\n6", ); } #[test] fn if_then_else_nested() { basic_test("1 if; 0 if; 3 else; 2 then; else; 3 then;", "2"); basic_test("1 if; 2 0 if; 3 then; else; 4 then;", "2"); } #[test] fn begin_until() { basic_test( "x var; 5 x !; begin; x @; println; x @; 1 -; x !; x @; 0 =; until", "5\n4\n3\n2\n1", ); basic_test( "x var; 5 x !; begin; x @; println; leave; x @; 1 -; x !; x @; 0 =; until", "5", ); } #[test] fn begin_until_nested() { basic_test( " x var; 3 x !; y var; begin; 2 y !; begin; y @; println; y @; 1 -; y !; y @; 0 =; until; x @; println; x @; 1 -; x !; x @; 0 =; until;", "2\n1\n3\n2\n1\n2\n2\n1\n1", ); } #[test] fn top_level_functions() { basic_test( ": asdf 1 2 3 ,, : qwer asdf; 1 2 3 ,, qwer;", "1\n2\n3\n1\n2\n3", ); } #[test] fn fn_name_error() { basic_error_test(": 1234 ,,", "1:3: expected name token"); } #[test] fn then_error() { basic_error_test("then;", "1:1: 'then' without 'if'"); } #[test] fn else_error() { basic_error_test(" else;", "1:2: 'else' without 'if'"); } #[test] fn leave_error() { basic_error_test(" leave;", "1:3: 'leave' without 'begin'"); } #[test] fn until_error() { basic_error_test(" until;", "1:3: 'until' without 'begin'"); } #[test] fn add_error() { basic_error_test("1 t +;", "1:5: + requires two numbers"); } #[test] fn subtract_error() { basic_error_test("1 t -;", "1:5: - requires two numbers"); } #[test] fn multiply_error() { basic_error_test("1 t *;", "1:5: * requires two numbers"); } #[test] fn divide_error() { basic_error_test("1 t /;", "1:5: / requires two numbers"); } #[test] fn equals_error() { basic_test("1 t =;", ".f"); } #[test] fn function_not_found_error() { basic_error_test("asdf;", "1:1: function not found"); } #[test] fn var_must_be_string_error() { basic_error_test("1 var;", "1:3: variable name must be a string"); } #[test] fn could_not_find_var_error() { basic_error_test("x @;", "1:3: could not find variable"); } #[test] fn var_must_be_string_2_error() { basic_error_test("1 @;", "1:3: variable name must be a string"); } #[test] fn var_must_be_string_in_fn_error() { basic_error_test( ": m 100 asdf dup; var; !; ,,", "1:19: variable name must precede var", ); } #[test] fn set_must_be_string_in_fn_error() { basic_error_test( ": m asdf var; asdf dup; !; ,,", "1:25: variable name must precede !", ); } #[test] fn get_must_be_string_in_fn_error() { basic_error_test( ": m asdf var; 100 asdf !; asdf dup; @; ,,", "1:37: variable name must precede @", ); } #[test] fn map_test_with_result() { basic_test("(1 2 3) [2 +] map", "v[gen (\n 0: 3\n 1: 4\n 2: 5\n)]"); } #[test] fn grep_test() { basic_test("(1 2 3) [2 =] grep", "v[gen (\n 0: 2\n)]"); } #[test] fn foldl_test() { basic_test("(1 2 3) 0 [+] foldl", "6"); } #[test] fn for_test() { basic_test("(1 2 3) [println] for", "1\n2\n3"); } #[test] fn generator_basic_test() { basic_test(":~ gen 0 0 drop; 1 yield; 2 yield; 3 yield; ,, gen; dup; shift; println; dup; shift; println; shift; println;", "1\n2\n3"); } #[test] fn generator_var_test() { basic_test( " :~ gen 0 0 drop; n var; 0 n !; begin; n @; yield; n @; 1 +; n !; n @; 3 >; until; ,, n var; 100 n !; gen; dup; shift; println; dup; shift; println; shift; println; n @; println;", "0\n1\n2\n100", ); } #[test] fn clear_test() { basic_test("1 2 clear; 3 4", "3\n4"); } #[test] fn dup_test() { basic_test("1 dup; dup;", "1\n1\n1"); } #[test] fn swap_test() { basic_test("1 2 swap;", "2\n1"); } #[test] fn rot_test() { basic_test("1 2 3 rot;", "2\n3\n1"); } #[test] fn over_test() { basic_test("1 2 3 over;", "1\n2\n3\n2"); } #[test] fn depth_test() { basic_test("1 depth; 2 depth; 3 depth;", "1\n1\n2\n3\n3\n5"); } #[test] fn le_test() { basic_test("1 5 <=;", ".t"); basic_test("1 1 <=;", ".t"); basic_test("1 0 <=;", ".f"); } #[test] fn ge_test() { basic_test("1 5 >=;", ".f"); basic_test("1 1 >=;", ".t"); basic_test("1 0 >=;", ".t"); } #[test] fn is_null_test() { basic_test( ":~ nullgen 0 0 drop; ,, nullgen; dup; shift; is-null; nip;", ".t", ); } #[test] fn is_list_test() { basic_test("(1 2 3) is-list;", ".t"); } #[test] fn read_file_test() { basic_test( " : rl dup; readline; print; ,, test-data/readfile r open; rl; rl; rl; rl; rl; drop; ", "1\n2\n3\n4\n5", ); } #[test] fn write_file_test() { basic_test( " test w open; dup; \"asdf\\n\" writeline; dup; \"qwer\\n\" writeline; close; test r open; dup; readline; print; dup; readline; print; close; ", "asdf\nqwer", ); fs::remove_file("test").unwrap(); } #[test] fn lsr_test() { basic_test( ". lsr; begin; dup; shift; is-null; if; leave; then; 0 until;", "v[gen]", ); } #[test] fn implicit_generator_test() { basic_test("lsr; begin; 1 take; drop; ()", "()"); } #[test] fn regex_borrow_problem() { basic_test( "((\"asdf\") (\"asdf\")) [[asdf m] grep] map", "v[gen (\n 0: v[gen (\n 0: asdf\n )]\n 1: v[gen (\n 0: asdf\n )]\n)]", ); } #[test] fn import_test() { basic_test("(1 2 3) sum;", "6"); } #[test] fn push_test() { basic_test( "(1 2 3) 5 push;", "(\n 0: 1\n 1: 2\n 2: 3\n 3: 5\n)", ); } #[test] fn pop_test() { basic_test("(1 2 3) pop;", "3"); } #[test] fn unshift_test() { basic_test( "(1 2 3) 5 unshift;", "(\n 0: 5\n 1: 1\n 2: 2\n 3: 3\n)", ); } #[test] fn shift_test() { basic_test("(1 2 3) shift;", "1"); } #[test] fn file_copy_test() { basic_test("README.md f<; output f>; ()", "()"); let md1 = fs::metadata("README.md").unwrap(); let md2 = fs::metadata("output").unwrap(); assert_eq!(md1.len(), md2.len()); fs::remove_file("output").unwrap(); } #[test] fn single_quote_test() { basic_test("'asdf asdf' println;", "asdf asdf"); } #[test] fn regex_tests() { basic_test("'asdf asdf' asdf m;", ".t"); basic_test("'asdf asdf' asdf/g qwer s;", "\"qwer qwer\""); basic_test( "'12341234' \\d\\d\\d\\d/g c; () ++ foldl", "v[multi-gen (\n 0: 1234\n 1: 1234\n)]", ); } #[test] fn get_test() { basic_test("(1 2 3) 1 get", "2"); basic_test("(1 2 3) 1 100 set", "(\n 0: 1\n 1: 100\n 2: 3\n)"); basic_test("s(1 2 3) 1 get", "2"); basic_test("s(1 2 3 4 5) (0 4 5) get", "(\n 0: 1\n 1: 5\n 2: null\n)"); basic_test("(1.2.3.4) ips; 0 get", "v[ip 1.2.3.4]"); basic_test("(1.2.3.4 2000::) ips; 1 get", "v[ip 2000::]"); basic_test("(1.2.3.4 2000::) ips; 2 get", "null"); } #[test] fn dotted_set_test() { // Basic dotted field specifier test - issue #157 basic_test("((0 0)) 0.1 asdf set", "(\n 0: (\n 0: 0\n 1: asdf\n )\n)"); // Test with nested lists - simple case basic_test("((a b) (c d)) 0.1 xyz set", "(\n 0: (\n 0: a\n 1: xyz\n )\n 1: (\n 0: c\n 1: d\n )\n)"); // Test with 3 levels of nesting basic_test("(((a b) (c d)) ((e f) (g h))) 1.0.1 xyz set", "(\n 0: (\n 0: (\n 0: a\n 1: b\n )\n 1: (\n 0: c\n 1: d\n )\n )\n 1: (\n 0: (\n 0: e\n 1: xyz\n )\n 1: (\n 0: g\n 1: h\n )\n )\n)"); // Test first index access basic_test("((first second) (third fourth)) 1.0 new_first set", "(\n 0: (\n 0: first\n 1: second\n )\n 1: (\n 0: new_first\n 1: fourth\n )\n)"); // Ensure backward compatibility with simple integer indices basic_test("(a b c) 1 xyz set", "(\n 0: a\n 1: xyz\n 2: c\n)"); } #[test] fn take_test() { basic_test("(1 2 3) 2 take", "(\n 0: 1\n 1: 2\n)"); basic_test("(1 2 3) take-all", "(\n 0: 1\n 1: 2\n 2: 3\n)"); basic_test("README.md f<; 1 take", "(\n 0: \"## cosh\\n\"\n)"); } #[test] fn grep_test_generator() { basic_test( "10 range; [5 <] grep; take-all", "(\n 0: 0\n 1: 1\n 2: 2\n 3: 3\n 4: 4\n)", ); basic_test( "10 range; take-all; [5 <] grep", "v[gen (\n 0: 0\n 1: 1\n 2: 2\n 3: 3\n 4: 4\n)]", ); } #[test] fn map_test_generator() { basic_test( "5 range; [2 *] map; take-all", "(\n 0: 0\n 1: 2\n 2: 4\n 3: 6\n 4: 8\n)", ); basic_test( "5 range; take-all; [2 *] map", "v[gen (\n 0: 0\n 1: 2\n 2: 4\n 3: 6\n 4: 8\n)]", ); } #[test] fn split_test() { basic_test("test-data/split f<; take-all; 0 get; , split", "(\n 0: asdf\n 1: qwer\n 2: \"asdf asdf\"\n 3: asdf,asdf\n 4: \"\"\n 5: \"\"\n 6: \"\"\n 7: \"qwer\\n\"\n)"); basic_test("asdf:asdf:asdf \":\" split; \":\" join", "asdf:asdf:asdf"); } #[test] fn join_test() { basic_test_no_rt("(a b c) , join", "a,b,c"); basic_test_no_rt("('a,b' c d) , join", "\\\"a,b\\\",c,d"); basic_test_no_rt("(a,b c d) , join", "\\\"a,b\\\",c,d"); basic_test_no_rt("('a\"b' c d) , join", "\\\"a\\\\\"b\\\",c,d"); // Test for the period separator issue - elements without period should not be quoted basic_test_no_rt("(1 2) . join", "1.2"); // Elements containing the separator should still be quoted basic_test_no_rt("('a.b' c d) . join", "\\\"a.b\\\".c.d"); } #[test] fn append_test() { basic_test("a b ++", "ab"); basic_test( "3 range; take-all; 3 range; take-all; ++", "v[multi-gen (\n 0: 0\n 1: 1\n 2: 2\n 3: 0\n 4: 1\n 5: 2\n)]", ); basic_test("h(1 2) h(3 4) ++; keys; sort; '-' join", "1-3"); } #[test] fn coerce_to_int_test() { basic_test( "test-data/csv f<; [chomp] map; [, split] map; [0 [+] foldl] map; take-all;", "(\n 0: 10\n 1: 26\n 2: 42\n)", ); } #[test] fn coerce_to_string_test() { basic_test("(1 2 3 4 5 6) '' [++] foldl;", "123456"); } #[test] fn commands_test() { basic_test( "{ls}; {sort} |; take-all; [o.toml m] grep; chomp map;", "v[gen (\n 0: Cargo.toml\n)]", ); basic_test(". -type f {find {2} -maxdepth 1 {1} {0}}; {sort} |; take-all; [o.toml m] grep; chomp map; nip; nip; nip;", "v[gen (\n 0: ./Cargo.toml\n)]"); basic_test( "{ls}; -r {sort {}} |; take-all; [o.toml m] grep; chomp map;", "v[gen (\n 0: Cargo.toml\n)]", ); basic_test( "3 2 1 {dc -e \"{2} {0} + {1} + p\"}; shift; chomp; nip; nip; nip;", "6", ); } #[test] fn hash_test() { basic_test("h(1 2 3 4) 1 get;", "2"); basic_test("h(1 2 3 4) 1 5 set; 1 get;", "5"); basic_test("h(1 2 3 4) keys; take-all;", "(\n 0: 3\n 1: 1\n)"); basic_test("h(1 2 3 4) values; take-all;", "(\n 0: 4\n 1: 2\n)"); basic_test( "h(1 2 3 4) each; take-all;", "(\n 0: (\n 0: 3\n 1: 4\n )\n 1: (\n 0: 1\n 1: 2\n )\n)", ); } #[test] fn json_test() { basic_test("'{\"3\":4,\"1\":2}' from-json; 3 get", "4"); basic_test("h(1 2 3 4) to-json", "{\\\"3\\\":4,\\\"1\\\":2}"); basic_test("test-data/json-bigint f<; \"\" join; from-json;", "h(\n \"num1\": 0\n \"num2\": 100\n \"num3\": 123.456\n \"num4\": -123456789123\n \"num5\": 123456789123\n)"); basic_test("test-data/json-bigint f<; from-json;", "h(\n \"num1\": 0\n \"num2\": 100\n \"num3\": 123.456\n \"num4\": -123456789123\n \"num5\": 123456789123\n)"); } #[test] fn json_file_test() { basic_test( "test-data/json1 f<; \"\" join; from-json;", "h(\n \"asdf\": 1\n)", ); basic_test("test-data/json2 f<; \"\" join; from-json;", "h(\n \"asdf\": 1\n \"qwer\": 2\n \"tyui\": h(\n \"asdf\": 5\n )\n \"zxcv\": (\n 0: 3\n 1: 4\n )\n)"); } #[test] fn xml_test() { basic_test( "\"<e a='b'>one<a>two</a>three</e>\" from-xml; to-xml;", "\"<e a=\\\"b\\\">one<a>two</a>three</e>\"", ); } #[test] fn bigint_test_add() { basic_test("1000000000000000000 1 +;", "1000000000000000001"); } #[test] fn float_test_add() { basic_test("1.5 2.4 +;", "3.9"); } #[test] fn bigint_test_subtract() { basic_test("1000000000000000000 1000000000000000001 -;", "-1"); } #[test] fn float_test_subtract() { basic_test("5.5 2.5 -;", "3"); } #[test] fn bigint_test_multiply() { basic_test( "1000000000000000000 1000000000000000001 *;", "1000000000000000001000000000000000000", ); } #[test] fn float_test_multiply() { basic_test("5.5 2.5 *;", "13.75"); } #[test] fn local_var_is_zero() { basic_test(": mfn x var; x @; ,, mfn;", "0"); } #[test] fn global_var_is_zero() { basic_test("x var; x @;", "0"); } #[test] fn nested_function_vars() { /* Now that anonymous functions capture their environment, the 'f * @' calls here do not affect the n in the top function. For the * n in the top function to be affected, it needs to be part of a * reference type, like a list. */ basic_test( " : ff n var; 10 n !; f var; [n @; 1 +; n !] f !; f @; funcall; f @; funcall; n @; ,, ff; ", "10", ); basic_test( " : ff n var; (10) n !; f var; [n @; dup; 0 get; 1 +; 0 swap; set; drop] f !; f @; funcall; f @; funcall; n @; ,, ff; 0 get; ", "12", ); } #[test] fn grep_not_iterated_n_is_the_same() { basic_test( "n var; 10 n !; README.md f<; [n @; 1 +; n !; eeeee m] grep; n @;", "v[gen]\n10", ); } #[test] fn regex_numbers() { basic_test("((asdf asdf)) [[243 m] grep] map", "v[gen (\n 0: v[gen]\n)]"); } #[test] fn negative_numbers() { basic_test("-5 4 +; -6.5 3.2 +;", "-1\n-3.3"); } #[test] fn misc_lst_fns() { basic_test("(1 2 3) [3 =] any", ".t"); basic_test("(1 2 3) [4 =] any", ".f"); basic_test("(1 2 3) [0 >] all", ".t"); basic_test("(1 2 3) [100 >] all", ".f"); basic_test("(1 2 3) [0 >] none", ".f"); basic_test("(1 2 3) [100 >] none", ".t"); basic_test("(1 2 3) [0 >] notall", ".f"); basic_test("(1 2 3) [100 >] notall", ".t"); basic_test("(1 2 3) [2 >] first", "3"); basic_test("(1 2 3) [100 >] first", "null"); basic_test("4 range; dup; shift; drop; product", "6"); basic_test( "(1 2 5 1 2 5 3 6) uniq", "v[gen (\n 0: 1\n 1: 2\n 2: 5\n 3: 3\n 4: 6\n)]", ); basic_test( "(a b 1 b 2) uniq", "v[gen (\n 0: a\n 1: b\n 2: 1\n 3: 2\n)]", ); } #[test] fn return_test() { basic_test(": f ding println; return; ding println; ,, f;", "ding"); } #[test] fn sort_test() { basic_test( "(5 2 3 4 1) sort;", "(\n 0: 1\n 1: 2\n 2: 3\n 3: 4\n 4: 5\n)", ); basic_test( "(5 2 3 4 1) <=> sortp;", "(\n 0: 1\n 1: 2\n 2: 3\n 3: 4\n 4: 5\n)", ); } #[test] fn conv_test() { basic_test("5 int; \"10\" int;", "5\n10"); basic_test("5 str; \"10\" str;", "5\n10"); basic_test("5 float; \"10\" float;", "5\n10"); } #[test] fn search_replace_test() { basic_test("asdf \"(as)(df)\" as\\2\\1df s;", "asdfasdf"); } #[test] fn eq_test() { basic_test("asdf asdf =", ".t"); } #[test] fn nth_bounds_test1() { basic_test( "10 range; take-all; 15 get", "null" ); } #[test] fn nth_bounds_test2() { basic_error_test( "10 range; take-all; 10 15 set", "1:27: second set argument must fall within list bounds", ); } #[test] fn dotted_set_bounds_test() { // Test out of bounds error with dotted field specifier basic_error_test( "((a b)) 1.0 xyz set", "1:18: second set argument must fall within list bounds", ); // Test out of bounds error with deep nesting basic_error_test( "((a b)) 0.2 xyz set", "1:18: second set argument must fall within list bounds", ); } #[test] fn anon_fn_var_test() { basic_test( "3 range; [drop; x var; 3 x !; x @] map;", "v[gen (\n 0: 3\n 1: 3\n 2: 3\n)]", ); } #[test] fn generator_closure_test() { basic_test( " : f x var; 10 x !; : e z var; 20 z !; : q x @; z @; +; 5 +; ,, :~ gen 0 0 drop; y var; 30 y !; begin; y @; q; +; y !; y @; yield; 0 until; ,, gen; ,, e; ,, f; dup; shift; println; dup; shift; println; dup; shift; println; drop; ", "65\n100\n135", ); } #[test] fn anon_fn_test() { basic_test( " : f x var; 10 x !; [x @; 20 +;] ,, f; funcall; ", "30", ); } #[test] fn bool_test() { basic_test(".t if; 1 else; 2 then;", "1"); basic_test(".f if; 1 else; 2 then;", "2"); } #[test] fn json_bool_test() { basic_test("\"[true, false]\" from-json; to-json", "[true,false]"); } #[test] fn comment_test() { basic_test( " # A function. : f 100 ,, f; ", "100", ); basic_test("mystring#allgood", "mystring#allgood"); } #[test] fn clone_test() { basic_test( "3 range; take-all; dup; clone; shift;", "(\n 0: 0\n 1: 1\n 2: 2\n)\n0", ); basic_test( "3 range; dup; clone; take-all; swap; take-all; ++; '-' join;", "0-1-2-0-1-2", ); basic_test("h(1 2) keys; dup; clone; 0 get; swap; 0 get; ++", "11"); basic_test("h(1 2) values; dup; clone; 0 get; swap; 0 get; ++", "22"); } #[test] fn date_test() { basic_test("now; now; =", ".f"); basic_test("date; date; =", ".f"); basic_test("now; now; <", ".t"); basic_test("now; now; >", ".f"); basic_test("now; to-epoch; \\d+ m;", ".t"); basic_test( "now; dup; '%F %T' strftime; swap; to-epoch; from-epoch; '%F %T' strftime; =", ".t", ); basic_test( "1664280627 from-epoch; '%F %T' strftime", "\"2022-09-27 12:10:27\"", ); basic_test("now; dup; '%F %T' strftime; swap; Australia/Brisbane set-tz; UTC set-tz; '%F %T' strftime; =", ".t"); basic_test( "'2022-09-27 12:10:27' '%F %T' strptime; to-epoch;", "1664280627", ); basic_test( "'2022-09-27 22:10:27' '%F %T' Australia/Brisbane strptimez; to-epoch;", "1664280627", ); basic_test( "'2022' '%Y' Australia/Brisbane strptimez; '%F %T %z' strftime;", "\"2022-01-01 00:00:00 +1000\"", ); basic_test("'2022-09-27' '%F' strptime; '%F' strftime;", "2022-09-27"); basic_test( "'2022-09-27' '%F' strptime; '%F %T' strftime;", "\"2022-09-27 00:00:00\"", ); basic_test( "'02' '%H' strptime; '%F %T' strftime;", "\"1970-01-01 02:00:00\"", ); basic_test( "'02 +10:00' '%H %z' strptime; '%F %T %z' strftime;", "\"1970-01-01 02:00:00 +1000\"", ); basic_test("\"2000-01-01 00:00:00\" \"%F %T\" Asia/Vladivostok strptimez; \"2000-01-01 00:00:00 +1000\" \"%F %T %z\" strptime; =", ".t"); basic_test("\"2000-01-01 00:00:00\" \"%F %T\" Asia/Vladivostok strptimez; \"2000-01-01 00:00:00 +1000\" \"%F %T %z\" strptime; <", ".f"); basic_test("\"2000-02-01 00:00:00\" \"%F %T\" Asia/Vladivostok strptimez; \"2000-01-01 00:00:00 +1000\" \"%F %T %z\" strptime; >", ".t"); } #[test] fn ip_test() { basic_test("1.0.0.0/24 ip", "v[ip 1.0.0.0/24]"); basic_test("16777216 4 ip.from-int; str", "1.0.0.0"); basic_test("1.0.0.0/24 ip; ip.addr", "1.0.0.0"); basic_test("3.1.0.0/16 ip; ip.len", "16"); basic_test("0.0.0.0/0 ip; ip.addr-int", "0"); basic_test("16.0.0.0/7 ip; ip.last-addr", "17.255.255.255"); basic_test("16.0.0.0/7 ip; ip.last-addr-int", "301989887"); basic_test("1.0.0.0/24 ip; ip.size", "256"); basic_test("1.0.0.0/24 ip; ip.version", "4"); basic_test("1.0.0.0/24 ip; str", "1.0.0.0/24"); basic_test("::/128 ip", "v[ip ::]"); basic_test("10000000000 6 ip.from-int; str", "::2:540b:e400"); basic_test("31CC::/64 ip; ip.addr", "31cc::"); basic_test("305F:305F::/32 ip; ip.len", "32"); basic_test("::2:540b:e400 ip; ip.addr-int", "10000000000"); basic_test( "3000::/16 ip; ip.last-addr", "3000:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ); basic_test( "3000::/16 ip; ip.last-addr-int", "63808136094534496727011269389785759743", ); basic_test("::/112 ip; ip.size", "65536"); basic_test(":: ip; ip.version", "6"); basic_test("ABCD::/32 ip; str", "abcd::/32"); basic_test("1.0.0.0-1.0.0.255 ip", "v[ip 1.0.0.0-1.0.0.255]"); basic_test("1.0.0.0-1.0.0.255 ip; ip.addr", "1.0.0.0"); basic_test("3.1.0.0-3.1.255.255 ip; ip.len", "16"); basic_test("0.0.0.0-255.255.255.255 ip; ip.addr-int", "0"); basic_test("16.0.0.0-17.255.255.255 ip; ip.last-addr", "17.255.255.255"); basic_test("16.0.0.0-17.255.255.255 ip; ip.last-addr-int", "301989887"); basic_test("1.0.0.0-1.0.0.255 ip; ip.size", "256"); basic_test("1.0.0.0-1.0.0.255 ip; ip.version", "4"); basic_test("1.0.0.0-1.0.0.255 ip; str", "1.0.0.0-1.0.0.255"); basic_test("31CC::-31CC::ffff:ffff:ffff:ffff ip; ip.addr", "31cc::"); basic_test( "305F:305F::-305F:305F:ffff:ffff:ffff:ffff:ffff:ffff ip; ip.len", "32", ); basic_test("::2:540b:e400 ip; ip.addr-int", "10000000000"); basic_test( "3000::-3000:ffff:ffff:ffff:ffff:ffff:ffff:ffff ip; ip.last-addr", "3000:ffff:ffff:ffff:ffff:ffff:ffff:ffff", ); basic_test( "3000::-3000:ffff:ffff:ffff:ffff:ffff:ffff:ffff ip; ip.last-addr-int", "63808136094534496727011269389785759743", ); basic_test("::/112 ip; ip.size", "65536"); basic_test(":: ip; ip.version", "6"); basic_test( "ABCD::-ABCD:0000:ffff:ffff:ffff:ffff:ffff:ffff ip; str", "abcd::-abcd:0:ffff:ffff:ffff:ffff:ffff:ffff", ); } #[test] fn ipset_test() { basic_test( "0.0.0.0-1.0.0.0 ip; ip.prefixes; str map;", "v[gen (\n 0: 0.0.0.0/8\n 1: 1.0.0.0\n)]", ); basic_test( "0.0.0.0-1.0.0.0 ips; take-all; str map;", "v[gen (\n 0: 0.0.0.0/8\n 1: 1.0.0.0\n)]", ); basic_test("::-FFFF:: ip; ip.prefixes; str map;", "v[gen (\n 0: ::/1\n 1: 8000::/2\n 2: c000::/3\n 3: e000::/4\n 4: f000::/5\n 5: f800::/6\n 6: fc00::/7\n 7: fe00::/8\n 8: ff00::/9\n 9: ff80::/10\n 10: ffc0::/11\n 11: ffe0::/12\n 12: fff0::/13\n 13: fff8::/14\n 14: fffc::/15\n 15: fffe::/16\n 16: ffff::\n)]"); basic_test("::-FFFF:: ips; take-all; str map;", "v[gen (\n 0: ::/1\n 1: 8000::/2\n 2: c000::/3\n 3: e000::/4\n 4: f000::/5\n 5: f800::/6\n 6: fc00::/7\n 7: fe00::/8\n 8: ff00::/9\n 9: ff80::/10\n 10: ffc0::/11\n 11: ffe0::/12\n 12: fff0::/13\n 13: fff8::/14\n 14: fffc::/15\n 15: fffe::/16\n 16: ffff::\n)]"); basic_test( "1.0.0.0/8 ip; ip.prefixes; str map;", "v[gen (\n 0: 1.0.0.0/8\n)]", ); basic_test("0.0.0.251-0.0.5.16 ip; ip.prefixes; str map;", "v[gen (\n 0: 0.0.0.251\n 1: 0.0.0.252/30\n 2: 0.0.1.0/24\n 3: 0.0.2.0/23\n 4: 0.0.4.0/24\n 5: 0.0.5.0/28\n 6: 0.0.5.16\n)]"); basic_test("::/120 ip; ip.prefixes; str map;", "v[gen (\n 0: ::/120\n)]"); basic_test("1:0:0:0:0:0:0:1-1:0:0:0:0:0:0:8000 ip; ip.prefixes; str map;", "v[gen (\n 0: 1::1\n 1: 1::2/127\n 2: 1::4/126\n 3: 1::8/125\n 4: 1::10/124\n 5: 1::20/123\n 6: 1::40/122\n 7: 1::80/121\n 8: 1::100/120\n 9: 1::200/119\n 10: 1::400/118\n 11: 1::800/117\n 12: 1::1000/116\n 13: 1::2000/115\n 14: 1::4000/114\n 15: 1::8000\n)]"); basic_test("(0.0.0.0/8 1.0.0.0/8) ips; str", "0.0.0.0/7"); basic_test("(:: ::1) ips; str", "::/127"); basic_test("(::) ips; ::1 ips; union; str", "::/127"); basic_test( "1.0.0.0-1.255.255.255 ips; 1.128.0.0-2.255.255.255 ips; isect; str", "1.128.0.0/9", ); basic_test( "1.0.0.0-1.255.255.255 ips; 1.128.0.0-2.255.255.255 ips; diff; str", "1.0.0.0/9", ); basic_test( "1.0.0.0-1.255.255.255 ips; 1.128.0.0-2.255.255.255 ips; symdiff; str", "1.0.0.0/9,2.0.0.0/8", ); basic_test( "1.0.0.0-1.255.255.255 ips; take-all; str map", "v[gen (\n 0: 1.0.0.0/8\n)]", ); basic_test("1.0.0.0-1.255.255.255 ips; dup; =;", ".t"); basic_test( "1.0.0.0-255.255.255.255 ips; take-all; shift; str;", "1.0.0.0/8", ); } #[test] fn set_test() { basic_test("s(1 2 3) 4 push;", "s(\n 1\n 2\n 3\n 4\n)"); basic_test( "s(1 2 3) s(2 3 4) union;", "s(\n 1\n 2\n 3\n 4\n)", ); basic_test("s(1 2 3) s(2 3 4) isect;", "s(\n 2\n 3\n)"); basic_test("s(1 2 3) s(2 3 4) diff;", "s(\n 1\n)"); basic_test("s(1 2 3) s(2 3 4) symdiff;", "s(\n 1\n 4\n)"); basic_test("s(1 2 3) dup; shift;", "s(\n 2\n 3\n)\n1"); } #[test] fn nested_set_test() { // Test that nested sets display without element indices basic_test_no_rt("(s(1 2) s(3 4))", "(\n 0: s(\n 1\n 2\n )\n 1: s(\n 3\n 4\n )\n)"); // Test deeply nested sets basic_test_no_rt("((s(1 2)))", "(\n 0: (\n 0: s(\n 1\n 2\n )\n )\n)"); // Test single nested set basic_test_no_rt("(s(1))", "(\n 0: s(\n 1\n )\n)"); } #[test] fn predicate_test() { basic_test(".t is-bool;", ".t"); basic_test(".f is-bool;", ".t"); basic_test("100 is-bool;", ".f"); basic_test("1000 is-int;", ".t"); basic_test("0 is-int;", ".t"); basic_test("10.0 is-int;", ".f"); basic_test("10000000000000000000000000000000000 is-int;", ".f"); basic_test("1000 is-bigint;", ".f"); basic_test("10000000000000000000000000000000000 is-bigint;", ".t"); basic_test("1000 is-str;", ".f"); basic_test("\"1000\" is-str;", ".t"); basic_test("asdf is-str;", ".t"); basic_test("s(1 2 3) is-str;", ".f"); basic_test("1 is-float;", ".f"); basic_test("1.0 float; is-float;", ".t"); basic_test("asdf is-float;", ".f"); basic_test("\"1.0\" is-float;", ".f"); } #[test] fn bigint_conversion_test() { basic_test("1 bigint;", "1"); basic_test( "1000000000000000000000000 bigint;", "1000000000000000000000000", ); basic_test("asdf bigint;", "null"); } #[test] fn chr_test() { basic_test("100 chr;", "d"); basic_test("100 bigint; chr;", "d"); basic_error_test("-100 bigint; chr", "1:14: chr argument must be u32 integer"); } #[test] fn ord_test() { basic_test("d ord;", "100"); basic_test("千 ord;", "21315"); basic_error_test( "asdf ord;", "1:6: ord argument must be one character in length", ); } #[test] fn hex_test() { basic_test("5353 unhex;", "21331"); basic_test("5353 unhex; hex;", "5353"); basic_test("5353 unhex; hex; unhex", "21331"); basic_test("0x5353 unhex;", "21331"); basic_test("0x5353535353535353 unhex;", "6004234345560363859"); basic_error_test("asdf unhex;", "1:6: unhex argument must be hexadecimal string"); } #[test] fn oct_test() { basic_test("777 unoct;", "511"); basic_test("777 unoct; oct;", "777"); } #[test] fn lc_test() { basic_test("AsDf lc;", "asdf"); basic_error_test("[] lc;", "1:4: lc argument must be string"); } #[test] fn lcfirst_test() { basic_test("'' lcfirst;", "\"\""); basic_test("AsDf lcfirst;", "asDf"); basic_error_test("[] lcfirst;", "1:4: lcfirst argument must be string"); } #[test] fn uc_test() { basic_test("AsDf uc;", "ASDF"); basic_error_test("[] uc;", "1:4: uc argument must be string"); } #[test] fn ucfirst_test() { basic_test("'' ucfirst;", "\"\""); basic_test("asDf ucfirst;", "AsDf"); basic_error_test("[] ucfirst;", "1:4: ucfirst argument must be string"); } #[test] fn reverse_test() { basic_test("(1 2 3) reverse;", "(\n 0: 3\n 1: 2\n 2: 1\n)"); basic_test("asdf reverse;", "fdsa"); } #[test] fn sqrt_test() { basic_test("100 sqrt;", "10"); basic_test("100.0 sqrt;", "10"); basic_test("1 sqrt;", "1"); } #[test] fn exp_test() { basic_test("2 2 **;", "4"); basic_test("100000000000000 50 **;", "10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); basic_test("\"100\" \"2.0\" **;", "10000"); } #[test] fn abs_test() { basic_test("-100 abs;", "100"); basic_test("-100.50 abs;", "100.5"); basic_test("-10000000000000 abs;", "10000000000000"); } #[test]
rust
BSD-3-Clause
367a51684662fde5e9abff946538b08e60ea6ea9
2026-01-04T20:18:56.825981Z
true
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/inventory.rs
src/inventory.rs
use crate::bad_json::deserialize_bad_location_as_none; use crate::ErrorResponse; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize)] pub(crate) struct MoveItemRequest<'a, T> { pub(crate) data: &'a [T], pub(crate) tm: u64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct RagfairResponseData { pub(crate) items: serde_json::Value, #[serde(rename = "badRequest")] pub(crate) errors: Vec<ErrorResponse>, } /// Changes to the player's inventory after interacting with traders or the flea market. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct InventoryUpdate { /// New items in inventory. pub new: Option<Vec<Item>>, /// Changed items in inventory. pub change: Option<Vec<Item>>, /// Deleted items in inventory. pub del: Option<Vec<DeletedItem>>, } /// Item deleted from inventory. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DeletedItem { /// Item ID #[serde(rename = "_id")] pub id: String, } /// In-game item #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Item { /// Item ID #[serde(rename = "_id")] pub id: String, /// Item localization schema ID #[serde(rename = "_tpl")] pub schema_id: String, /// Item parent ID pub parent_id: Option<String>, /// Item slot ID pub slot_id: Option<String>, /// Item attachments/options pub upd: Option<Upd>, /// Item location #[serde(default, deserialize_with = "deserialize_bad_location_as_none")] pub location: Option<Location>, } /// Item location #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Location { /// Inventory slot x pub x: u64, /// Inventory slot y pub y: u64, /// Inventory slot rotation pub r: u64, /// Item is searched (if searchable) pub is_searched: Option<bool>, } /// Item options #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Upd { /// Item stack count pub stack_objects_count: Option<u64>, /// Item spawned in session pub spawned_in_session: Option<bool>, /// Item is medkit pub med_kit: Option<UpdMedkit>, /// Item is repairable pub repairable: Option<UpdRepairable>, /// Item has a light attachment pub light: Option<UpdLight>, /// Unlimited stack pub unlimited_count: Option<bool>, /// ? pub buy_restriction_max: Option<u64>, /// ? pub buy_restriction_current: Option<u64>, /// Key info pub key: Option<UpdKey>, /// Tag info pub tag: Option<UpdTag>, } /// Medkit item info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct UpdMedkit { /// Health pub hp_resource: f64, } /// Repairable item info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct UpdRepairable { /// Maximum durability pub max_durability: Option<f64>, /// Current durability pub durability: f64, } /// Light attachment info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct UpdLight { /// Light is active pub is_active: bool, /// Light mode pub selected_mode: u64, } /// Key info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct UpdKey { /// Number of usage pub number_of_usages: u64, } /// Tag info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct UpdTag { /// Color pub color: u64, /// Name pub name: String, } /// Inventory item for trading. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct BarterItem { /// Item ID from player's inventory. pub id: String, /// Amount of items. pub count: f64, }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/lib.rs
src/lib.rs
//! An unofficial client library for the [Escape from Tarkov](https://escapefromtarkov.com) (EFT) API. //! //! To get started, login to EFT with `Tarkov::login`, `from_access_token`, or `from_session`. //! Additionally, on a new session, a profile must be selected with `select_profile` before continuing. //! //! Once authenticated, the resulting value can be used to make further API requests. //! //! See [Tarkov](struct.Tarkov.html) for a list of available methods. //! //! For examples, see the `examples` directory in the source tree. #![warn(missing_docs)] use crate::auth::LoginError; use crate::hwid::generate_hwid; use crate::profile::ProfileError; use crate::ragfair::RagfairError; use crate::trading::TradingError; use err_derive::Error; use flate2::read::ZlibDecoder; use hyper::body::Buf; use hyper::client::connect::dns::GaiResolver; use hyper::client::{Client, HttpConnector}; use hyper::Body; use hyper::Request; use hyper::{Method, StatusCode}; use hyper_tls::HttpsConnector; use log::debug; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::io::Read; const GAME_VERSION: &str = "0.12.7.9018"; const LAUNCHER_VERSION: &str = "10.2.0.1149"; const UNITY_VERSION: &str = "2018.4.13f1"; const LAUNCHER_ENDPOINT: &str = "https://launcher.escapefromtarkov.com"; const PROD_ENDPOINT: &str = "https://prod.escapefromtarkov.com"; const TRADING_ENDPOINT: &str = "https://trading.escapefromtarkov.com"; const RAGFAIR_ENDPOINT: &str = "https://ragfair.escapefromtarkov.com"; mod bad_json; /// Structs for authentication. pub mod auth; /// Structs for game constants API. pub mod constant; /// Structs for the Friend API. pub mod friend; /// Helper functions for hardware ID. pub mod hwid; /// Structs for inventory and items. pub mod inventory; /// Flea market search helpers. pub mod market_filter; /// Structs for the Profile API. pub mod profile; /// Structs for the Flea Market (Ragfair) API. pub mod ragfair; /// Structs for the Trading API. pub mod trading; /// Common error enum returned by most functions. #[derive(Debug, Error)] pub enum Error { /// A `std::io` error #[error(display = "io error: {}", _0)] Io(#[error(source)] std::io::Error), /// HTTP request error. #[error(display = "http error: {}", _0)] Http(#[error(source)] http::Error), /// A `hyper` crate error. #[error(display = "hyper error: {}", _0)] Hyper(#[error(source)] hyper::Error), /// A `serde_json` error. #[error(display = "json error: {}", _0)] Json(#[error(source)] serde_json::error::Error), /// Generic non-success response from the API. #[error(display = "non-success response from api: {}", _0)] Status(StatusCode), /// Invalid or missing parameters. #[error(display = "invalid or missing login parameters")] InvalidParameters, /// Unidentified error within the EFT API. #[error(display = "unidentified login error with error code: {}", _0)] UnknownAPIError(u64), /// Not authorized to API or profile is not selected. #[error(display = "not authorized or game profile not selected")] NotAuthorized, /// EFT API is down for maintenance. #[error(display = "api is down for maintenance")] Maintenance, /// Backend error. No other information is given. #[error(display = "backend error")] BackendError, /// Authentication API error. #[error(display = "login api error: {}", _0)] LoginError(#[error(source)] LoginError), /// Profile API error. #[error(display = "profile api error: {}", _0)] ProfileError(#[error(source)] ProfileError), /// Trading API error. #[error(display = "trading api error: {}", _0)] TradingError(#[error(source)] TradingError), /// Ragfair API error. #[error(display = "trading api error: {}", _0)] RagfairError(#[error(source)] RagfairError), } /// `Result` alias type. pub type Result<T> = std::result::Result<T, Error>; #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] struct ErrorResponse { #[serde(rename = "err")] code: u64, #[serde(rename = "errmsg")] message: Option<String>, } /// Client for the EFT API. pub struct Tarkov { client: Client<HttpsConnector<HttpConnector<GaiResolver>>, Body>, /// Hardware ID pub hwid: String, /// Session cookie pub session: String, } impl Tarkov { /// Login with email and password. pub async fn login(email: &str, password: &str, hwid: &str) -> Result<Self> { if email.is_empty() || password.is_empty() || hwid.is_empty() { return Err(Error::InvalidParameters); } let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); let user = auth::login(&client, email, password, None, &hwid).await?; let session = auth::exchange_access_token(&client, &user.access_token, &hwid).await?; Ok(Tarkov { client, hwid: hwid.to_string(), session: session.session, }) } /// Login with email, password and captcha. pub async fn login_with_captcha( email: &str, password: &str, captcha: &str, hwid: &str, ) -> Result<Self> { if email.is_empty() || password.is_empty() || captcha.is_empty() || hwid.is_empty() { return Err(Error::InvalidParameters); } let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); let user = auth::login(&client, email, password, Some(captcha), &hwid).await?; let session = auth::exchange_access_token(&client, &user.access_token, &hwid).await?; Ok(Tarkov { client, hwid: hwid.to_string(), session: session.session, }) } /// Login with email, password and 2FA code. pub async fn login_with_2fa( email: &str, password: &str, code: &str, hwid: &str, ) -> Result<Self> { if email.is_empty() || password.is_empty() || code.is_empty() || hwid.is_empty() { return Err(Error::InvalidParameters); } let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); let _ = auth::activate_hardware(&client, email, code, &hwid).await?; let user = auth::login(&client, email, password, None, &hwid).await?; let session = auth::exchange_access_token(&client, &user.access_token, &hwid).await?; Ok(Tarkov { client, hwid: hwid.to_string(), session: session.session, }) } /// Login with a Bearer token. pub async fn from_access_token(access_token: &str, hwid: &str) -> Result<Self> { if access_token.is_empty() || hwid.is_empty() { return Err(Error::InvalidParameters); } let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); let session = auth::exchange_access_token(&client, &access_token, &hwid).await?; Ok(Tarkov { client, hwid: hwid.to_string(), session: session.session, }) } /// Login with a cookie session (AKA `PHPSESSID`). pub fn from_session(session: &str) -> Self { let https = HttpsConnector::new(); let client = Client::builder().build::<_, Body>(https); Tarkov { client, hwid: generate_hwid(), session: session.to_string(), } } async fn post_json<S, T>(&self, url: &str, body: &S) -> Result<T> where S: serde::Serialize + ?Sized + std::fmt::Debug, T: DeserializeOwned, { debug!("Sending request to {} ({:?})", url, body); let body = match serde_json::to_string(&body) { Ok(body) => Ok(Body::from(if body == "null" { "{}".to_string() } else { body })), Err(e) => Err(e), }?; let req = Request::builder() .uri(url) .method(Method::POST) .header("Content-Type", "application/json") .header( "User-Agent", format!( "UnityPlayer/{} (UnityWebRequest/1.0, libcurl/7.52.0-DEV)", UNITY_VERSION ), ) .header("App-Version", format!("EFT Client {}", GAME_VERSION)) .header("X-Unity-Version", UNITY_VERSION) .header("Cookie", format!("PHPSESSID={}", self.session)) .body(body)?; let res = self.client.request(req).await?; match res.status() { StatusCode::OK => { let body = hyper::body::to_bytes(res.into_body()).await?; let mut decode = ZlibDecoder::new(body.bytes()); let mut body = String::new(); decode.read_to_string(&mut body)?; debug!("Response: {}", body); Ok(serde_json::from_slice::<T>(body.as_bytes())?) } _ => Err(Error::Status(res.status())), } } } pub(crate) fn handle_error<T: DeserializeOwned>(error: ErrorResponse, ret: Option<T>) -> Result<T> { handle_error2(error)?; Ok(ret.expect("API returned no errors but `data` is unavailable.")) } pub(crate) fn handle_error2(error: ErrorResponse) -> Result<()> { match error.code { 0 => Ok(()), 201 => Err(Error::NotAuthorized)?, 205 => Err(ProfileError::InvalidUserID)?, 206 => Err(LoginError::BadLogin)?, 207 => Err(Error::InvalidParameters)?, 209 => Err(LoginError::TwoFactorRequired)?, 211 => Err(LoginError::BadTwoFactorCode)?, 214 => Err(LoginError::CaptchaRequired)?, 228 => Err(RagfairError::InvalidBarterItems)?, 230 => Err(LoginError::RateLimited)?, 232 => Err(LoginError::WrongMajorVersion)?, 263 => Err(Error::Maintenance)?, 1000 => Err(Error::BackendError)?, 1501 => Err(RagfairError::MaxOfferCount)?, 1502 => Err(RagfairError::InsufficientTaxFunds)?, 1507 => Err(RagfairError::OfferNotFound)?, 1510 => Err(TradingError::BadLoyaltyLevel)?, 1512 => Err(RagfairError::OfferNotAvailableYet)?, 1514 => Err(TradingError::TransactionError)?, _ => Err(Error::UnknownAPIError(error.code)), } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/hwid.rs
src/hwid.rs
use rand::Rng; fn random_md5<R: Rng + ?Sized>(rng: &mut R) -> String { format!("{:x}", md5::compute(&rng.gen::<i32>().to_le_bytes())) } /// Generate a random EFT compatible HWID. pub fn generate_hwid() -> String { let mut rng = rand::thread_rng(); let short_md5 = { let mut hash = random_md5(&mut rng); hash.truncate(hash.len() - 8); hash }; format!( "#1-{}:{}:{}-{}-{}-{}-{}-{}", random_md5(&mut rng), random_md5(&mut rng), random_md5(&mut rng), random_md5(&mut rng), random_md5(&mut rng), random_md5(&mut rng), random_md5(&mut rng), short_md5 ) } #[test] fn test_generate_hwid() { assert_eq!(generate_hwid().len(), 258) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/market_filter.rs
src/market_filter.rs
use serde_repr::Serialize_repr; /// Search filter for the flea market. #[derive(Debug, Clone, PartialEq)] pub struct MarketFilter<'a> { /// Sort type. pub sort_type: SortBy, /// Sort direction. pub sort_direction: SortDirection, /// Offer currency type. pub currency: Currency, /// Minimum item price. pub min_price: Option<u64>, /// Maximum item price. pub max_price: Option<u64>, /// Minimum item quantity. pub min_quantity: Option<u64>, /// Maximum item quantity. pub max_quantity: Option<u64>, /// Minimum item condition percentage. pub min_condition: Option<u64>, /// Maximum item condition percentage. pub max_condition: Option<u64>, /// Show offers expiring soon. pub expiring_within_hour: bool, /// Hide offers asking for items for trade. pub hide_bartering_offers: bool, /// Offer owner type. pub owner_type: Owner, /// Hide inoperable weapons. pub hide_inoperable_weapons: bool, /// Search by market category or item ID. pub handbook_id: Option<&'a str>, /// Search item related to item ID. pub linked_search_id: Option<&'a str>, /// Search items that can be traded for item ID. pub required_search_id: Option<&'a str>, } /// Sort by categories. #[derive(Serialize_repr, Debug, Clone, PartialEq)] #[repr(u8)] pub enum SortBy { /// Sort by ID ID = 0, /// Sort by bartering offers BarteringOffers = 2, /// Sort by merchant rating MerchantRating = 3, /// Sort by price (default) Price = 5, /// Sort by expiry Expiry = 6, } /// Sort by direction. #[derive(Serialize_repr, Debug, Clone, PartialEq)] #[repr(u8)] pub enum SortDirection { /// Sort ascending (default) Ascending = 0, /// Sort descending Descending = 1, } /// Currency types. #[derive(Serialize_repr, Debug, Clone, PartialEq)] #[repr(u8)] pub enum Currency { /// Any currency (default) Any = 0, /// Rouble Rouble = 1, /// US dollar Dollar = 2, /// Euro Euro = 3, } /// Item listed by. #[derive(Serialize_repr, Debug, Clone, PartialEq)] #[repr(u8)] pub enum Owner { /// Any owner (default) Any = 0, /// Item listed by traders Traders = 1, /// Item listed by players Player = 2, } impl<'a> Default for MarketFilter<'a> { fn default() -> Self { Self { sort_type: SortBy::Price, sort_direction: SortDirection::Ascending, currency: Currency::Any, min_price: None, max_price: None, min_quantity: None, max_quantity: None, min_condition: None, max_condition: Some(100), expiring_within_hour: false, hide_bartering_offers: false, owner_type: Owner::Any, hide_inoperable_weapons: true, handbook_id: None, linked_search_id: None, required_search_id: None, } } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/trading.rs
src/trading.rs
use crate::inventory::{ BarterItem, InventoryUpdate, Item, MoveItemRequest, RagfairResponseData, Upd, }; use crate::{ handle_error, handle_error2, Error, ErrorResponse, Result, Tarkov, PROD_ENDPOINT, TRADING_ENDPOINT, }; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// Trading error #[derive(Debug, err_derive::Error)] pub enum TradingError { /// Transaction error #[error(display = "transaction error")] TransactionError, /// Loyalty level is not high enough to purchase this item. #[error(display = "bad loyalty level")] BadLoyaltyLevel, } /// Trader info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Trader { /// Trader ID #[serde(rename = "_id")] pub id: String, /// Trader is working pub working: bool, /// ? pub customization_seller: bool, /// Trader name pub name: String, /// Trader surname pub surname: String, /// Trader nickname pub nickname: String, /// Trader location pub location: String, /// Trader avatar pub avatar: String, /// Trader rouble balance pub balance_rub: u64, /// Trader dollar balance pub balance_dol: u64, /// Trader euro balance pub balance_eur: u64, /// ? pub display: bool, /// Trader discount pub discount: i64, /// Trader discount expiry pub discount_end: i64, /// ? pub buyer_up: bool, /// Trader currency pub currency: Currency, /// Resupply time pub supply_next_time: u64, /// Trader repair offer pub repair: Repair, /// Trader insurance offer pub insurance: Insurance, /// Trader grid height #[serde(rename = "gridHeight")] pub grid_height: u64, /// Trader loyalty pub loyalty: Loyalty, /// Unknown type pub sell_category: Vec<serde_json::Value>, } /// Trader's repair stats #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Repair { /// Repair is available pub availability: bool, /// Repair quality pub quality: String, /// Item IDs excluded from repair. pub excluded_id_list: Vec<String>, /// Category IDs excluded from repair. pub excluded_category: Vec<String>, /// Currency pub currency: Option<String>, /// ? pub currency_coefficient: Option<u64>, /// Repair price rate pub price_rate: u64, } /// Trader currency #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub enum Currency { /// Rouble #[serde(rename = "RUB")] Rouble, /// US Dollar #[serde(rename = "USD")] Dollar, /// Euro #[serde(rename = "EUR")] Euro, } /// Trader's insurance offer #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Insurance { /// Insurance is available pub availability: bool, /// Minimum cost to insure pub min_payment: u64, /// Minimum return time in hours. pub min_return_hour: u64, /// Maximum return time in hours. pub max_return_hour: u64, /// Maximum storage time in hours. pub max_storage_time: u64, /// Categories IDs excluded from insurance. pub excluded_category: Vec<String>, } /// Trader loyalty #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Loyalty { /// Current loyalty level pub current_level: u64, /// Current loyalty standing pub current_standing: f64, /// Amount spent on trader pub current_sales_sum: u64, /// All loyalty levels pub loyalty_levels: HashMap<String, LoyaltyLevel>, } /// Trader loyalty level #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct LoyaltyLevel { /// Minimum level pub min_level: u64, /// Minimum sales amount pub min_sales_sum: u64, /// Minimum standing pub min_standing: f64, } #[derive(Debug, Deserialize)] struct TradersResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Vec<Trader>>, } #[derive(Debug, Deserialize)] struct TraderResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Trader>, } #[derive(Debug, Deserialize)] struct TraderItemsResponse { #[serde(flatten)] error: ErrorResponse, data: Option<TraderItems>, } #[derive(Debug, Deserialize)] struct TraderItems { items: Vec<Item>, barter_scheme: HashMap<String, Vec<Vec<Price>>>, loyal_level_items: HashMap<String, u8>, } #[derive(Debug, Deserialize)] struct TraderPricesResponse { #[serde(flatten)] error: ErrorResponse, data: Option<HashMap<String, Vec<Vec<Price>>>>, } /// Trader item price #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Price { /// Item localization schema ID #[serde(rename = "_tpl")] pub schema_id: String, /// Item count pub count: f64, } /// Item for trade #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct TraderItem { /// Item ID pub id: String, /// Item localization schema ID pub schema_id: String, /// Item attachments/options pub upd: Option<Upd>, /// Item price pub price: Vec<Price>, /// Loyalty level pub loyalty_level: u8, } #[derive(Debug, Serialize)] struct TradeItemRequest<'a> { #[serde(rename = "Action")] action: &'a str, #[serde(rename = "type")] trade_type: &'a str, #[serde(rename = "tid")] trader_id: &'a str, item_id: &'a str, count: u64, scheme_id: u64, scheme_items: &'a [BarterItem], } #[derive(Debug, Deserialize)] struct TradeResponse { #[serde(flatten)] error: ErrorResponse, data: serde_json::Value, } #[derive(Debug, Serialize)] struct SellItemRequest<'a> { #[serde(rename = "Action")] action: &'a str, #[serde(rename = "type")] trade_type: &'a str, #[serde(rename = "tid")] trader_id: &'a str, items: &'a [SellItem], } #[derive(Debug, Serialize)] struct SellItem { id: String, count: u64, scheme_id: u64, } #[derive(Debug, Deserialize)] struct SellResponse { #[serde(flatten)] error: ErrorResponse, } impl Tarkov { /// Get a list of all traders. pub async fn get_traders(&self) -> Result<Vec<Trader>> { let url = format!("{}/client/trading/api/getTradersList", TRADING_ENDPOINT); let res: TradersResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } /// Get a trader by ID. pub async fn get_trader(&self, trader_id: &str) -> Result<Trader> { if trader_id.is_empty() { return Err(Error::InvalidParameters); } let url = format!( "{}/client/trading/api/getTrader/{}", TRADING_ENDPOINT, trader_id ); let res: TraderResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } async fn get_trader_items_raw(&self, trader_id: &str) -> Result<TraderItems> { let url = format!( "{}/client/trading/api/getTraderAssort/{}", TRADING_ENDPOINT, trader_id ); let res: TraderItemsResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } async fn get_trader_prices_raw( &self, trader_id: &str, ) -> Result<HashMap<String, Vec<Vec<Price>>>> { let url = format!( "{}/client/trading/api/getUserAssortPrice/trader/{}", TRADING_ENDPOINT, trader_id ); let res: TraderPricesResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } /// Get a list of items for sale by trader ID. pub async fn get_trader_items(&self, trader_id: &str) -> Result<Vec<TraderItem>> { if trader_id.is_empty() { return Err(Error::InvalidParameters); } let mut result: Vec<TraderItem> = Vec::new(); let items = self.get_trader_items_raw(trader_id).await?; let prices = self.get_trader_prices_raw(trader_id).await?; for item in items.items { // TODO: Properly deal with parent/children items if item.parent_id != Some("hideout".to_string()) { continue; } let loyalty_level = items .loyal_level_items .get(&item.id) .expect("Loyalty level could not be mapped."); let price = { let barter_or_price = match items.barter_scheme.get(&item.id) { None => prices .get(&item.id) .expect("Item price could not be mapped."), Some(barter) => barter, }; barter_or_price.get(0) }; let trader_item = TraderItem { id: item.id, schema_id: item.schema_id, upd: item.upd, price: price.expect("Item price could not be mapped.").clone(), loyalty_level: *loyalty_level, }; result.push(trader_item); } Ok(result) } /// Trade items with traders. /// /// All trades, including cash trades, are considered bartering. `barter_items` expects a /// list of items from your inventory that matches the item price. pub async fn trade_item( &self, trader_id: &str, item_id: &str, quantity: u64, barter_items: &[BarterItem], ) -> Result<InventoryUpdate> { if trader_id.is_empty() || item_id.is_empty() || quantity == 0 || barter_items.is_empty() { return Err(Error::InvalidParameters); } let url = format!("{}/client/game/profile/items/moving", PROD_ENDPOINT); let body = MoveItemRequest { data: &[TradeItemRequest { action: "TradingConfirm", trade_type: "buy_from_trader", trader_id, item_id, count: quantity, scheme_id: 0, scheme_items: barter_items, }], tm: 0, }; let res: TradeResponse = self.post_json(&url, &body).await?; handle_error2(res.error)?; let res: RagfairResponseData = Deserialize::deserialize(res.data)?; if !res.errors.is_empty() { let error = &res.errors[0]; return Err(Error::UnknownAPIError(error.code)); } let items: InventoryUpdate = Deserialize::deserialize(res.items)?; Ok(items) } /// Sell items to trader. pub async fn sell_item( &self, trader_id: &str, item_id: &str, quantity: u64, ) -> Result<InventoryUpdate> { if trader_id.is_empty() || item_id.is_empty() || quantity == 0 { return Err(Error::InvalidParameters); } let url = format!("{}/client/game/profile/items/moving", PROD_ENDPOINT); let body = MoveItemRequest { data: &[SellItemRequest { action: "TradingConfirm", trade_type: "sell_to_trader", trader_id, items: &[SellItem { id: item_id.to_string(), count: quantity, scheme_id: 0, }], }], tm: 0, }; let res: TradeResponse = self.post_json(&url, &body).await?; handle_error2(res.error)?; let res: RagfairResponseData = Deserialize::deserialize(res.data)?; if !res.errors.is_empty() { let error = &res.errors[0]; return Err(Error::UnknownAPIError(error.code)); } let items: InventoryUpdate = Deserialize::deserialize(res.items)?; Ok(items) } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/auth.rs
src/auth.rs
use crate::{ handle_error, handle_error2, Error, ErrorResponse, Result, Tarkov, GAME_VERSION, LAUNCHER_ENDPOINT, LAUNCHER_VERSION, PROD_ENDPOINT, }; use flate2::read::ZlibDecoder; use hyper::body::Buf; use hyper::client::connect::dns::GaiResolver; use hyper::client::{Client, HttpConnector}; use hyper::Request; use hyper::StatusCode; use hyper::{Body, Method}; use hyper_tls::HttpsConnector; use log::debug; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use std::io::Read; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct LoginRequest<'a> { email: &'a str, pass: &'a str, hw_code: &'a str, captcha: Option<&'a str>, } #[derive(Debug, Deserialize)] pub(crate) struct Auth { pub aid: String, pub lang: String, pub region: Option<String>, #[serde(rename = "gameVersion")] pub game_version: Option<String>, #[serde(rename = "dataCenters")] pub data_centers: Vec<String>, #[serde(rename = "ipRegion")] pub ip_region: String, pub token_type: String, pub expires_in: u64, pub access_token: String, pub refresh_token: String, } #[derive(Debug, Deserialize)] struct LoginResponse { #[serde(flatten)] error: ErrorResponse, #[serde(default)] data: serde_json::Value, } /// Login error #[derive(Debug, err_derive::Error)] pub enum LoginError { /// Bad login, invalid email or password. #[error(display = "bad login, wrong email or password.")] BadLogin, /// 2FA code is required to continue authentication. #[error(display = "2fa is required")] TwoFactorRequired, /// Captcha response is required to continue authentication. #[error(display = "captcha is required")] CaptchaRequired, /// Incorrect 2FA code. #[error(display = "incorrect 2FA code")] BadTwoFactorCode, /// Rate limited after too many bad login attempts. #[error(display = "too many login attempts")] RateLimited, /// Library contains the wrong major version. #[error(display = "wrong major version")] WrongMajorVersion, } pub(crate) async fn login( client: &Client<HttpsConnector<HttpConnector<GaiResolver>>, Body>, email: &str, password: &str, captcha: Option<&str>, hwid: &str, ) -> Result<Auth> { let url = format!( "{}/launcher/login?launcherVersion={}&branch=live", LAUNCHER_ENDPOINT, LAUNCHER_VERSION ); let password = format!("{:x}", md5::compute(&password)); let body = LoginRequest { email, pass: &password, hw_code: hwid, captcha, }; let res: LoginResponse = post_json(client, &url, &body).await?; handle_error2(res.error)?; Ok(Deserialize::deserialize(res.data)?) } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SecurityLoginRequest<'a> { email: &'a str, hw_code: &'a str, activate_code: &'a str, } #[derive(Debug, Deserialize)] struct SecurityLoginResponse { #[serde(flatten)] error: ErrorResponse, } pub(crate) async fn activate_hardware( client: &Client<HttpsConnector<HttpConnector<GaiResolver>>, Body>, email: &str, code: &str, hwid: &str, ) -> Result<()> { let url = format!( "{}/launcher/hardwareCode/activate?launcherVersion={}", LAUNCHER_ENDPOINT, LAUNCHER_VERSION ); let body = SecurityLoginRequest { email, hw_code: hwid, activate_code: code, }; let res: SecurityLoginResponse = post_json(client, &url, &body).await?; handle_error2(res.error) } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct ExchangeRequest<'a> { version: ExchangeVersion<'a>, hw_code: &'a str, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct ExchangeVersion<'a> { major: &'a str, game: &'a str, backend: &'a str, } #[derive(Debug, Deserialize)] struct ExchangeResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Session>, } /// Authenticated user session. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Session { queued: bool, /// Session cookie. pub session: String, } pub(crate) async fn exchange_access_token( client: &Client<HttpsConnector<HttpConnector<GaiResolver>>, Body>, access_token: &str, hwid: &str, ) -> Result<Session> { let url = format!( "{}/launcher/game/start?launcherVersion={}&branch=live", PROD_ENDPOINT, LAUNCHER_VERSION ); let body = ExchangeRequest { version: ExchangeVersion { major: GAME_VERSION, game: "live", backend: "6", }, hw_code: hwid, }; debug!("Sending request to {} ({:?})", url, body); let req = Request::builder() .uri(url) .method(Method::POST) .header("Content-Type", "application/json") .header("User-Agent", format!("BSG Launcher {}", LAUNCHER_VERSION)) .header("Authorization", access_token) .body(Body::from(serde_json::to_string(&body)?))?; let res = client.request(req).await?; match res.status() { StatusCode::OK => { let body = hyper::body::to_bytes(res.into_body()).await?; let mut decode = ZlibDecoder::new(body.bytes()); let mut body = String::new(); decode.read_to_string(&mut body)?; debug!("Response: {}", body); let res = serde_json::from_slice::<ExchangeResponse>(body.as_bytes())?; handle_error(res.error, res.data) } _ => Err(Error::Status(res.status())), } } async fn post_json<S: serde::Serialize + ?Sized + std::fmt::Debug, T: DeserializeOwned>( client: &Client<HttpsConnector<HttpConnector<GaiResolver>>, Body>, url: &str, body: &S, ) -> Result<T> { debug!("Sending request to {} ({:?})", url, body); let req = Request::builder() .uri(url) .method(Method::POST) .header("Content-Type", "application/json") .header("User-Agent", format!("BSG Launcher {}", LAUNCHER_VERSION)) .body(Body::from(serde_json::to_string(&body)?))?; let res = client.request(req).await?; match res.status() { StatusCode::OK => { let body = hyper::body::to_bytes(res.into_body()).await?; let mut decode = ZlibDecoder::new(body.bytes()); let mut body = String::new(); decode.read_to_string(&mut body)?; debug!("Response: {}", body); Ok(serde_json::from_slice::<T>(body.as_bytes())?) } _ => Err(Error::Status(res.status())), } } impl Tarkov { /// Keep the current session alive. Session expires after 30 seconds of idling. pub async fn keep_alive(&self) -> Result<()> { let url = format!("{}/client/game/keepalive", PROD_ENDPOINT); let res: ErrorResponse = self.post_json(&url, &{}).await?; match res.code { 0 => Ok(()), _ => Err(Error::UnknownAPIError(res.code)), } } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/constant.rs
src/constant.rs
use crate::{handle_error, Error, ErrorResponse, Result, Tarkov, PROD_ENDPOINT}; use crate::bad_json::{deserialize_integer_to_option_string, StringOrInt}; use crate::profile::Side; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct Request { crc: u64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct ItemsResponse { #[serde(flatten)] error: ErrorResponse, data: Option<HashMap<String, Item>>, } /// Localization item #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Item { /// Item ID #[serde(rename = "_id")] pub id: String, /// Item name #[serde(rename = "_name")] pub name: String, /// Item parent ID #[serde(rename = "_parent")] pub parent: String, /// Item type #[serde(rename = "_type")] pub item_type: String, /// Item properties #[serde(rename = "_props")] pub props: Props, /// ? #[serde(rename = "_proto")] pub proto: Option<String>, } /// All item properties. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Props { /// Full item name pub name: Option<String>, /// Short item name pub short_name: Option<String>, /// Item description pub description: Option<String>, /// Item weight pub weight: Option<f64>, /// Item background color pub background_color: Option<String>, /// Item width pub width: Option<u64>, /// Item height pub height: Option<u64>, /// Item maximum stack size pub stack_max_size: Option<u64>, /// Item rarity pub rarity: Option<String>, /// Item spawn chance pub spawn_chance: Option<f64>, /// Item price? pub credits_price: Option<u64>, /// Item sound pub item_sound: Option<String>, /// Item prefab pub prefab: Option<Prefab>, /// Item prefab? pub use_prefab: Option<Prefab>, /// Item stack count pub stack_objects_count: Option<u64>, /// ? pub not_shown_in_slot: Option<bool>, /// Item is examined by default. pub examined_by_default: Option<bool>, /// Time it takes to examine an item in seconds. pub examine_time: Option<u64>, /// Item cannot be deleted. pub is_undiscardable: Option<bool>, /// Item cannot be sold. pub is_unsaleable: Option<bool>, /// Item cannot be bought. pub is_unbuyable: Option<bool>, /// Item cannot be given?. pub is_ungivable: Option<bool>, /// Item locked after equipping?. #[serde(rename = "IsLockedafterEquip")] pub is_locked_after_equip: Option<bool>, /// Item is needed for quests. pub quest_item: Option<bool>, /// Experience for looting item. pub loot_experience: Option<u64>, /// Experience for examining item. pub examine_experience: Option<u64>, /// ? pub hide_entrails: Option<bool>, /// Item repair cost pub repair_cost: Option<u64>, /// Item repair speed pub repair_speed: Option<u64>, /// ? pub extra_size_left: Option<u64>, /// ? pub extra_size_right: Option<u64>, /// ? pub extra_size_up: Option<u64>, /// ? pub extra_size_down: Option<u64>, /// ? pub extra_size_force_add: Option<bool>, /// ? pub merges_with_children: Option<bool>, /// Item can be sold on the flea market. pub can_sell_on_ragfair: Option<bool>, /// Item can be traded on the flea market. pub can_require_on_ragfair: Option<bool>, /// Item banned from the flea market. pub banned_from_ragfair: Option<bool>, /// ? pub conflicting_items: Option<Vec<String>>, /// Item fixed price pub fixed_price: Option<bool>, /// Item cannot be looted. pub unlootable: Option<bool>, /// Item cannot be looted from slot. pub unlootable_from_slot: Option<String>, /// Item cannot be looted from side. pub unlootable_from_side: Option<Vec<Side>>, /// ? #[serde(rename = "ChangePriceCoef")] pub change_price_coefficient: Option<u64>, /// Item spawns locations pub allow_spawn_on_locations: Option<Vec<String>>, /// ? pub send_to_client: Option<bool>, /// ? pub animation_variants_number: Option<u64>, /// ? pub discarding_block: Option<bool>, /// ? pub max_resource: Option<u64>, /// ? pub resource: Option<u64>, /// ? pub dog_tag_qualities: Option<bool>, /// Item grids pub grids: Option<Vec<Grid>>, /// Item slots pub slots: Option<Vec<Slot>>, /// Items can be equipped during a raid. pub can_put_into_during_the_raid: Option<bool>, /// Item cannot be removed from slots during a raid. pub cant_remove_from_slots_during_raid: Option<Vec<String>>, /// Item key IDs pub key_ids: Option<Vec<String>>, /// Item tag color pub tag_color: Option<u64>, /// Item tag name pub tag_name: Option<String>, /// Item durability pub durability: Option<u64>, /// Weapon accuracy pub accuracy: Option<i64>, /// Weapon recoil pub recoil: Option<f64>, /// Weapon loudness pub loudness: Option<i64>, /// Weapon effective distance pub effective_distance: Option<u64>, /// Item ergonomics? pub ergonomics: Option<f64>, /// Item velocity pub velocity: Option<f64>, /// ? pub raid_moddable: Option<bool>, /// ? pub tool_moddable: Option<bool>, /// ? pub blocks_folding: Option<bool>, /// ? pub blocks_collapsible: Option<bool>, /// ? pub is_animated: Option<bool>, /// Weapon has a buttstock. pub has_shoulder_contact: Option<bool>, /// Weapon sighting range pub sighting_range: Option<u64>, /// Weapon firing modes pub modes_count: Option<u64>, /// Weapon muzzle mod type #[serde(rename = "muzzleModType")] pub muzzle_mod_type: Option<String>, /// Weapon sight mod type #[serde(rename = "sightModType")] pub sight_mod_type: Option<String>, /// Weapon has a telescopic sight equipped. #[serde(rename = "variableZoom")] pub variable_zoom: Option<bool>, /// Weapon telescopic sight magnification levels. #[serde(rename = "varZoomCount")] pub var_zoom_count: Option<u64>, /// Weapon telescopic sight magnification? #[serde(rename = "varZoomAdd")] pub var_zoom_add: Option<u64>, /// Weapon aiming sensitivity #[serde(rename = "aimingSensitivity")] pub aiming_sensitivity: Option<f64>, /// Weapon sight mode count pub sight_modes_count: Option<u64>, /// Weapon sight calibration distances pub optic_calibration_distances: Option<Vec<u64>>, /// ? pub intensity: Option<f64>, /// ? pub mask: Option<String>, /// ? pub mask_size: Option<f64>, /// Item noise intensity pub noise_intensity: Option<f64>, /// Item noise scale pub noise_scale: Option<u64>, /// Item color pub color: Option<Color>, /// ? pub diffuse_intensity: Option<f64>, /// ? pub has_hinge: Option<bool>, /// ? pub ramp_palette: Option<String>, /// ? pub depth_fade: Option<f64>, /// ? #[serde(rename = "RoughnessCoef")] pub roughness_coefficient: Option<f64>, /// ? #[serde(rename = "SpecularCoef")] pub specular_coefficient: Option<f64>, /// ? #[serde(rename = "MainTexColorCoef")] pub main_tex_color_coefficient: Option<f64>, /// ? pub minimum_temperature_value: Option<f64>, /// ? pub ramp_shift: Option<f64>, /// ? pub heat_min: Option<f64>, /// ? pub cold_max: Option<f64>, /// ? pub is_noisy: Option<bool>, /// ? pub is_fps_stuck: Option<bool>, /// ? pub is_glitch: Option<bool>, /// ? pub is_motion_blurred: Option<bool>, /// ? pub is_pixelated: Option<bool>, /// ? pub pixelation_block_count: Option<u64>, /// ? #[serde(rename = "magAnimationIndex")] pub mag_animation_index: Option<u64>, /// Weapon cartridge/ammo pub cartridges: Option<Vec<Cartridge>>, /// ? pub can_fast: Option<bool>, /// ? pub can_hit: Option<bool>, /// ? pub can_admin: Option<bool>, /// ? pub load_unload_modifier: Option<i64>, /// ? pub check_time_modifier: Option<i64>, /// ? pub check_override: Option<u64>, /// ? pub reload_mag_type: Option<String>, /// ? pub visible_ammo_ranges_string: Option<String>, /// Weapon has a buttstock. pub is_shoulder_contact: Option<bool>, /// Weapon stock is foldable. pub foldable: Option<bool>, /// Weapon stock is retractable? pub retractable: Option<bool>, /// ? pub size_reduce_right: Option<u64>, /// ? pub center_of_impact: Option<f64>, /// Shotgun shot dispersion pub shotgun_dispersion: Option<f64>, /// Weapon has a suppressor. pub is_silencer: Option<bool>, /// Item search sound pub search_sound: Option<String>, /// ? pub blocks_armor_vest: Option<bool>, /// ? #[serde(rename = "speedPenaltyPercent")] pub speed_penalty_percent: Option<i64>, /// ? pub grid_layout_name: Option<String>, /// ? pub spawn_filter: Option<Vec<String>>, /// Unknown type #[serde(rename = "containType")] pub contain_type: Option<serde_json::Value>, /// Item width in inventory. #[serde(rename = "sizeWidth")] pub size_width: Option<u64>, /// Item height in inventory. #[serde(rename = "sizeHeight")] pub size_height: Option<u64>, /// ? #[serde(rename = "isSecured")] pub is_secured: Option<bool>, /// ? #[serde(rename = "spawnTypes")] pub spawn_types: Option<String>, /// Unknown type #[serde(rename = "lootFilter")] pub loot_filter: Option<serde_json::Value>, /// Item spawn rarity #[serde(rename = "spawnRarity")] pub spawn_rarity: Option<String>, /// ? #[serde(rename = "minCountSpawn")] pub min_count_spawn: Option<u64>, /// ? #[serde(rename = "maxCountSpawn")] pub max_count_spawn: Option<u64>, /// Unknown type #[serde(rename = "openedByKeyID")] pub opened_by_key_id: Option<serde_json::Value>, /// Item rig layout name pub rig_layout_name: Option<String>, /// Item maximum durability pub max_durability: Option<u64>, /// Item armor zone #[serde(rename = "armorZone")] pub armor_zone: Option<Vec<ArmorZone>>, /// Item armor class #[serde( default, rename = "armorClass", deserialize_with = "deserialize_integer_to_option_string" )] pub armor_class: Option<String>, /// ? #[serde(rename = "mousePenalty")] pub mouse_penalty: Option<i64>, /// ? #[serde(rename = "weaponErgonomicPenalty")] pub weapon_ergonomic_penalty: Option<i64>, /// ? pub blunt_throughput: Option<f64>, /// Item armor material pub armor_material: Option<String>, /// Weapon class #[serde(rename = "weapClass")] pub weapon_class: Option<String>, /// Weapon type #[serde(rename = "weapUseType")] pub weapon_use_type: Option<String>, /// Weapon ammo caliber pub ammo_caliber: Option<String>, /// ? pub operating_resource: Option<u64>, /// ? pub repair_complexity: Option<u64>, /// Item spawn minimum durability chance #[serde(rename = "durabSpawnMin")] pub durability_spawn_min: Option<u64>, /// Item spawn maximum durability chance #[serde(rename = "durabSpawnMax")] pub durability_spawn_max: Option<u64>, /// Weapon fast reload #[serde(rename = "isFastReload")] pub is_fast_reload: Option<bool>, /// Weapon recoil vertical force pub recoil_force_up: Option<u64>, /// Weapon recoil back force pub recoil_force_back: Option<u64>, /// ? pub convergence: Option<f64>, /// Weapon recoil angle pub recoil_angle: Option<u64>, /// Weapon fire modes #[serde(rename = "weapFireType")] pub weapon_fire_type: Option<Vec<FireMode>>, /// Weapon recoil dispersion rate #[serde(rename = "RecolDispersion")] pub recoil_dispersion: Option<u64>, /// Weapon fire mode #[serde(rename = "bFirerate")] pub firerate: Option<u64>, /// Weapon effective distance? #[serde(rename = "bEffDist")] pub eff_dist: Option<u64>, /// Weapon maximum sound distance #[serde(rename = "bHearDist")] pub hear_dist: Option<u64>, /// Weapon has a round in the chamber. #[serde(rename = "isChamberLoad")] pub is_chamber_load: Option<bool>, /// ? #[serde(rename = "chamberAmmoCount")] pub chamber_ammo_count: Option<u64>, /// Weapon bolt catch is engaged. #[serde(rename = "isBoltCatch")] pub is_bolt_catch: Option<bool>, /// Weapon magazine type?. #[serde(rename = "defMagType")] pub def_mag_type: Option<String>, /// Weapon ammo type?. #[serde(rename = "defAmmo")] pub def_ammo: Option<String>, /// Weapon chamber?. pub chambers: Option<Vec<Chamber>>, /// ? pub camera_recoil: Option<f64>, /// ? pub camera_snap: Option<f64>, /// Weapon reload mode pub reload_mode: Option<String>, /// ? pub aim_plane: Option<f64>, /// ? pub deviation_curve: Option<u64>, /// ? pub deviation_max: Option<u64>, /// ? #[serde(rename = "TacticalReloadStiffnes")] pub tactical_reload_stiffness: Option<Coordinate>, /// ? pub tactical_reload_fixation: Option<f64>, /// ? pub recoil_center: Option<Coordinate>, /// ? pub rotation_center: Option<Coordinate>, /// ? pub rotation_center_no_stock: Option<Coordinate>, /// ? pub folded_slot: Option<String>, /// ? pub compact_handling: Option<bool>, /// Item minimum repair degradation pub min_repair_degradation: Option<u64>, /// Item maximum repair degradation pub max_repair_degradation: Option<f64>, /// Weapon iron sight zero pub iron_sight_range: Option<u64>, /// Weapon's bolt catch must be engaged for external reload (pressing R). #[serde(rename = "MustBoltBeOpennedForExternalReload")] pub must_bolt_be_opened_for_external_reload: Option<bool>, /// Weapon's bolt catch must be engaged for internal reload (reload inside inventory). #[serde(rename = "MustBoltBeOpennedForInternalReload")] pub must_bolt_be_opened_for_internal_reload: Option<bool>, /// Weapon is bolt action operated. pub bolt_action: Option<bool>, /// ? pub hip_accuracy_restoration_delay: Option<f64>, /// ? pub hip_accuracy_restoration_speed: Option<u64>, /// ? #[serde(rename = "HipInnaccuracyGain")] pub hip_inaccuracy_gain: Option<f64>, /// ? pub manual_bolt_catch: Option<bool>, /// Item blocks earpiece. pub blocks_earpiece: Option<bool>, /// Item blocks eye wear. #[serde(rename = "BlocksEyewear")] pub blocks_eye_wear: Option<bool>, /// Item blocks head wear. #[serde(rename = "BlocksHeadwear")] pub blocks_head_wear: Option<bool>, /// Item blocks face cover. pub blocks_face_cover: Option<bool>, /// Time it takes to consume food. #[serde(rename = "foodUseTime")] pub food_use_time: Option<u64>, /// Food effect type. #[serde(rename = "foodEffectType")] pub food_effect_type: Option<String>, /// ? pub stimulator_buffs: Option<String>, /// Health effects on player #[serde(rename = "effects_health")] pub effects_health: Option<HealthEffects>, /// Damage effects on player #[serde(rename = "effects_damage")] pub effects_damage: Option<DamageEffects>, /// Speed effects on player #[serde(rename = "effects_speed")] pub effects_speed: Option<SpeedEffects>, /// Maximum item usage pub maximum_number_of_usage: Option<u64>, /// Knife hit delay #[serde(rename = "knifeHitDelay")] pub knife_hit_delay: Option<u64>, /// Knife slash rate #[serde(rename = "knifeHitSlashRate")] pub knife_hit_slash_rate: Option<u64>, /// Knife stab rate #[serde(rename = "knifeHitStabRate")] pub knife_hit_stab_rate: Option<u64>, /// Knife effective hit radius #[serde(rename = "knifeHitRadius")] pub knife_hit_radius: Option<f64>, /// Knife slash damage #[serde(rename = "knifeHitSlashDam")] pub knife_hit_slash_damage: Option<u64>, /// Knife stab damage #[serde(rename = "knifeHitStabDam")] pub knife_hit_stab_damage: Option<u64>, /// Knife durability #[serde(rename = "knifeDurab")] pub knife_durability: Option<u64>, /// ? pub primary_distance: Option<f64>, /// ? #[serde(rename = "SecondryDistance")] pub secondary_distance: Option<f64>, /// ? pub slash_penetration: Option<u64>, /// ? pub stab_penetration: Option<u64>, /// ? pub primary_consumption: Option<u64>, /// ? #[serde(rename = "SecondryConsumption")] pub secondary_consumption: Option<u64>, /// ? pub deflection_consumption: Option<u64>, /// ? pub config_path_str: Option<String>, /// ? pub max_markers_count: Option<u64>, /// ? #[serde(rename = "scaleMin")] pub scale_min: Option<f64>, /// ? #[serde(rename = "scaleMax")] pub scale_max: Option<f64>, /// Time it takes to consume medkit. #[serde(rename = "medUseTime")] pub med_use_time: Option<u64>, /// Medkit effect type #[serde(rename = "medEffectType")] pub med_effect_type: Option<String>, /// ? pub max_hp_resource: Option<u64>, /// ? #[serde(rename = "hpResourceRate")] pub hp_resource_rate: Option<u64>, /// ? pub max_efficiency: Option<u64>, /// ? pub addiction: Option<u64>, /// ? pub overdose: Option<u64>, /// ? pub overdose_recovery: Option<u64>, /// ? pub addiction_recovery: Option<u64>, /// Unknown type pub buffs: Option<serde_json::Value>, /// ? #[serde(rename = "apResource")] pub ap_resource: Option<u64>, /// ? #[serde(rename = "krResource")] pub kr_resource: Option<u64>, /// ? pub stack_min_random: Option<u64>, /// ? pub stack_max_random: Option<u64>, /// Ammo type #[serde(rename = "ammoType")] pub ammo_type: Option<String>, /// Ammo damage pub damage: Option<u64>, /// Ammo accuracy #[serde(rename = "ammoAccr")] pub ammo_accr: Option<i64>, /// Ammo recoil #[serde(rename = "ammoRec")] pub ammo_rec: Option<i64>, /// Ammo effective distance #[serde(rename = "ammoDist")] pub ammo_dist: Option<u64>, /// Buckshot bullet count? #[serde(rename = "buckshotBullets")] pub buckshot_bullets: Option<u64>, /// Ammo penetration power pub penetration_power: Option<u64>, /// Ammo ? #[serde(rename = "penetration_power_diviation")] pub penetration_power_deviation: Option<f64>, /// Ammo ? #[serde(rename = "ammoHear")] pub ammo_hear: Option<i64>, /// Ammo sound effect #[serde(rename = "ammoSfx")] pub ammo_sfx: Option<String>, /// Item chance of misfire pub misfire_chance: Option<f64>, /// ? pub min_fragments_count: Option<u64>, /// ? pub max_fragments_count: Option<u64>, /// ? #[serde(rename = "ammoShiftChance")] pub ammo_shift_chance: Option<u64>, /// Ammo casing name #[serde(rename = "casingName")] pub casing_name: Option<String>, /// Ammo casing ejection power #[serde(rename = "casingEjectPower")] pub casing_eject_power: Option<u64>, /// Ammo casing mass #[serde(rename = "casingMass")] pub casing_mass: Option<f64>, /// Ammo casing sound #[serde(rename = "casingSounds")] pub casing_sounds: Option<String>, /// Ammo projectile count pub projectile_count: Option<u64>, /// Ammo initial speed pub initial_speed: Option<u64>, /// Ammo penetration chance pub penetration_chance: Option<f64>, /// Ammo ricochet chance pub ricochet_chance: Option<f64>, /// Ammo fragmentation chance pub fragmentation_chance: Option<f64>, /// Ammo ballistic coefficient #[serde(rename = "BallisticCoeficient")] pub ballistic_coefficient: Option<f64>, /// ? pub deterioration: Option<u64>, /// ? pub speed_retardation: Option<f64>, /// Ammo is a tracer round pub tracer: Option<bool>, /// Tracer color pub tracer_color: Option<String>, /// Tracer distance pub tracer_distance: Option<f64>, /// Ammo armor damage pub armor_damage: Option<u64>, /// Ammo caliber pub caliber: Option<String>, /// ? pub stamina_burn_per_damage: Option<f64>, /// ? pub show_bullet: Option<bool>, /// ? pub has_grenader_component: Option<bool>, /// ? pub fuze_arm_time_sec: Option<f64>, /// Item explosion strength pub explosion_strength: Option<u64>, /// Item minimum explosion distance pub min_explosion_distance: Option<f64>, /// Item maximum explosion distance pub max_explosion_distance: Option<f64>, /// Explosion fragment count pub fragments_count: Option<u64>, /// Explosion fragment type pub fragment_type: Option<String>, /// ? pub show_hit_effect_on_explode: Option<bool>, /// Explosion type pub explosion_type: Option<String>, /// ? pub ammo_life_time_sec: Option<u64>, /// ? pub stack_slots: Option<Vec<StackSlot>>, /// Item type #[serde(rename = "type")] pub item_type: Option<String>, /// ? #[serde(rename = "eqMin")] pub eq_min: Option<u64>, /// ? #[serde(rename = "eqMax")] pub eq_max: Option<u64>, /// ? #[serde(rename = "rate")] pub rate: Option<u64>, /// ? pub throw_type: Option<String>, /// ? pub strength: Option<u64>, /// ? pub contusion_distance: Option<u64>, /// ? #[serde(rename = "throwDamMax")] pub throw_dam_max: Option<u64>, /// ? pub expl_delay: Option<f64>, /// ? pub blindness: Option<Coordinate>, /// ? pub contusion: Option<Coordinate>, /// ? pub emit_time: Option<u64>, /// ? pub can_be_hidden_during_throw: Option<bool>, /// ? pub indestructibility: Option<f64>, /// ? #[serde(rename = "headSegments")] pub head_segments: Option<Vec<HeadSegment>>, /// ? pub face_shield_component: Option<bool>, /// ? pub face_shield_mask: Option<String>, /// ? pub material_type: Option<String>, /// ? pub ricochet_params: Option<Coordinate>, /// ? pub deaf_strength: Option<String>, /// ? pub distortion: Option<f64>, /// ? #[serde(rename = "CompressorTreshold")] pub compressor_threshold: Option<i64>, /// ? pub compressor_attack: Option<u64>, /// ? pub compressor_release: Option<u64>, /// ? pub compressor_gain: Option<u64>, /// ? pub cutoff_freq: Option<u64>, /// ? pub resonance: Option<f64>, /// ? pub compressor_volume: Option<i64>, /// Item ambient volume pub ambient_volume: Option<i64>, /// Item dry volume pub dry_volume: Option<i64>, } /// Item prefab #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Prefab { /// Prefab path pub path: String, /// ? pub rcid: String, } /// Item grid #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Grid { /// Grid ID #[serde(rename = "_id")] pub id: String, /// Grid name #[serde(rename = "_name")] pub name: String, /// Grid parent ID #[serde(rename = "_parent")] pub parent: String, /// Grid properties #[serde(rename = "_props")] pub props: GridProps, /// ? #[serde(rename = "_proto")] pub proto: String, } /// Item grid properties #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct GridProps { /// Grid filters pub filters: Vec<GridFilter>, /// Grid height pub cells_h: u64, /// Grid width? #[serde(rename = "cellsV")] pub cells_w: u64, /// Minimum grid space pub min_count: u64, /// Maximum grid space pub max_count: u64, /// Grid maximum weight pub max_weight: u64, } /// Item grid filter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct GridFilter { /// Grid filters pub filter: Vec<String>, /// Grid exclusion filter pub excluded_filter: Vec<String>, } /// Item slot #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Slot { /// Slot ID #[serde(rename = "_id")] pub id: String, /// Slot name #[serde(rename = "_name")] pub name: String, /// Slot parent ID #[serde(rename = "_parent")] pub parent: String, /// Slot properties #[serde(rename = "_props")] pub props: SlotProps, /// Slot is required #[serde(rename = "_required")] pub required: bool, /// Merge slot with children #[serde(rename = "_mergeSlotWithChildren")] pub merge_slot_with_children: bool, /// ? #[serde(rename = "_proto")] pub proto: String, } /// Item slot properties #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SlotProps { /// ? pub slot: Option<i64>, /// Slot animation pub animation_index: Option<i64>, /// Slot filters pub filters: Option<Vec<SlotFilter>>, } /// Item slot filter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SlotFilter { /// ? pub slot: Option<i64>, /// Slot filter animation index pub animation_index: Option<i64>, /// Slot filter filters pub filters: Vec<String>, } /// Item cartridge/ammo #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Cartridge { /// Cartridge ID #[serde(rename = "_id")] pub id: String, /// Cartridge name #[serde(rename = "_name")] pub name: String, /// Cartridge parent ID #[serde(rename = "_parent")] pub parent: String, /// Maximum number of cartridges #[serde(rename = "_max_count")] pub max_count: u64, /// Cartridge properties #[serde(rename = "_props")] pub props: CartridgeProps, /// ? #[serde(rename = "_proto")] pub proto: String, } /// Cartridge properties #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct CartridgeProps { /// Cartridge filters pub filters: Vec<CartridgeFilter>, } /// Cartridge filter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct CartridgeFilter { /// Cartridge filter filters? pub filter: Vec<String>, } /// Item armor zone #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub enum ArmorZone { /// Head Head, /// Chest Chest, /// Stomach Stomach, /// Left arm LeftArm, /// Right arm RightArm, /// Left leg LeftLeg, /// Right leg RightLeg, } /// Item fire mode #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "lowercase")] pub enum FireMode { /// Single fire Single, /// Burst mode Burst, /// Full auto FullAuto, } /// Item chamber #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Chamber { /// Chamber ID #[serde(rename = "_id")] pub id: String, /// Chamber name #[serde(rename = "_name")] pub name: String, /// Chamber parent ID #[serde(rename = "_parent")] pub parent: String, /// Chamber properties #[serde(rename = "_props")] pub props: ChamberProps, /// Chamber is required #[serde(rename = "_required")] pub required: bool, /// Merge chamber slot with children #[serde(rename = "_mergeSlotWithChildren")] pub merge_slot_with_children: bool, /// ? #[serde(rename = "_proto")] pub proto: String, } /// Chamber properties #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct ChamberProps { /// Chamber filters pub filters: Vec<ChamberFilter>, } /// Chamber filter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct ChamberFilter { /// Chamber filter filters? pub filter: Vec<String>, } /// RGB color #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Color { /// Red pub r: u8, /// Green pub g: u8, /// Blue pub b: u8, /// Alpha pub a: u8, } /// 3D Coordinate #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Coordinate { /// x plane pub x: f64, /// y plane pub y: f64, /// z plane pub z: f64, } /// Head parts #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub enum HeadSegment { /// Top of head Top, /// Nape Nape, /// Ears Ears, /// Eyes Eyes, /// Jaws Jaws, } /// Health effects on player #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct HealthEffects { /// Body effects pub common: Health, /// Head effects pub head: Health, /// Left arm effects pub arm_left: Health, /// Right arm effects pub arm_right: Health, /// Chest effects pub chest: Health, /// Stomach effects pub tummy: Health, /// Left leg effects pub leg_left: Health, /// Right leg effects pub leg_right: Health, /// Energy effects pub energy: Health, /// Hydration effects pub hydration: Health, } /// Health effect #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Health { /// Effect value pub value: i64, /// Effect percent pub percent: bool, /// ? pub time: u64, /// Effect duration pub duration: u64, } /// Damage effects on player #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DamageEffects { /// Bloodloss effect pub bloodloss: Damage, /// Fracture effect pub fracture: Damage, /// Pain effect pub pain: Damage, /// Contusion effect pub contusion: Damage, /// Toxication effect pub toxication: Damage, /// Radiation exposure #[serde(rename = "radExposure")] pub radiation_exposure: Damage, } /// Damage effect #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Damage { /// ? pub remove: bool, /// ? pub time: u64, /// Damage effect duration pub duration: u64, /// ? pub fade_out: Option<u64>, /// ? pub cost: Option<u64>, /// Damage minimum health penalty pub health_penalty_min: Option<u64>, /// Damage maximum health penalty pub health_penalty_max: Option<u64>, } /// Speed effects on player #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SpeedEffects { /// Mobility effect pub mobility: Speed, /// Recoil effect pub recoil: Speed, /// Reload effect pub reload_speed: Speed, /// Loot effect pub loot_speed: Speed, /// Unlock effect pub unlock_speed: Speed, } /// Speed effect #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Speed { /// Effect value pub value: i64, /// Effect percent pub percent: bool, /// ? pub time: u64, /// Effect duration pub duration: u64, } /// ? #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct StackSlot { /// Stack slot ID #[serde(rename = "_id")] pub id: String, /// Stack slot name #[serde(rename = "_name")] pub name: String, /// Stack slot parent ID #[serde(rename = "_parent")] pub parent: String, /// Maximum stack slots #[serde(rename = "_max_count")] pub max_count: u64, /// Stack slot properties #[serde(rename = "_props")] pub props: StackSlotProps, /// ? #[serde(rename = "_proto")] pub proto: String, } /// Stack slot properties #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct StackSlotProps { /// Stack slot filters pub filters: Vec<StackSlotFilter>, } /// Stack slot filter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct StackSlotFilter { /// Stack slot filter filters? pub filter: Vec<String>, } #[derive(Debug, Deserialize)] struct LocationsResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Locations>, } /// All in-game locations #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Locations {
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
true
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/ragfair.rs
src/ragfair.rs
use crate::{ handle_error, handle_error2, Error, ErrorResponse, Result, Tarkov, PROD_ENDPOINT, RAGFAIR_ENDPOINT, }; use crate::inventory::{BarterItem, InventoryUpdate, Item, MoveItemRequest, RagfairResponseData}; use crate::market_filter::{Currency, MarketFilter, Owner, SortBy, SortDirection}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; /// Ragfair error #[derive(Debug, err_derive::Error)] pub enum RagfairError { /// Offer is not available yet. #[error(display = "offer not available yet")] OfferNotAvailableYet, /// Offer not found, sold out or out of stock. #[error(display = "offer not found, sold out or out of stock")] OfferNotFound, /// Provided `BarterItem` is invalid, not enough quantities available or not found. #[error(display = "barter items provided cannot be found")] InvalidBarterItems, /// Maximum outstanding offer count of 3 was reached. #[error(display = "maximum offer count of 3 was reached")] MaxOfferCount, /// Insufficient funds to pay the flea market fee. #[error(display = "insufficient funds to pay market fee")] InsufficientTaxFunds, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SearchRequest<'a> { page: u64, limit: u64, sort_type: SortBy, sort_direction: SortDirection, currency: Currency, price_from: u64, price_to: u64, quantity_from: u64, quantity_to: u64, condition_from: u64, condition_to: u64, one_hour_expiration: bool, remove_bartering: bool, offer_owner_type: Owner, only_functional: bool, update_offer_count: bool, handbook_id: &'a str, linked_search_id: &'a str, needed_search_id: &'a str, //build_items: {} //build_count: u64, tm: u64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct SearchResponse { #[serde(flatten)] error: ErrorResponse, data: Option<SearchResult>, } /// Market search result #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct SearchResult { /// Market categories pub categories: HashMap<String, u64>, /// Available offers pub offers: Vec<Offer>, /// Number of items for sale pub offers_count: u64, /// Selected category ID pub selected_category: String, } /// Market offer #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Offer { /// Offer ID #[serde(rename = "_id")] pub id: String, /// ? pub int_id: u64, /// Merchant profile pub user: User, /// ? pub root: String, /// Items for sale pub items: Vec<Item>, /// Items cost pub items_cost: u64, /// Items wanted in return pub requirements: Vec<Requirement>, /// Requirement items cost pub requirements_cost: u64, /// Summary cost pub summary_cost: u64, /// ? pub sell_in_one_piece: bool, /// Time when item was listed on the market. /// /// Add 60 seconds for the true start time, when the item will be available for purchase. pub start_time: u64, /// Offer expiry time pub end_time: u64, /// Merchant loyalty level pub loyalty_level: u64, } /// Merchant profile #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct User { /// Merchant ID pub id: String, /// Merchant member type pub member_type: u64, /// Merchant nickname pub nickname: Option<String>, /// Merchant rating pub rating: Option<f64>, /// Merchant rating is growing pub is_rating_growing: Option<bool>, /// Merchant avatar pub avatar: Option<String>, } /// Offer requirement #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Requirement { /// Item localization schema ID #[serde(rename = "_tpl")] pub schema_id: String, /// Item count pub count: f64, } #[derive(Debug, Serialize)] struct BuyItemRequest<'a> { #[serde(rename = "Action")] action: &'a str, offers: &'a [BuyOffer<'a>], } #[derive(Debug, Serialize)] struct BuyOffer<'a> { id: &'a str, count: u64, items: &'a [BarterItem], } #[derive(Debug, Serialize)] struct BuyItem { item: String, count: f64, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct BuyItemResponse { #[serde(flatten)] error: ErrorResponse, data: serde_json::Value, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct GetPriceRequest<'a> { template_id: &'a str, } #[derive(Debug, Deserialize)] struct GetPriceResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Price>, } /// Ragfair item price #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Price { /// Item localization schema ID #[serde(rename = "templateId")] pub schema_id: String, /// Minimum item price pub min: f64, /// Maximum item price pub max: f64, /// Average item price pub avg: f64, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SellItemRequest<'a> { #[serde(rename = "Action")] action: &'a str, sell_in_one_piece: bool, items: &'a [&'a str], requirements: &'a [SellRequirement], } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct SellRequirement { #[serde(flatten)] requirement: Requirement, level: u64, side: u8, only_functional: bool, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] struct SellItemResponse { #[serde(flatten)] error: ErrorResponse, data: serde_json::Value, } impl Tarkov { /// Search the flea market. pub async fn search_market<'a>( &self, page: u64, limit: u64, filter: MarketFilter<'_>, ) -> Result<SearchResult> { if limit == 0 { return Err(Error::InvalidParameters); } let body = SearchRequest { page, limit, sort_type: filter.sort_type, sort_direction: filter.sort_direction, currency: filter.currency, price_from: filter.min_price.unwrap_or(0), price_to: filter.max_price.unwrap_or(0), quantity_from: filter.min_quantity.unwrap_or(0), quantity_to: filter.max_quantity.unwrap_or(0), condition_from: filter.min_condition.unwrap_or(0), condition_to: filter.max_condition.unwrap_or(0), one_hour_expiration: filter.expiring_within_hour, remove_bartering: filter.hide_bartering_offers, offer_owner_type: filter.owner_type, only_functional: filter.hide_inoperable_weapons, update_offer_count: true, handbook_id: &filter.handbook_id.unwrap_or(""), linked_search_id: &filter.linked_search_id.unwrap_or(""), needed_search_id: &filter.required_search_id.unwrap_or(""), tm: 1, }; let url = format!("{}/client/ragfair/find", RAGFAIR_ENDPOINT); let res: SearchResponse = self.post_json(&url, &body).await?; handle_error(res.error, res.data) } /// Get the item price data from the flea market. pub async fn get_item_price(&self, schema_id: &str) -> Result<Price> { if schema_id.is_empty() { return Err(Error::InvalidParameters); } let url = format!("{}/client/ragfair/itemMarketPrice", RAGFAIR_ENDPOINT); let body = GetPriceRequest { template_id: schema_id, }; let res: GetPriceResponse = self.post_json(&url, &body).await?; handle_error(res.error, res.data) } /// Buy items from the flea market. pub async fn buy_item( &self, offer_id: &str, quantity: u64, barter_items: &[BarterItem], ) -> Result<InventoryUpdate> { if offer_id.is_empty() || quantity == 0 || barter_items.is_empty() { return Err(Error::InvalidParameters); } let url = format!("{}/client/game/profile/items/moving", PROD_ENDPOINT); let body = &MoveItemRequest { data: &[BuyItemRequest { action: "RagFairBuyOffer", offers: &[BuyOffer { id: offer_id, count: quantity, items: barter_items, }], }], tm: 2, }; let res: BuyItemResponse = self.post_json(&url, body).await?; handle_error2(res.error)?; let res: RagfairResponseData = Deserialize::deserialize(res.data)?; if !res.errors.is_empty() { let error = &res.errors[0]; match error.code { 1503 | 1506 | 1507 => return Err(RagfairError::OfferNotFound)?, _ => return Err(Error::UnknownAPIError(error.code)), } } let items: InventoryUpdate = Deserialize::deserialize(res.items)?; Ok(items) } /// List an item for sale on the flea market. pub async fn offer_item( &self, items: &[&str], requirements: &[Requirement], sell_all: bool, ) -> Result<InventoryUpdate> { if items.is_empty() || requirements.is_empty() { return Err(Error::InvalidParameters); } let url = format!("{}/client/game/profile/items/moving", PROD_ENDPOINT); let body = &MoveItemRequest { data: &[SellItemRequest { action: "RagFairAddOffer", sell_in_one_piece: sell_all, items, requirements: &requirements .into_iter() .map(|r| SellRequirement { requirement: r.to_owned(), level: 0, side: 0, only_functional: false, }) .collect::<Vec<SellRequirement>>(), }], tm: 2, }; let res: SellItemResponse = self.post_json(&url, body).await?; handle_error2(res.error)?; let res: RagfairResponseData = Deserialize::deserialize(res.data)?; if !res.errors.is_empty() { let error = &res.errors[0]; return Err(Error::UnknownAPIError(error.code)); } let items: InventoryUpdate = Deserialize::deserialize(res.items)?; Ok(items) } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/friend.rs
src/friend.rs
use crate::{handle_error, ErrorResponse, Result, Tarkov, PROD_ENDPOINT}; use crate::profile::Side; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize)] struct FriendResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Friends>, } /// Friend list #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Friends { /// Friends pub friends: Vec<Friend>, /// Muted friend IDs pub ignore: Vec<String>, /// ? pub in_ignore_list: Vec<String>, } /// Friend #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Friend { /// Friend ID #[serde(rename = "_id")] pub id: String, /// Friend info pub info: Info, } /// Friend info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Info { /// Friend nickname pub nickname: String, /// Friend side pub side: Side, /// Friend level pub level: u64, /// ? pub member_category: String, } impl Tarkov { /// Get a list of account's friends. pub async fn get_friends(&self) -> Result<Friends> { let url = format!("{}/client/friend/list", PROD_ENDPOINT); let res: FriendResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/profile.rs
src/profile.rs
use crate::{handle_error, Error, ErrorResponse, Result, Tarkov, PROD_ENDPOINT}; use crate::bad_json::deserialize_integer_to_string; use crate::inventory::Item; use crate::ragfair::Offer; use serde::{Deserialize, Serialize}; use std::collections::HashMap; #[derive(Debug, Deserialize)] struct ProfileResponse { #[serde(flatten)] error: ErrorResponse, data: Option<Vec<Profile>>, } /// Profile #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Profile { /// Profile ID #[serde(rename = "_id")] pub id: String, /// ? #[serde(rename = "aid")] pub aid: u64, /// SCAV profile ID #[serde(rename = "savage")] pub savage: Option<String>, /// Profile info pub info: Info, /// Character customization pub customization: Customization, /// Character health pub health: Health, /// Inventory pub inventory: Inventory, /// Skills pub skills: Skills, /// Stats pub stats: Stats, /// Encyclopedia pub encyclopedia: HashMap<String, bool>, /// ? pub condition_counters: ConditionCounters, /// ? pub backend_counters: HashMap<String, BackendCounter>, /// Insured items pub insured_items: Vec<InsuredItem>, /// Unimplemented type pub hideout: serde_json::Value, /// Unknown type pub notes: serde_json::Value, /// Bonuses? pub bonuses: Vec<Bonus>, /// Active quests pub quests: Vec<Quest>, /// Flea market stats #[serde(rename = "RagfairInfo")] pub ragfair: Ragfair, /// Unknown type pub trader_standings: serde_json::Value, /// Item wishlist #[serde(rename = "WishList")] pub wishlist: Vec<String>, } /// Profile info #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Info { /// Profile nickname pub nickname: String, /// Profile lowercase nickname pub lower_nickname: String, /// Profile side pub side: Side, /// Profile voice pub voice: String, /// Profile level pub level: u64, /// Profile experience points pub experience: u64, /// Profile registration timestamp pub registration_date: u64, /// Game version pub game_version: String, /// Profile type pub account_type: u64, /// ? #[serde(deserialize_with = "deserialize_integer_to_string")] pub member_category: String, /// ? #[serde(rename = "lockedMoveCommands")] pub locked_move_commands: bool, /// SCAV cooldown timestamp pub savage_lock_time: u64, /// Last time played as SCAV pub last_time_played_as_savage: u64, /// Profile settings pub settings: Settings, /// ? pub need_wipe: bool, /// ? pub global_wipe: bool, /// Profile nickname change timestamp pub nickname_change_date: u64, /// Unknown type pub bans: serde_json::Value, } /// Faction, team or side. #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub enum Side { /// BEAR faction Bear, /// USEC faction Usec, /// SCAV Savage, } /// Profile settings #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Settings { /// ? pub role: Option<String>, /// ? pub bot_difficulty: Option<String>, /// ? pub experience: Option<i64>, } /// Player customization #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Customization { /// Head customization pub head: String, /// Body customization pub body: String, /// Feet customization pub feet: String, /// Hands customization pub hands: String, } /// Player health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Health { /// Hydration level pub hydration: HealthLevel, /// Energy level pub energy: HealthLevel, /// Body parts health pub body_parts: BodyParts, /// ? pub update_time: u64, } /// Health level #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct HealthLevel { /// Current health pub current: f64, /// Maximum health pub maximum: f64, } /// Body health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct BodyParts { /// Head health pub head: Head, /// Chest health pub chest: Chest, /// Stomach health pub stomach: Stomach, /// Left arm health pub left_arm: LeftArm, /// Right arm health pub right_arm: RightArm, /// Left leg health pub left_leg: LeftLeg, /// Right arm health pub right_leg: RightLeg, } /// Head health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Head { /// Health pub health: HealthLevel, } /// Chest health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Chest { /// Health pub health: HealthLevel, } /// Stomach health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Stomach { /// Health pub health: HealthLevel, } /// Left arm health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct LeftArm { /// Health pub health: HealthLevel, } /// Right arm health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct RightArm { /// Health pub health: HealthLevel, } /// Left leg health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct LeftLeg { /// Health pub health: HealthLevel, } /// Right leg health #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct RightLeg { /// Health pub health: HealthLevel, } /// Profile inventory #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Inventory { /// Items pub items: Vec<Item>, /// Equipment pub equipment: String, /// Stash pub stash: Option<String>, /// ? pub quest_raid_items: String, /// ? pub quest_stash_items: String, /// Unknown type pub fast_panel: serde_json::Value, } /// Player skills #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Skills { /// Common skills pub common: Vec<CommonSkill>, /// Master skills pub mastering: Vec<MasteringSkill>, /// Skill points pub points: f64, } /// Common skill #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct CommonSkill { /// Skill ID pub id: String, /// Skill progress pub progress: f64, /// Points earned during session pub points_earned_during_session: Option<f64>, /// ? pub last_access: i64, } /// Master skill #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct MasteringSkill { /// Skill ID pub id: String, /// Skill progress pub progress: u64, } /// Player statistics #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Stats { /// Session stats counters pub session_counters: SessionCounters, /// Overall stats counters pub overall_counters: OverallCounters, /// Session experience multiplier? pub session_experience_mult: f64, /// Experience bonus multiplier? pub experience_bonus_mult: f64, /// Total session experience pub total_session_experience: u64, /// Last session timestamp pub last_session_date: u64, /// ? pub aggressor: Option<Aggressor>, /// Total game time pub total_in_game_time: u64, /// Survivor class pub survivor_class: String, /// Unknown type pub dropped_items: serde_json::Value, /// Unknown type pub found_in_raid_items: serde_json::Value, /// Unknown type pub victims: Vec<Victim>, /// Unknown type pub carried_quest_items: serde_json::Value, } /// Session stats counter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SessionCounters { /// Statistics pub items: Vec<SessionItem>, } /// Overall stats counter #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct OverallCounters { /// Statistics pub items: Vec<SessionItem>, } /// Statistics #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SessionItem { /// Statistic key pub key: Vec<String>, /// Statistic value pub value: u64, } /// Aggressor #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Aggressor { /// Aggressor name pub name: String, /// Aggressor side pub side: Side, /// Aggressor body part pub body_part: String, /// Aggressor head segment pub head_segment: Option<String>, /// Aggressor weapon name pub weapon_name: String, /// Aggressor category pub category: String, } /// Victim #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct Victim { /// Victim name pub name: String, /// Victim side pub side: Side, /// Victim death time pub time: String, /// Victim level pub level: u64, /// Body part shot pub body_part: String, /// Weapon used to kill pub weapon: String, } /// ? #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct ConditionCounters { /// Counters pub counters: Vec<ConditionCounter>, } /// ? #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ConditionCounter { /// Counter ID pub id: String, /// Counter value pub value: u64, } /// ? #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct BackendCounter { /// Counter ID pub id: String, /// ? pub qid: String, /// Counter value pub value: u64, } /// Insured item #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct InsuredItem { /// Insurance ID #[serde(rename = "tid")] id: String, /// Insured item ID item_id: String, } /// Bonus? #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Bonus { /// ? #[serde(rename = "type")] pub bonus_type: String, /// ? pub template_id: Option<String>, /// ? pub value: Option<i64>, /// ? pub passive: Option<bool>, /// ? pub visible: Option<bool>, /// ? pub production: Option<bool>, /// ? pub filter: Option<Vec<String>>, /// ? pub id: Option<String>, /// ? pub icon: Option<String>, } /// Quest #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Quest { /// Quest ID #[serde(rename = "qid")] pub id: String, /// Quest start time pub start_time: u64, /// Quest status pub status: u64, /// Quest status timers pub status_timers: HashMap<String, u64>, } /// Flea market profile #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Ragfair { /// Market rating pub rating: f64, /// Market rating is growing pub is_rating_growing: bool, /// Active offers (items for sale) pub offers: Vec<Offer>, } /// Profile error. #[derive(Debug, err_derive::Error)] pub enum ProfileError { /// Invalid user ID selected. #[error(display = "invalid user id selected")] InvalidUserID, /// Failed selecting profile. #[error(display = "select profile failed")] SelectProfileFail, } #[derive(Debug, Serialize)] struct SelectRequest<'a> { uid: &'a str, } #[derive(Debug, Deserialize)] struct SelectResponse { #[serde(flatten)] error: ErrorResponse, data: Option<ProfileSelected>, } /// Profile select result #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] #[serde(rename_all = "camelCase")] struct ProfileSelected { /// Profile status pub status: String, /// Profile notifier pub notifier: Notifier, /// Profile notifier server pub notifier_server: String, } /// Profile notifier #[derive(Debug, Deserialize, Serialize, Clone, PartialEq)] pub struct Notifier { /// Notifier server pub server: String, /// Notifier channel ID pub channel_id: String, /// Notifier URL pub url: String, } impl Tarkov { /// Get a list of account's profiles. pub async fn get_profiles(&self) -> Result<Vec<Profile>> { let url = format!("{}/client/game/profile/list", PROD_ENDPOINT); let res: ProfileResponse = self.post_json(&url, &{}).await?; handle_error(res.error, res.data) } /// Select a profile by user ID. pub async fn select_profile(&self, user_id: &str) -> Result<()> { if user_id.is_empty() { return Err(Error::InvalidParameters); } let url = format!("{}/client/game/profile/select", PROD_ENDPOINT); let res: SelectResponse = self .post_json(&url, &SelectRequest { uid: user_id }) .await?; let res = handle_error(res.error, res.data)?; if res.status != "ok" { return Err(ProfileError::SelectProfileFail)?; } Ok(()) } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/src/bad_json.rs
src/bad_json.rs
//! EFT API returns a lot of inconsistent and bad JSON. Serde deserializers to fix those broken JSON. use crate::inventory::Location; use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize}; use serde_json::Value; use std::fmt; pub(crate) fn deserialize_integer_to_string<'de, D>(de: D) -> Result<String, D::Error> where D: Deserializer<'de>, { let json: serde_json::Value = Deserialize::deserialize(de)?; match json { Value::Number(i) => Ok(i.to_string()), Value::String(s) => Ok(s), _ => Err(Error::custom("Unexpected value")), } } pub(crate) fn deserialize_integer_to_option_string<'de, D>( de: D, ) -> Result<Option<String>, D::Error> where D: Deserializer<'de>, { let json: serde_json::Value = Deserialize::deserialize(de)?; match json { Value::Number(i) => Ok(Some(i.to_string())), Value::String(s) => Ok(Some(s)), _ => Ok(None), } } pub(crate) fn deserialize_bad_location_as_none<'de, D>(de: D) -> Result<Option<Location>, D::Error> where D: Deserializer<'de>, { let json: serde_json::Value = Deserialize::deserialize(de)?; match json { Value::Object(_) => Ok(Some( serde_json::from_value(json).map_err(|_| Error::custom("Unexpected value"))?, )), _ => Ok(None), } } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct StringOrInt(String); impl<'de> Deserialize<'de> for StringOrInt { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct StringOrIntVisitor; impl<'de> Visitor<'de> for StringOrIntVisitor { type Value = StringOrInt; fn expecting(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "string or integer represented as String.") } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(StringOrInt(v.to_string())) } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(StringOrInt(v.to_string())) } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(StringOrInt(v.to_string())) } } deserializer.deserialize_any(StringOrIntVisitor) } } impl StringOrInt { pub fn as_ref(&self) -> &str { self.0.as_str() } }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/tests/test_api.rs
tests/test_api.rs
use std::env; use std::time::{SystemTime, UNIX_EPOCH}; use tarkov::inventory::BarterItem; use tarkov::market_filter::{Currency, MarketFilter, Owner}; use tarkov::profile::Side; use tarkov::ragfair::Requirement; use tarkov::{Result, Tarkov}; #[tokio::test] async fn test_profile() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; Ok(()) } #[tokio::test] async fn test_keep_alive() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); t.keep_alive().await?; Ok(()) } #[tokio::test] async fn test_constants() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let _ = t.get_items().await?; let _ = t.get_item_prices().await?; let _ = t.get_locations().await?; let _ = t.get_weather().await?; let _ = t.get_i18n("en").await?; Ok(()) } #[tokio::test] async fn test_flea_market_getters() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let _ = t.search_market(0, 15, MarketFilter::default()).await?; // USD price let _ = t.get_item_price("5696686a4bdc2da3298b456a").await?; Ok(()) } #[tokio::test] async fn test_flea_market_buying() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); let offers = t .search_market( 0, 15, MarketFilter { max_price: Some(2000), handbook_id: Some("5b47574386f77428ca22b33e"), owner_type: Owner::Player, hide_bartering_offers: true, currency: Currency::Rouble, ..MarketFilter::default() }, ) .await?; let current_time = SystemTime::now(); let epoch_time = current_time.duration_since(UNIX_EPOCH).unwrap().as_secs(); let offer = offers .offers .into_iter() .find(|o| o.start_time + 60 <= epoch_time && o.end_time >= epoch_time) .unwrap(); let rouble = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "5449016a4bdc2d6f028b456f") .unwrap(); let _ = t .buy_item( &offer.id, 1, &[BarterItem { id: rouble.id.to_owned(), count: offer.requirements_cost as f64, }], ) .await?; Ok(()) } #[tokio::test] async fn test_flea_market_selling() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); let painkiller = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "544fb37f4bdc2dee738b4567") .unwrap(); let _ = t .offer_item( &[&painkiller.id], &[Requirement { schema_id: "5449016a4bdc2d6f028b456f".to_string(), count: 2000.0, }], false, ) .await?; Ok(()) } #[tokio::test] async fn test_trader_getters() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let traders = t.get_traders().await?; let trader = traders.get(0).unwrap(); let trader = t.get_trader(&trader.id).await?; let _ = t.get_trader_items(&trader.id).await?; Ok(()) } #[tokio::test] async fn test_trader_buying() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| t.nickname == "Терапевт") .unwrap(); let rouble = &profile .inventory .items .into_iter() .find(|i| { i.schema_id == "5449016a4bdc2d6f028b456f" && i.upd.as_ref().unwrap().stack_objects_count >= Some(3990) }) .unwrap(); let _ = t .trade_item( &trader.id, "5e064f5deb009468d90baef7", // ID might change. 1, &[BarterItem { id: rouble.id.to_owned(), count: 3990.0, // Assume price is 3990₽. }], ) .await?; Ok(()) } #[tokio::test] async fn test_trader_selling() -> Result<()> { let session = env::var("TARKOV_SESSION").unwrap(); let t = Tarkov::from_session(&session); let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| t.nickname == "Терапевт") .unwrap(); let painkiller = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "544fb37f4bdc2dee738b4567") .unwrap(); let _ = t.sell_item(&trader.id, &painkiller.id, 1).await?; Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/auth_basic.rs
examples/auth_basic.rs
use tarkov::hwid::generate_hwid; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::login("me@example.com", "password", generate_hwid().as_str()).await?; println!("{}", t.session); let t = Tarkov::from_access_token( "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", generate_hwid().as_str(), ) .await?; println!("{}", t.session); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db1"); println!("{}", t.session); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/auth_captcha.rs
examples/auth_captcha.rs
use tarkov::auth::LoginError; use tarkov::hwid::generate_hwid; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let email = "me@example.com"; let password = "password"; let hwid = generate_hwid(); let t = match Tarkov::login(email, password, &hwid).await { Ok(t) => Ok(t), Err(Error::LoginError(e)) => match e { // Captcha required! LoginError::CaptchaRequired => { // Solve captcha here and try again let captcha = "03AOLTBLQ952pO-qQYPeLr53N5nK9Co14iXyCp..."; Tarkov::login_with_captcha(email, password, captcha, &hwid).await } _ => Err(e)?, }, Err(e) => Err(e), }?; println!("{}", t.session); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/ragfair_buy_item.rs
examples/ragfair_buy_item.rs
use std::time::{SystemTime, UNIX_EPOCH}; use tarkov::inventory::BarterItem; use tarkov::market_filter::{Currency, MarketFilter, Owner}; use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db2"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Fetch the translation table for market categories. let locale = t.get_i18n("en").await?; // Get the "Barter items" category ID. let barter_item_category_id: Option<String> = { let mut id = None; for (k, v) in locale.handbook { if v == "Barter items" { id = Some(k); break; } } id }; // Search flea market. let offers = t .search_market( 0, 15, MarketFilter { max_price: Some(2000), handbook_id: barter_item_category_id.as_deref(), owner_type: Owner::Player, hide_bartering_offers: true, currency: Currency::Rouble, ..MarketFilter::default() }, ) .await?; // Find the first item available for purchase immediately. let current_time = SystemTime::now(); let epoch_time = current_time.duration_since(UNIX_EPOCH).unwrap().as_secs(); let offer = offers .offers .into_iter() .find(|o| o.start_time + 60 <= epoch_time && o.end_time >= epoch_time) .unwrap(); // Get Rouble item ID from my inventory let rouble = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "5449016a4bdc2d6f028b456f") .unwrap(); // Buy the item. println!( "{:#?}", t.buy_item( &offer.id, 1, &[BarterItem { id: rouble.id.to_owned(), count: offer.requirements_cost as f64, }], ) .await? ); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/search_traders.rs
examples/search_traders.rs
use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db2"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Fetch the translation table because trader names are in Russian. let locale = t.get_i18n("en").await?; // Find trader by name. let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| locale.traders.get(&t.id).unwrap().nickname == "Mechanic") .unwrap(); println!("{:#?}", trader); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/auth_2fa.rs
examples/auth_2fa.rs
use tarkov::auth::LoginError; use tarkov::hwid::generate_hwid; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let email = "me@example.com"; let password = "password"; let hwid = generate_hwid(); let t = match Tarkov::login(email, password, &hwid).await { Ok(t) => Ok(t), Err(Error::LoginError(e)) => match e { // 2FA required! LoginError::TwoFactorRequired => { // Get 2FA from email (or generate TOTP) then continue... let code = "XYZ"; Tarkov::login_with_2fa(email, password, code, &hwid).await } _ => Err(e)?, }, Err(e) => Err(e), }?; println!("{}", t.session); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/search_trader_items.rs
examples/search_trader_items.rs
use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db2"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Fetch the translation table because trader names are in Russian. let locale = t.get_i18n("en").await?; // Find trader by name. let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| locale.traders.get(&t.id).unwrap().nickname == "Therapist") .unwrap(); // Fetch all items to map item ID to item name/descriptor. let items = t.get_items().await?; // Find trader's item by name let trader_items = t.get_trader_items(&trader.id).await?; let painkiller = trader_items .into_iter() .find(|i| { // Therapist sells painkillers for Roubles or 2 matches. Finding the barter deal. let item = items.get(&i.schema_id).unwrap(); item.name == "painkiller" && i.price.get(0).unwrap().count == 2.0 }) .unwrap(); println!("{:#?}", painkiller); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/trader_cash_deal.rs
examples/trader_cash_deal.rs
use tarkov::inventory::BarterItem; use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("3e463058dd4884ab0c4a6035dc56066b"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Get Therapist let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| t.nickname == "Терапевт") .unwrap(); // Therapist wants 3990₽ for 1 painkiller. let painkiller = t .get_trader_items(&trader.id) .await? .into_iter() .find(|i| i.id == "5e064f5deb009468d90baef7") .unwrap(); // Get Rouble item ID from my inventory let rouble = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "5449016a4bdc2d6f028b456f") .unwrap(); // Trade item println!( "{:#?}", t.trade_item( &trader.id, "5e064f5deb009468d90baef7", 1, &[BarterItem { id: rouble.id.to_owned(), count: painkiller.price.get(0).unwrap().count, // Assume price is 3990₽. }], ) .await ); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/trader_sell_item.rs
examples/trader_sell_item.rs
use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("da3902b29e442da4972f8ce499834ee7"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Get Therapist let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| t.nickname == "Терапевт") .unwrap(); // Get painkiller item ID from my inventory let painkiller = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "544fb37f4bdc2dee738b4567") .unwrap(); // Sell item println!("{:#?}", t.sell_item(&trader.id, &painkiller.id, 1).await); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/ragfair_sell_item.rs
examples/ragfair_sell_item.rs
use tarkov::profile::Side; use tarkov::ragfair::Requirement; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db2"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Get the painkiller item ID from my inventory let painkiller = &profile .inventory .items .into_iter() .find(|i| i.schema_id == "544fb37f4bdc2dee738b4567") .unwrap(); // Get market price of painkiller let price = t.get_item_price(&painkiller.schema_id).await?; // Put the painkiller on market for average price println!( "{:#?}", t.offer_item( &[&painkiller.id], &[Requirement { schema_id: "5449016a4bdc2d6f028b456f".to_string(), count: price.avg.round(), }], false, ) .await? ); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
dank/tarkov
https://github.com/dank/tarkov/blob/93d32b66c8b01d8ded7f0b44c75be95a18a27f15/examples/trader_barter_deal.rs
examples/trader_barter_deal.rs
use tarkov::inventory::BarterItem; use tarkov::profile::Side; use tarkov::{Error, Tarkov}; #[tokio::main] async fn main() -> Result<(), Error> { std::env::set_var("RUST_LOG", "tarkov=info"); env_logger::init(); let t = Tarkov::from_session("e1bc65a216325f0ad0db8518fa299db2"); // Find and select PMC profile to complete login. let profiles = t.get_profiles().await?; let profile = profiles .into_iter() .find(|p| p.info.side != Side::Savage) .unwrap(); t.select_profile(&profile.id).await?; // Get Therapist let traders = t.get_traders().await?; let trader = traders .into_iter() .find(|t| t.nickname == "Терапевт") .unwrap(); // Therapist wants 2 matches for 1 painkiller. let painkiller = t .get_trader_items(&trader.id) .await? .into_iter() .find(|i| i.id == "5e064f5deb009468d90baf01") .unwrap(); // Get the IDs of 2 painkillers from my inventory let barter_items = &profile .inventory .items .into_iter() .filter(|i| i.schema_id == painkiller.price.get(0).unwrap().schema_id) .map(|i| BarterItem { id: i.id, count: 1.0, }) .collect::<Vec<BarterItem>>()[..2]; // Trade item println!( "{:#?}", t.trade_item(&trader.id, &painkiller.id, 1, barter_items) .await? ); Ok(()) }
rust
MIT
93d32b66c8b01d8ded7f0b44c75be95a18a27f15
2026-01-04T20:19:02.188879Z
false
drmingdrmer/one-file-raft
https://github.com/drmingdrmer/one-file-raft/blob/3d9ebbbee5fde16f5bf0626be4c565ca9d67860d/src/lib.rs
src/lib.rs
#![doc = include_str!("../README.md")] //! //! - Read the [Tutorial](`crate::docs::tutorial`); //! - Read the [Tutorial-cn](`crate::docs::tutorial_cn`); //! //! Features: //! //! - [x] Election(`Raft::elect()`) //! - [x] Log replication(`Raft::handle_replicate_req()`) //! - [x] Commit //! - [x] Write application data(`Raft::write()`) //! - [x] Membership store(`Store::configs`). //! - [x] Membership change: joint consensus. //! - [x] Event loop model(main loop: `Raft::run()`). //! - [x] Pseudo network simulated by mpsc channels(`Net`). //! - [x] Pseudo Log store simulated by in-memory store(`Store`). //! - [x] Raft log data is a simple `String` //! - [x] Metrics //! //! Not yet implemented: //! - [ ] State machine(`Raft::commit()` is a no-op entry) //! - [ ] Log compaction //! - [ ] Log purge //! - [ ] Heartbeat //! - [ ] Leader lease //! - [ ] Linearizable read //! //! Implementation details: //! - [x] Membership config takes effect once appended(not on-applied). //! - [x] Standalone Leader, it has to check vote when accessing local store. //! - [x] Leader access store directly(not via RPC). //! - [ ] Append log when vote? #![feature(map_try_insert)] mod display; pub mod docs; #[cfg(test)] mod tests; use std::cmp::max; use std::cmp::min; use std::cmp::Ordering; use std::collections::BTreeMap; use std::collections::BTreeSet; use derivative::Derivative; use derive_more::Display; use derive_new::new as New; use itertools::Itertools; use log::debug; use log::error; use log::info; use log::trace; use mpsc::UnboundedReceiver; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::sync::watch; use crate::display::DisplayExt; #[derive(Debug, Clone, Default, Copy, PartialEq, Eq, Hash, Display)] #[display(fmt = "L({})", _0)] pub struct LeaderId(pub u64); impl PartialOrd for LeaderId { fn partial_cmp(&self, b: &Self) -> Option<Ordering> { [None, Some(Ordering::Equal)][(self.0 == b.0) as usize] } } #[derive(Debug, Clone, Default, Copy, PartialEq, Eq, PartialOrd, Hash)] #[derive(New)] pub struct Vote { pub term: u64, pub committed: Option<()>, pub voted_for: LeaderId, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Display)] #[display(fmt = "T{}-{}", term, index)] pub struct LogId { term: u64, index: u64, } #[derive(Debug, Clone, Default, New)] pub struct Log { #[new(default)] pub log_id: LogId, pub data: Option<String>, pub config: Option<Vec<BTreeSet<u64>>>, } #[derive(Debug, Default)] pub struct Net { pub targets: BTreeMap<u64, mpsc::UnboundedSender<(u64, Event)>>, } impl Net { fn send(&mut self, from: u64, target: u64, ev: Event) { trace!("N{} send --> N{} {}", from, target, ev); let tx = self.targets.get(&target).unwrap(); tx.send((from, ev)).unwrap(); } } #[derive(Debug)] pub struct Request { vote: Vote, last_log_id: LogId, prev: LogId, logs: Vec<Log>, commit: u64, } #[derive(Debug)] pub struct Reply { granted: bool, vote: Vote, log: Result<LogId, u64>, } #[derive(Display)] pub enum Event { #[display(fmt = "Request({})", _0)] Request(Request), #[display(fmt = "Reply({})", _0)] Reply(Reply), #[display(fmt = "Write({})", _1)] Write(oneshot::Sender<String>, Log), #[display(fmt = "Func")] Func(Box<dyn FnOnce(&mut Raft) + Send + 'static>), } #[derive(Debug, Clone, Copy, Derivative, PartialEq, Eq, New)] #[derivative(Default)] pub struct Progress { acked: LogId, len: u64, /// It is a token to indicate if it can send an RPC, e.g., there is no inflight RPC sending. /// It is set to `None` when an RPC is sent, and set to `Some(())` when the RPC is finished. #[derivative(Default(value = "Some(())"))] ready: Option<()>, } pub struct Leading { granted_by: BTreeSet<u64>, progresses: BTreeMap<u64, Progress>, log_index_range: (u64, u64), } #[derive(Debug, Default, Clone, PartialEq, Eq, New)] pub struct Metrics { pub vote: Vote, pub last_log: LogId, pub commit: u64, pub config: Vec<BTreeSet<u64>>, pub progresses: Option<BTreeMap<u64, Progress>>, } #[derive(Debug, Default)] pub struct Store { id: u64, vote: Vote, configs: BTreeMap<u64, Vec<BTreeSet<u64>>>, replies: BTreeMap<u64, oneshot::Sender<String>>, logs: Vec<Log>, } impl Store { pub fn new(membership: Vec<BTreeSet<u64>>) -> Self { let mut configs = BTreeMap::new(); let vote = Vote::default(); configs.insert(0, membership); let replies = BTreeMap::new(); Store { id: 0, vote, configs, replies, logs: vec![Log::default()] } } pub fn config(&self) -> &Vec<BTreeSet<u64>> { self.configs.values().last().unwrap() } fn last(&self) -> LogId { self.logs.last().map(|x| x.log_id).unwrap_or_default() } fn truncate(&mut self, log_id: LogId) { debug!("truncate: {}", log_id); self.replies.retain(|&x, _| x < log_id.index); self.configs.retain(|&x, _| x < log_id.index); self.logs.truncate(log_id.index as usize); } fn append(&mut self, logs: Vec<Log>) { if logs.is_empty() { return; } debug!("N{} append: [{}]", self.id, logs.iter().join(", ")); for log in logs { if let Some(x) = self.get_log_id(log.log_id.index) { if x != log.log_id { self.truncate(x); } else { continue; } } if let Some(ref membership) = log.config { self.configs.insert(log.log_id.index, membership.clone()); } self.logs.push(log); } } fn get_log_id(&self, rel_index: u64) -> Option<LogId> { self.logs.get(rel_index as usize).map(|x| x.log_id) } fn read_logs(&self, i: u64, n: u64) -> Vec<Log> { if n == 0 { return vec![]; } let logs: Vec<_> = self.logs[i as usize..].iter().take(n as usize).cloned().collect(); debug!("N{} read_logs: [{i},+{n})={}", self.id, logs.iter().join(",")); logs } } pub struct Raft { pub id: u64, pub leading: Option<Leading>, pub commit: u64, pub net: Net, pub sto: Store, pub metrics: watch::Sender<Metrics>, pub rx: UnboundedReceiver<(u64, Event)>, } impl Raft { pub fn new(id: u64, mut sto: Store, net: Net, rx: UnboundedReceiver<(u64, Event)>) -> Self { let (metrics, _) = watch::channel(Metrics::default()); sto.id = id; Raft { id, leading: None, commit: 0, net, sto, metrics, rx } } pub async fn run(mut self) -> Result<(), anyhow::Error> { loop { let mem = self.sto.config().clone(); #[allow(clippy::useless_asref)] let ps = self.leading.as_ref().map(|x| x.progresses.clone()); let m = Metrics::new(self.sto.vote, self.sto.last(), self.commit, mem, ps); self.metrics.send_replace(m); let (from, ev) = self.rx.recv().await.ok_or(anyhow::anyhow!("closed"))?; debug!("N{} recv <-- N{} {}", self.id, from, ev); match ev { Event::Request(req) => { let reply = self.handle_replicate_req(req); self.net.send(self.id, from, Event::Reply(reply)); } Event::Reply(reply) => { self.handle_replicate_reply(from, reply); } Event::Write(tx, log) => { let res = self.write(tx, log.clone()); if res.is_none() { error!("N{} leader can not write : {}", self.id, log); } } Event::Func(f) => { f(&mut self); } } } } pub fn elect(&mut self) { self.sto.vote = Vote::new(self.sto.vote.term + 1, None, LeaderId(self.id)); let noop_index = self.sto.last().index + 1; let config = self.sto.config().clone(); let p = Progress::new(LogId::default(), noop_index, Some(())); debug!("N{} elect: ids: {}", self.id, node_ids(&config).join(",")); self.leading = Some(Leading { granted_by: BTreeSet::new(), progresses: node_ids(&config).map(|id| (id, p)).collect(), log_index_range: (noop_index, noop_index), }); node_ids(&config).for_each(|id| self.send_if_idle(id, 0).unwrap_or(())); } pub fn write(&mut self, tx: oneshot::Sender<String>, mut log: Log) -> Option<LogId> { self.sto.vote.committed?; let l = self.leading.as_mut()?; let log_id = LogId { term: self.sto.vote.term, index: l.log_index_range.1 }; l.log_index_range.1 += 1; log.log_id = log_id; if let Some(ref membership) = log.config { if self.sto.configs.keys().last().copied().unwrap() > self.commit { panic!("N{} can write membership: {} before committing the previous", self.id, log); } let ids = node_ids(membership); l.progresses = ids.map(|x| (x, l.progresses.remove(&x).unwrap_or_default())).collect(); info!("N{} rebuild progresses: {}", self.id, l.progresses.display()); } self.sto.replies.insert(log_id.index, tx); self.sto.append(vec![log]); // Mark it as sending, so that it won't be sent again. l.progresses.insert(self.id, Progress::new(log_id, log_id.index, None)); node_ids(self.sto.config()).for_each(|id| self.send_if_idle(id, 10).unwrap_or(())); Some(log_id) } pub fn handle_replicate_req(&mut self, req: Request) -> Reply { let my_last = self.sto.last(); let (is_granted, vote) = self.check_vote(req.vote); let is_upto_date = req.last_log_id >= my_last; let req_last = req.logs.last().map(|x| x.log_id).unwrap_or(req.prev); if is_granted && is_upto_date { let log = if self.sto.get_log_id(req.prev.index) == Some(req.prev) { self.sto.append(req.logs); self.commit(min(req.commit, req_last.index)); Ok(req_last) } else { self.sto.truncate(req.prev); Err(req.prev.index) }; Reply { granted: true, vote, log } } else { Reply { granted: false, vote, log: Err(my_last.index + 1) } } } pub fn handle_replicate_reply(&mut self, target: u64, reply: Reply) -> Option<Leading> { let l = self.leading.as_mut()?; let v = self.sto.vote; let is_same_leader = reply.vote.term == v.term && reply.vote.voted_for == v.voted_for; // 0. Set a replication channel to `ready`, once a reply is received. if is_same_leader { assert!(l.progresses[&target].ready.is_none()); l.progresses.get_mut(&target).unwrap().ready = Some(()); } if reply.granted && is_same_leader { // 1. Vote is granted, means that Log replication privilege is acquired. if v.committed.is_none() { debug!("N{} is granted by: N{}", self.id, target); l.granted_by.insert(target); if is_quorum(self.sto.config(), &l.granted_by) { self.sto.vote.committed = Some(()); info!("N{} Leader established: {}", self.id, self.sto.vote); let (tx, _rx) = oneshot::channel(); self.net.send(self.id, self.id, Event::Write(tx, Log::default())); } } let p = l.progresses.get_mut(&target).unwrap(); // 2. Update the log replication progress *p = match reply.log { Ok(acked) => Progress::new(acked, max(p.len, acked.index + 1), Some(())), Err(len) => Progress::new(p.acked, min(p.len, len), Some(())), }; debug!("N{} progress N{target}={}", self.id, p); // 3. Update committed index let (noop_index, len) = l.log_index_range; let acked = p.acked.index; let acked_desc = l.progresses.values().map(|p| p.acked).sorted().rev(); let mut max_committed = acked_desc.filter(|acked| { let greater_equal = l.progresses.iter().filter(|(_id, p)| p.acked >= *acked); acked.index >= noop_index && is_quorum(self.sto.config(), greater_equal.map(|(id, _)| id)) }); if let Some(log_id) = max_committed.next() { self.commit(log_id.index) } // 4. Keep sending if len - 1 > acked { self.send_if_idle(target, len - 1 - acked); } } else { self.check_vote(reply.vote); } None } pub fn send_if_idle(&mut self, target: u64, n: u64) -> Option<()> { let l = self.leading.as_mut().unwrap(); let p = l.progresses.get_mut(&target).unwrap(); p.ready.take()?; let prev = (p.acked.index + p.len) / 2; let req = Request { vote: self.sto.vote, last_log_id: self.sto.last(), prev: self.sto.get_log_id(prev).unwrap(), logs: self.sto.read_logs(prev + 1, n), commit: self.commit, }; self.net.send(self.id, target, Event::Request(req)); Some(()) } fn commit(&mut self, i: u64) { if i > self.commit { info!("N{} commit: {i}: {}", self.id, self.sto.logs[i as usize]); self.commit = i; let right = self.sto.replies.split_off(&(i + 1)); for (i, tx) in std::mem::replace(&mut self.sto.replies, right).into_iter() { let _ = tx.send(format!("{}", i)); } } } pub fn check_vote(&mut self, vote: Vote) -> (bool, Vote) { trace!("N{} check_vote: my:{}, {}", self.id, self.sto.vote, vote); if vote > self.sto.vote { info!("N{} update_vote: {} --> {}", self.id, self.sto.vote, vote); self.sto.vote = vote; if vote.voted_for != LeaderId(self.id) && self.leading.is_some() { info!("N{} Leading quit: vote:{}", self.id, self.sto.vote); self.leading = None; } } trace!("check_vote: ret: {}", self.sto.vote); (vote == self.sto.vote, self.sto.vote) } } pub fn is_quorum<'a>(config: &[BTreeSet<u64>], granted: impl IntoIterator<Item = &'a u64>) -> bool { let granted = granted.into_iter().copied().collect::<BTreeSet<_>>(); for group in config { if group.intersection(&granted).count() <= group.len() / 2 { return false; } } true } pub fn node_ids(config: &[BTreeSet<u64>]) -> impl Iterator<Item = u64> + 'static { config.iter().flat_map(|x| x.iter().copied()).collect::<BTreeSet<_>>().into_iter() }
rust
Apache-2.0
3d9ebbbee5fde16f5bf0626be4c565ca9d67860d
2026-01-04T20:19:09.207473Z
false
drmingdrmer/one-file-raft
https://github.com/drmingdrmer/one-file-raft/blob/3d9ebbbee5fde16f5bf0626be4c565ca9d67860d/src/tests.rs
src/tests.rs
#![allow(clippy::let_underscore_future)] use std::collections::BTreeSet; use log::debug; use log::info; use mpsc::UnboundedSender; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::sync::watch; use crate::Event; use crate::LeaderId; use crate::Log; use crate::Metrics; use crate::Net; use crate::Raft; use crate::Store; #[tokio::test(flavor = "current_thread")] async fn test_raft() { env_logger::builder().filter_level(log::LevelFilter::Debug).init(); fn btset( config: impl IntoIterator<Item = impl IntoIterator<Item = u64>>, ) -> Vec<BTreeSet<u64>> { config.into_iter().map(|x| x.into_iter().collect()).collect() } let sto123 = || Store::new(btset([[1, 2, 3]])); let (tx1, rx1) = mpsc::unbounded_channel(); let (tx2, rx2) = mpsc::unbounded_channel(); let (tx3, rx3) = mpsc::unbounded_channel(); let (tx4, rx4) = mpsc::unbounded_channel(); let net = || { let mut r = Net::default(); r.targets.insert(1, tx1.clone()); r.targets.insert(2, tx2.clone()); r.targets.insert(3, tx3.clone()); r.targets.insert(4, tx4.clone()); r }; let n1 = Raft::new(1, sto123(), net(), rx1); let n2 = Raft::new(2, sto123(), net(), rx2); let n3 = Raft::new(3, sto123(), net(), rx3); let n4 = Raft::new(4, Store::new(btset([[]])), net(), rx4); let h1 = tokio::spawn(n1.run()); let h2 = tokio::spawn(n2.run()); let h3 = tokio::spawn(n3.run()); let h4 = tokio::spawn(n4.run()); async fn func<T>( raft_tx: &UnboundedSender<(u64, Event)>, f: impl FnOnce(&mut Raft) -> T + Send + 'static, ) -> T where T: Send + 'static, { let (tx, rx) = oneshot::channel(); let call_and_send = |raft: &mut Raft| { let ret = f(raft); let _ = tx.send(ret); }; raft_tx.send((0, Event::Func(Box::new(call_and_send)))).unwrap(); rx.await.unwrap() } async fn metrics(raft_tx: &UnboundedSender<(u64, Event)>) -> watch::Receiver<Metrics> { func(raft_tx, |raft| raft.metrics.subscribe()).await } async fn elect(raft_tx: &UnboundedSender<(u64, Event)>, id: u64) { func(raft_tx, |raft| raft.elect()).await; let mut mtx = metrics(raft_tx).await; loop { { let mm = mtx.borrow(); if mm.vote.voted_for == LeaderId(id) && mm.vote.committed.is_some() { info!("=== Leader established {}", mm.vote); break; } } mtx.changed().await.unwrap(); } } /// Write a log to a raft node async fn write(raft_tx: &UnboundedSender<(u64, Event)>, log: Log) -> String { let (tx, rx) = oneshot::channel(); func(raft_tx, |raft| raft.write(tx, log)).await; let got = rx.await.unwrap(); debug!("got: {:?}", got); got } elect(&tx1, 1).await; write(&tx1, Log::new(Some(s("x=1")), None)).await; elect(&tx2, 2).await; write(&tx2, Log::new(None, Some(btset([vec![1, 2, 3], vec![1, 2, 3, 4]])))).await; write(&tx2, Log::new(None, Some(btset([vec![1, 2, 3, 4]])))).await; let metrics = metrics(&tx2).await; info!("=== {}", metrics.borrow().clone()); tokio::time::sleep(std::time::Duration::from_secs(1)).await; let _ = h1; let _ = h2; let _ = h3; let _ = h4; } fn s(x: impl ToString) -> String { x.to_string() }
rust
Apache-2.0
3d9ebbbee5fde16f5bf0626be4c565ca9d67860d
2026-01-04T20:19:09.207473Z
false
drmingdrmer/one-file-raft
https://github.com/drmingdrmer/one-file-raft/blob/3d9ebbbee5fde16f5bf0626be4c565ca9d67860d/src/display.rs
src/display.rs
use std::collections::BTreeMap; use std::collections::BTreeSet; use std::fmt; use itertools::Itertools; use crate::Log; use crate::Metrics; use crate::Progress; use crate::Reply; use crate::Request; use crate::Vote; pub struct Display<'a, T> { v: &'a T, } pub(crate) trait DisplayExt { fn display(&self) -> Display<Self> where Self: Sized { Display { v: self } } } impl<T> DisplayExt for T {} impl<'a, T, E> fmt::Display for Display<'a, Result<T, E>> where T: fmt::Display, E: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.v { Ok(v) => write!(f, "Ok({})", v), Err(e) => write!(f, "Err({})", e), } } } impl<'a, T> fmt::Display for Display<'a, BTreeSet<T>> where T: fmt::Display { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{{")?; let s = self.v.iter().map(|x| x.to_string()).join(", "); write!(f, "{}", s)?; write!(f, "}}") } } impl<'a, K, V> fmt::Display for Display<'a, BTreeMap<K, V>> where K: fmt::Display, V: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{{")?; let s = self.v.iter().map(|(k, v)| format!("{k}={v}")).join(", "); write!(f, "{}", s)?; write!(f, "}}") } } impl<'a, T> fmt::Display for Display<'a, Vec<BTreeSet<T>>> where T: fmt::Display { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[")?; let s = self.v.iter().map(|x| x.display().to_string()).join(", "); write!(f, "{}", s)?; write!(f, "]") } } impl fmt::Display for Vote { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let c = if self.committed.is_some() { "COMMITTED" } else { "uncommitted" }; write!(f, "T{}-{c}-{}", self.term, self.voted_for) } } impl fmt::Display for Log { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Log({}", self.log_id)?; if self.data.is_none() && self.config.is_none() { write!(f, ", noop)")?; } if let Some(ref d) = self.data { write!(f, ", data:{}", d)?; } if let Some(ref c) = self.config { write!(f, ", members:{}", c.display())?; } write!(f, ")") } } impl fmt::Display for Progress { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "([{}, {}), {})", self.acked, self.len, if self.ready.is_some() { "READY" } else { "busy" } ) } } impl fmt::Display for Metrics { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Metrics(vote:{}, last:{}, commit:{}", self.vote, self.last_log, self.commit)?; write!(f, ", config:{}", self.config.display())?; if let Some(ref progresses) = self.progresses { write!(f, ", progresses:{{")?; let ps = progresses.iter().map(|(id, p)| format!("N{id}={p}")).join(", "); write!(f, " {ps}",)?; write!(f, " }}")?; } write!(f, ")") } } impl fmt::Display for Request { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "(vote:{}, last:{}", self.vote, self.last_log_id,)?; write!(f, " commit:{}", self.commit)?; write!(f, " logs:{}<{})", self.prev, self.logs.iter().join(",")) } } impl fmt::Display for Reply { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let granted = if self.granted { "granted" } else { "denied" }; let log = match self.log { Ok(acked) => { format!("Ack({})", acked) } Err(end) => { format!("Conflict({})", end) } }; write!(f, "({granted}, vote:{}, {})", self.vote, log) } }
rust
Apache-2.0
3d9ebbbee5fde16f5bf0626be4c565ca9d67860d
2026-01-04T20:19:09.207473Z
false
drmingdrmer/one-file-raft
https://github.com/drmingdrmer/one-file-raft/blob/3d9ebbbee5fde16f5bf0626be4c565ca9d67860d/src/docs/mod.rs
src/docs/mod.rs
#![doc = include_str!("docs.md")] pub mod tutorial { #![doc = include_str!("comment.md")] } pub mod tutorial_cn { #![doc = include_str!("comment-cn.md")] }
rust
Apache-2.0
3d9ebbbee5fde16f5bf0626be4c565ca9d67860d
2026-01-04T20:19:09.207473Z
false
tun-rs/tun-rs
https://github.com/tun-rs/tun-rs/blob/c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7/build.rs
build.rs
fn main() { println!("cargo:rerun-if-env-changed=DOCS_RS"); let docs_builder = std::env::var("DOCS_RS").is_ok(); if docs_builder { println!("cargo:rustc-cfg=docsrs"); return; } let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); if target_os == "windows" { #[cfg(feature = "bindgen")] build_wrapper_wintun(); } } #[cfg(feature = "bindgen")] fn build_wrapper_wintun() { use std::env; use std::path::PathBuf; let header_path = "src/platform/windows/tun/wintun_functions.h"; println!("cargo:rerun-if-changed={header_path}"); let bindings = bindgen::Builder::default() .header(header_path) .allowlist_function("Wintun.*") .allowlist_type("WINTUN_.*") .dynamic_library_name("wintun") .dynamic_link_require_all(true) .layout_tests(false) .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) .generate() .expect("Unable to generate bindings for wintun_functions.h"); println!("OUT_DIR = {}", env::var("OUT_DIR").unwrap()); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings.rs")) .expect("Couldn't write bindings!"); }
rust
Apache-2.0
c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7
2026-01-04T20:19:01.665942Z
false
tun-rs/tun-rs
https://github.com/tun-rs/tun-rs/blob/c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7/src/builder.rs
src/builder.rs
use std::io; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use std::str::FromStr; use crate::platform::{DeviceImpl, SyncDevice}; /// Represents the OSI layer at which the TUN interface operates. /// /// - **L2**: Data Link Layer (available on Windows, Linux, and FreeBSD; used for TAP interfaces). /// - **L3**: Network Layer (default for TUN interfaces). #[derive(Clone, Copy, Default, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum Layer { /// Data Link Layer. #[cfg(any( target_os = "windows", target_os = "linux", target_os = "freebsd", target_os = "macos", target_os = "openbsd", target_os = "netbsd", ))] L2, /// Network Layer (default for TUN interfaces). #[default] L3, } /// Configuration for a TUN/TAP interface. /// /// This structure stores settings such as the device name, operating layer, /// and platform-specific parameters (e.g., GUID, wintun file, ring capacity on Windows). #[derive(Clone, Default, Debug)] pub(crate) struct DeviceConfig { /// The name of the device/interface. pub(crate) dev_name: Option<String>, /// The description of the device/interface. #[cfg(windows)] pub(crate) description: Option<String>, /// Available with Layer::L2; creates a pair of feth devices, with peer_feth as the IO interface name. #[cfg(target_os = "macos")] pub(crate) peer_feth: Option<String>, /// If true (default), the program will automatically add or remove routes on macOS or FreeBSD to provide consistent routing behavior across all platforms. /// If false, the program will not modify or manage routes in any way, allowing the system to handle all routing natively. /// Set this to be false to obtain the platform's default routing behavior. #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub(crate) associate_route: Option<bool>, /// If true (default), the existing device with the given name will be used if possible. /// If false, an error will be returned if a device with the specified name already exists. #[cfg(any(target_os = "macos", target_os = "windows", target_os = "netbsd"))] pub(crate) reuse_dev: Option<bool>, /// If true, the feth device will be kept after the program exits; /// if false (default), the device will be destroyed automatically. #[cfg(any(target_os = "macos", target_os = "windows"))] pub(crate) persist: Option<bool>, /// Specifies whether the interface operates at L2 or L3. #[allow(dead_code)] pub(crate) layer: Option<Layer>, /// Device GUID on Windows. #[cfg(windows)] pub(crate) device_guid: Option<u128>, #[cfg(windows)] pub(crate) wintun_log: Option<bool>, /// Path to the wintun file on Windows. #[cfg(windows)] pub(crate) wintun_file: Option<String>, /// Capacity of the ring buffer on Windows. #[cfg(windows)] pub(crate) ring_capacity: Option<u32>, /// Whether to call WintunDeleteDriver to remove the driver. /// Default: false. #[cfg(windows)] pub(crate) delete_driver: Option<bool>, #[cfg(windows)] pub(crate) mac_address: Option<String>, /// switch of Enable/Disable packet information for network driver #[cfg(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub(crate) packet_information: Option<bool>, /// Enable/Disable TUN offloads. /// After enabling, use `recv_multiple`/`send_multiple` for data transmission. #[cfg(target_os = "linux")] pub(crate) offload: Option<bool>, /// Enable multi queue support #[cfg(target_os = "linux")] pub(crate) multi_queue: Option<bool>, } type IPV4 = ( io::Result<Ipv4Addr>, io::Result<u8>, Option<io::Result<Ipv4Addr>>, ); /// A builder for configuring a TUN/TAP interface. /// /// This builder allows you to set parameters such as device name, MTU, /// IPv4/IPv6 addresses, MAC address, and other platform-specific options. /// /// # Examples /// /// Creating a basic IPv4 TUN interface: /// /// ````no_run /// use std::net::Ipv4Addr; /// use tun_rs::DeviceBuilder; /// /// fn main() -> std::io::Result<()> { /// let tun = DeviceBuilder::new() /// .name("my-tun") /// .mtu(1500) /// .ipv4(Ipv4Addr::new(10, 0, 0, 1), 24, None) /// .build_sync()?; /// Ok(()) /// } /// ```` /// /// Creating an IPv6 TUN interface: /// /// ````no_run /// use std::net::Ipv6Addr; /// use tun_rs::DeviceBuilder; /// /// fn main() -> std::io::Result<()> { /// let tun = DeviceBuilder::new() /// .name("my-tun6") /// .mtu(1500) /// .ipv6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 1), 64) /// .build_sync()?; /// Ok(()) /// } /// ```` /// /// Creating an L2 TAP interface (platform-dependent): /// /// ````no_run /// #[cfg(any( /// target_os = "windows", /// all(target_os = "linux", not(target_env = "ohos")), /// target_os = "freebsd", /// target_os = "macos", /// target_os = "openbsd", /// target_os = "netbsd" /// ))] /// use tun_rs::{DeviceBuilder, Layer}; /// /// #[cfg(any( /// target_os = "windows", /// all(target_os = "linux", not(target_env = "ohos")), /// target_os = "freebsd", /// target_os = "macos", /// target_os = "openbsd", /// target_os = "netbsd" /// ))] /// fn main() -> std::io::Result<()> { /// let tap = DeviceBuilder::new() /// .name("my-tap") /// .layer(Layer::L2) /// .mac_addr([0x00, 0x11, 0x22, 0x33, 0x44, 0x55]) /// .mtu(1500) /// .build_sync()?; /// Ok(()) /// } /// ```` #[doc(hidden)] pub struct DeviceBuilderGuard<'a>(&'a mut DeviceBuilder); #[doc(hidden)] impl DeviceBuilderGuard<'_> { /// Sets the device description (effective only on Windows L3 mode). #[cfg(windows)] pub fn description<S: Into<String>>(&mut self, description: S) -> &mut Self { self.0.description = Some(description.into()); self } /// Sets the IPv4 MTU specifically for Windows. #[cfg(windows)] pub fn mtu_v4(&mut self, mtu: u16) -> &mut Self { self.0.mtu = Some(mtu); self } /// Sets the IPv6 MTU specifically for Windows. #[cfg(windows)] pub fn mtu_v6(&mut self, mtu: u16) -> &mut Self { self.0.mtu_v6 = Some(mtu); self } /// Sets the MAC address for the device (effective only in L2 mode). #[cfg(any( target_os = "windows", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "macos", target_os = "netbsd" ))] pub fn mac_addr(&mut self, mac_addr: [u8; 6]) -> &mut Self { self.0.mac_addr = Some(mac_addr); self } /// Sets the device GUID on Windows. /// By default, GUID is chosen by the system at random. #[cfg(windows)] pub fn device_guid(&mut self, device_guid: u128) -> &mut Self { self.0.device_guid = Some(device_guid); self } /// Enables or disables Wintun logging. /// /// By default, logging is disabled. #[cfg(windows)] pub fn wintun_log(&mut self, wintun_log: bool) -> &mut Self { self.0.wintun_log = Some(wintun_log); self } /// Sets the `wintun.dll` file path on Windows. #[cfg(windows)] pub fn wintun_file(&mut self, wintun_file: String) -> &mut Self { self.0.wintun_file = Some(wintun_file); self } /// Sets the ring capacity on Windows. /// This specifies the capacity of the packet ring buffer in bytes. /// By default, the ring capacity is set to `0x20_0000` (2 MB). #[cfg(windows)] pub fn ring_capacity(&mut self, ring_capacity: u32) -> &mut Self { self.0.ring_capacity = Some(ring_capacity); self } /// Sets the routing metric on Windows. #[cfg(windows)] pub fn metric(&mut self, metric: u16) -> &mut Self { self.0.metric = Some(metric); self } /// Whether to call `WintunDeleteDriver` to remove the driver. /// Default: false. /// # Note /// The clean-up work closely depends on whether the destructor can be normally executed #[cfg(windows)] pub fn delete_driver(&mut self, delete_driver: bool) -> &mut Self { self.0.delete_driver = Some(delete_driver); self } /// Sets the transmit queue length on Linux. #[cfg(target_os = "linux")] pub fn tx_queue_len(&mut self, tx_queue_len: u32) -> &mut Self { self.0.tx_queue_len = Some(tx_queue_len); self } /// Enables TUN offloads on Linux. /// After enabling, use `recv_multiple`/`send_multiple` for data transmission. #[cfg(target_os = "linux")] pub fn offload(&mut self, offload: bool) -> &mut Self { self.0.offload = Some(offload); self } /// Enables multi-queue support on Linux. #[cfg(target_os = "linux")] pub fn multi_queue(&mut self, multi_queue: bool) -> &mut Self { self.0.multi_queue = Some(multi_queue); self } /// Enables or disables packet information for the network driver(TUN) /// on macOS, Linux, freebsd, openbsd, netbsd. /// /// This option is disabled by default (`false`). /// # Note /// There is no native way to enable/disable packet information on macOS. /// The elimination of the packet information on macOS according to this setting /// is processed by this library. /// The set value `v` can be retrieved by `ignore_packet_info`, the returned value is `!v`. #[cfg(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub fn packet_information(&mut self, packet_information: bool) -> &mut Self { self.0.packet_information = Some(packet_information); self } /// Available on Layer::L2; /// creates a pair of `feth` devices, with `peer_feth` as the IO interface name. #[cfg(target_os = "macos")] pub fn peer_feth<S: Into<String>>(&mut self, peer_feth: S) -> &mut Self { self.0.peer_feth = Some(peer_feth.into()); self } /// If true (default), the program will automatically add or remove routes on macOS or FreeBSD to provide consistent routing behavior across all platforms. /// If false, the program will not modify or manage routes in any way, allowing the system to handle all routing natively. /// Set this to be false to obtain the platform's default routing behavior. #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub fn associate_route(&mut self, associate_route: bool) -> &mut Self { self.0.associate_route = Some(associate_route); self } /// Only works in TAP mode. /// If true (default), the existing device with the given name will be used if possible. /// If false, an error will be returned if a device with the specified name already exists. #[cfg(any(target_os = "macos", target_os = "windows", target_os = "netbsd"))] pub fn reuse_dev(&mut self, reuse: bool) -> &mut Self { self.0.reuse_dev = Some(reuse); self } /// Only works in TAP mode. /// If true, the `feth` device will be kept after the program exits; /// if false (default), the device will be destroyed automatically. #[cfg(any(target_os = "macos", target_os = "windows"))] pub fn persist(&mut self, persist: bool) -> &mut Self { self.0.persist = Some(persist); self } } /// This is a unified constructor of a device for various platforms. The specification of every API can be found by looking at /// the documentation of the concrete platform. #[derive(Default)] pub struct DeviceBuilder { dev_name: Option<String>, #[cfg(windows)] description: Option<String>, #[cfg(target_os = "macos")] peer_feth: Option<String>, #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] associate_route: Option<bool>, #[cfg(any(target_os = "macos", target_os = "windows", target_os = "netbsd"))] reuse_dev: Option<bool>, #[cfg(any(target_os = "macos", target_os = "windows"))] persist: Option<bool>, enabled: Option<bool>, mtu: Option<u16>, #[cfg(windows)] mtu_v6: Option<u16>, ipv4: Option<IPV4>, ipv6: Option<Vec<(io::Result<Ipv6Addr>, io::Result<u8>)>>, layer: Option<Layer>, #[cfg(any( target_os = "windows", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "macos", target_os = "netbsd" ))] mac_addr: Option<[u8; 6]>, #[cfg(windows)] device_guid: Option<u128>, #[cfg(windows)] wintun_log: Option<bool>, #[cfg(windows)] wintun_file: Option<String>, #[cfg(windows)] ring_capacity: Option<u32>, #[cfg(windows)] metric: Option<u16>, #[cfg(windows)] delete_driver: Option<bool>, /// switch of Enable/Disable packet information for network driver #[cfg(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] packet_information: Option<bool>, #[cfg(target_os = "linux")] tx_queue_len: Option<u32>, /// Enable/Disable TUN offloads. /// After enabling, use `recv_multiple`/`send_multiple` for data transmission. #[cfg(target_os = "linux")] offload: Option<bool>, /// Enable multi queue support #[cfg(target_os = "linux")] multi_queue: Option<bool>, } impl DeviceBuilder { /// Creates a new DeviceBuilder instance with default settings. pub fn new() -> Self { Self::default().enable(true) } /// Sets the device name. pub fn name<S: Into<String>>(mut self, dev_name: S) -> Self { self.dev_name = Some(dev_name.into()); self } /// Sets the device description (effective only on Windows L3 mode). #[cfg(windows)] pub fn description<S: Into<String>>(mut self, description: S) -> Self { self.description = Some(description.into()); self } /// Sets the device MTU (Maximum Transmission Unit). pub fn mtu(mut self, mtu: u16) -> Self { self.mtu = Some(mtu); #[cfg(windows)] { // On Windows, also set the MTU for IPv6. self.mtu_v6 = Some(mtu); } self } /// Sets the IPv4 MTU specifically for Windows. #[cfg(windows)] pub fn mtu_v4(mut self, mtu: u16) -> Self { self.mtu = Some(mtu); self } /// Sets the IPv6 MTU specifically for Windows. #[cfg(windows)] pub fn mtu_v6(mut self, mtu: u16) -> Self { self.mtu_v6 = Some(mtu); self } /// Sets the MAC address for the device (effective only in L2 mode). #[cfg(any( target_os = "windows", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "macos", target_os = "netbsd" ))] pub fn mac_addr(mut self, mac_addr: [u8; 6]) -> Self { self.mac_addr = Some(mac_addr); self } /// Configures the IPv4 address for the device. /// /// - `address`: The IPv4 address of the device. /// - `mask`: The subnet mask or prefix length. /// - `destination`: Optional destination address for point-to-point links. /// # Example /// ``` /// use std::net::Ipv4Addr; /// use tun_rs::DeviceBuilder; /// DeviceBuilder::new().ipv4(Ipv4Addr::new(10, 0, 0, 12), 24, None); /// ``` pub fn ipv4<IPv4: ToIpv4Address, Netmask: ToIpv4Netmask>( mut self, address: IPv4, mask: Netmask, destination: Option<IPv4>, ) -> Self { self.ipv4 = Some((address.ipv4(), mask.prefix(), destination.map(|v| v.ipv4()))); self } /// Configures a single IPv6 address for the device. /// /// - `address`: The IPv6 address. /// - `mask`: The subnet mask or prefix length. /// # Example /// ``` /// use tun_rs::DeviceBuilder; /// DeviceBuilder::new().ipv6("CDCD:910A:2222:5498:8475:1111:3900:2021", 64); /// ``` pub fn ipv6<IPv6: ToIpv6Address, Netmask: ToIpv6Netmask>( mut self, address: IPv6, mask: Netmask, ) -> Self { if let Some(v) = &mut self.ipv6 { v.push((address.ipv6(), mask.prefix())); } else { self.ipv6 = Some(vec![(address.ipv6(), mask.prefix())]); } self } /// Configures multiple IPv6 addresses in batch. /// /// Accepts a slice of (IPv6 address, netmask) tuples. /// # Example /// ```rust /// use tun_rs::DeviceBuilder; /// DeviceBuilder::new().ipv6_tuple(&[ /// ("CDCD:910A:2222:5498:8475:1111:3900:2022", 64), /// ("CDCD:910A:2222:5498:8475:1111:3900:2023", 64), /// ]); /// ``` pub fn ipv6_tuple<IPv6: ToIpv6Address, Netmask: ToIpv6Netmask>( mut self, addrs: &[(IPv6, Netmask)], ) -> Self { if let Some(v) = &mut self.ipv6 { for (address, mask) in addrs { v.push((address.ipv6(), mask.prefix())); } } else { self.ipv6 = Some( addrs .iter() .map(|(ip, mask)| (ip.ipv6(), mask.prefix())) .collect(), ); } self } /// Sets the operating layer (L2 or L3) for the device. /// /// * L2 corresponds to TAP /// * L3 corresponds to TUN pub fn layer(mut self, layer: Layer) -> Self { self.layer = Some(layer); self } /// Sets the device GUID on Windows. /// By default, GUID is chosen by the system at random. #[cfg(windows)] pub fn device_guid(mut self, device_guid: u128) -> Self { self.device_guid = Some(device_guid); self } /// Enables or disables Wintun logging. /// /// By default, logging is disabled. #[cfg(windows)] pub fn wintun_log(mut self, wintun_log: bool) -> Self { self.wintun_log = Some(wintun_log); self } /// Sets the `wintun.dll` file path on Windows. #[cfg(windows)] pub fn wintun_file(mut self, wintun_file: String) -> Self { self.wintun_file = Some(wintun_file); self } /// Sets the ring capacity on Windows. /// This specifies the capacity of the packet ring buffer in bytes. /// By default, the ring capacity is set to `0x20_0000` (2 MB). #[cfg(windows)] pub fn ring_capacity(mut self, ring_capacity: u32) -> Self { self.ring_capacity = Some(ring_capacity); self } /// Sets the routing metric on Windows. #[cfg(windows)] pub fn metric(mut self, metric: u16) -> Self { self.metric = Some(metric); self } /// Whether to call `WintunDeleteDriver` to remove the driver. /// Default: false. /// # Note /// The clean-up work closely depends on whether the destructor can be normally executed #[cfg(windows)] pub fn delete_driver(mut self, delete_driver: bool) -> Self { self.delete_driver = Some(delete_driver); self } /// Sets the transmit queue length on Linux. #[cfg(target_os = "linux")] pub fn tx_queue_len(mut self, tx_queue_len: u32) -> Self { self.tx_queue_len = Some(tx_queue_len); self } /// Enables TUN offloads on Linux. /// After enabling, use `recv_multiple`/`send_multiple` for data transmission. #[cfg(target_os = "linux")] pub fn offload(mut self, offload: bool) -> Self { self.offload = Some(offload); self } /// Enables multi-queue support on Linux. #[cfg(target_os = "linux")] pub fn multi_queue(mut self, multi_queue: bool) -> Self { self.multi_queue = Some(multi_queue); self } /// Enables or disables packet information for the network driver(TUN) /// on macOS, Linux, freebsd, openbsd, netbsd. /// /// This option is disabled by default (`false`). /// # Note /// There is no native way to enable/disable packet information on macOS. /// The elimination of the packet information on macOS according to this setting /// is processed by this library. /// The set value `v` can be retrieved by `ignore_packet_info`, the returned value is `!v`. #[cfg(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub fn packet_information(mut self, packet_information: bool) -> Self { self.packet_information = Some(packet_information); self } /// Available on Layer::L2; /// creates a pair of `feth` devices, with `peer_feth` as the IO interface name. #[cfg(target_os = "macos")] pub fn peer_feth<S: Into<String>>(mut self, peer_feth: S) -> Self { self.peer_feth = Some(peer_feth.into()); self } /// If true (default), the program will automatically add or remove routes on macOS or FreeBSD to provide consistent routing behavior across all platforms. /// If false, the program will not modify or manage routes in any way, allowing the system to handle all routing natively. /// Set this to be false to obtain the platform's default routing behavior. #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] pub fn associate_route(mut self, associate_route: bool) -> Self { self.associate_route = Some(associate_route); self } /// Only works in TAP mode. /// If true (default), the existing device with the given name will be used if possible. /// If false, an error will be returned if a device with the specified name already exists. #[cfg(any(target_os = "macos", target_os = "windows", target_os = "netbsd"))] pub fn reuse_dev(mut self, reuse: bool) -> Self { self.reuse_dev = Some(reuse); self } /// Only works in TAP mode. /// If true, the `feth` device will be kept after the program exits; /// if false (default), the device will be destroyed automatically. #[cfg(any(target_os = "macos", target_os = "windows"))] pub fn persist(mut self, persist: bool) -> Self { self.persist = Some(persist); self } /// Enables or disables the device. /// Defaults to be enabled. pub fn enable(mut self, enable: bool) -> Self { self.enabled = Some(enable); self } /// Keeps the device enable state unchanged. /// /// This method does not explicitly enable or disable the device. /// The existing system state is preserved. pub fn inherit_enable_state(mut self) -> Self { self.enabled = None; self } pub(crate) fn build_config(&mut self) -> DeviceConfig { DeviceConfig { dev_name: self.dev_name.take(), #[cfg(windows)] description: self.description.take(), #[cfg(target_os = "macos")] peer_feth: self.peer_feth.take(), #[cfg(any( target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] associate_route: self.associate_route, #[cfg(any(target_os = "macos", target_os = "windows", target_os = "netbsd"))] reuse_dev: self.reuse_dev, #[cfg(any(target_os = "macos", target_os = "windows"))] persist: self.persist, layer: self.layer.take(), #[cfg(windows)] device_guid: self.device_guid.take(), #[cfg(windows)] wintun_log: self.wintun_log.take(), #[cfg(windows)] wintun_file: self.wintun_file.take(), #[cfg(windows)] ring_capacity: self.ring_capacity.take(), #[cfg(windows)] delete_driver: self.delete_driver.take(), #[cfg(windows)] mac_address: self.mac_addr.map(|v| { use std::fmt::Write; v.iter() .fold(String::with_capacity(v.len() * 2), |mut s, b| { write!(&mut s, "{b:02X}").unwrap(); s }) }), #[cfg(any( target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd" ))] packet_information: self.packet_information.take(), #[cfg(target_os = "linux")] offload: self.offload.take(), #[cfg(target_os = "linux")] multi_queue: self.multi_queue.take(), } } pub(crate) fn config(self, device: &DeviceImpl) -> io::Result<()> { if let Some(mtu) = self.mtu { device.set_mtu(mtu)?; } #[cfg(windows)] if let Some(mtu) = self.mtu_v6 { device.set_mtu_v6(mtu)?; } #[cfg(windows)] if let Some(metric) = self.metric { device.set_metric(metric)?; } #[cfg(target_os = "linux")] if let Some(tx_queue_len) = self.tx_queue_len { device.set_tx_queue_len(tx_queue_len)?; } #[cfg(any( target_os = "linux", target_os = "freebsd", target_os = "macos", target_os = "openbsd", target_os = "netbsd" ))] if let Some(mac_addr) = self.mac_addr { device.set_mac_address(mac_addr)?; } if let Some((address, prefix, destination)) = self.ipv4 { let prefix = prefix?; let address = address?; let destination = destination.transpose()?; device.set_network_address(address, prefix, destination)?; } if let Some(ipv6) = self.ipv6 { for (address, prefix) in ipv6 { let prefix = prefix?; let address = address?; device.add_address_v6(address, prefix)?; } } if let Some(enabled) = self.enabled { device.enabled(enabled)?; } Ok(()) } /// Builds a synchronous device instance and applies all configuration parameters. pub fn build_sync(mut self) -> io::Result<SyncDevice> { let device = DeviceImpl::new(self.build_config())?; self.config(&device)?; Ok(SyncDevice(device)) } /// Builds an asynchronous device instance. /// /// This method is available only when either async_io or async_tokio feature is enabled. /// /// # Note /// Choose one of the two async runtimes; otherwise, a compile error will be incurred if both are enabled. #[cfg(any(feature = "async_io", feature = "async_tokio"))] pub fn build_async(self) -> io::Result<crate::AsyncDevice> { let sync_device = self.build_sync()?; let device = crate::AsyncDevice::new_dev(sync_device.0)?; Ok(device) } /// To conveniently set the platform-specific parameters without breaking the calling chain. /// # Ergonomic /// /// For example: /// ````no_run /// use tun_rs::DeviceBuilder; /// let builder = DeviceBuilder::new().name("tun1"); /// #[cfg(target_os = "macos")] /// let builder = builder.associate_route(false); /// #[cfg(windows)] /// let builder = builder.wintun_log(false); /// let dev = builder.build_sync().unwrap(); /// ```` /// This is tedious and breaks the calling chain. /// /// With `with`, we can just set platform-specific parameters as follows without breaking the calling chain: /// ````no_run /// use tun_rs::DeviceBuilder; /// let dev = DeviceBuilder::new().name("tun1").with(|opt|{ /// #[cfg(windows)] /// opt.wintun_log(false); /// #[cfg(target_os = "macos")] /// opt.associate_route(false).packet_information(false); /// }).build_sync().unwrap(); /// ```` pub fn with<F: FnMut(&mut DeviceBuilderGuard)>(mut self, mut f: F) -> Self { let mut borrow = DeviceBuilderGuard(&mut self); f(&mut borrow); self } } /// Trait for converting various types into an IPv4 address. pub trait ToIpv4Address { /// Attempts to convert the implementing type into an `Ipv4Addr`. /// Returns the IPv4 address on success or an error on failure. fn ipv4(&self) -> io::Result<Ipv4Addr>; } impl ToIpv4Address for Ipv4Addr { fn ipv4(&self) -> io::Result<Ipv4Addr> { Ok(*self) } } impl ToIpv4Address for IpAddr { fn ipv4(&self) -> io::Result<Ipv4Addr> { match self { IpAddr::V4(ip) => Ok(*ip), IpAddr::V6(_) => Err(io::Error::new( io::ErrorKind::InvalidData, "invalid address", )), } } } impl ToIpv4Address for String { fn ipv4(&self) -> io::Result<Ipv4Addr> { self.as_str().ipv4() } } impl ToIpv4Address for &str { fn ipv4(&self) -> io::Result<Ipv4Addr> { match Ipv4Addr::from_str(self) { Ok(ip) => Ok(ip), Err(_e) => Err(io::Error::new( io::ErrorKind::InvalidData, "invalid IPv4 str", )), } } } /// Trait for converting various types into an IPv6 address. pub trait ToIpv6Address { /// Attempts to convert the implementing type into an `Ipv6Addr`. /// Returns the IPv6 address on success or an error on failure. fn ipv6(&self) -> io::Result<Ipv6Addr>; } impl ToIpv6Address for Ipv6Addr { fn ipv6(&self) -> io::Result<Ipv6Addr> { Ok(*self) } } impl ToIpv6Address for IpAddr { fn ipv6(&self) -> io::Result<Ipv6Addr> { match self { IpAddr::V4(_) => Err(io::Error::new( io::ErrorKind::InvalidData, "invalid address", )), IpAddr::V6(ip) => Ok(*ip), } } } impl ToIpv6Address for String { fn ipv6(&self) -> io::Result<Ipv6Addr> { self.as_str().ipv6() } } impl ToIpv6Address for &str { fn ipv6(&self) -> io::Result<Ipv6Addr> { match Ipv6Addr::from_str(self) { Ok(ip) => Ok(ip), Err(_e) => Err(io::Error::new( io::ErrorKind::InvalidData, "invalid IPv6 str", )), } } } /// Trait for converting various types into an IPv4 netmask (prefix length). pub trait ToIpv4Netmask { /// Returns the prefix length (i.e., the number of consecutive 1s in the netmask). fn prefix(&self) -> io::Result<u8>; /// Computes the IPv4 netmask based on the prefix length. fn netmask(&self) -> io::Result<Ipv4Addr> { let ip = u32::MAX .checked_shl(32 - self.prefix()? as u32) .unwrap_or(0); Ok(Ipv4Addr::from(ip)) } } impl ToIpv4Netmask for u8 { fn prefix(&self) -> io::Result<u8> { if *self > 32 { return Err(io::Error::new( io::ErrorKind::InvalidData, "invalid IP prefix length", )); } Ok(*self) } } impl ToIpv4Netmask for Ipv4Addr { fn prefix(&self) -> io::Result<u8> { let ip = u32::from_be_bytes(self.octets()); // Validate that the netmask is contiguous (all 1s followed by all 0s). if ip.leading_ones() != ip.count_ones() { return Err(io::Error::new( io::ErrorKind::InvalidData, "invalid netmask", )); } Ok(ip.leading_ones() as u8) } } impl ToIpv4Netmask for String { fn prefix(&self) -> io::Result<u8> { ToIpv4Netmask::prefix(&self.as_str()) } } impl ToIpv4Netmask for &str { fn prefix(&self) -> io::Result<u8> { match Ipv4Addr::from_str(self) { Ok(ip) => ip.prefix(), Err(_e) => Err(io::Error::new( io::ErrorKind::InvalidData, "invalid netmask str", )), } } } /// Trait for converting various types into an IPv6 netmask (prefix length). pub trait ToIpv6Netmask { /// Returns the prefix length. fn prefix(&self) -> io::Result<u8>; /// Computes the IPv6 netmask based on the prefix length.
rust
Apache-2.0
c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7
2026-01-04T20:19:01.665942Z
true
tun-rs/tun-rs
https://github.com/tun-rs/tun-rs/blob/c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7/src/lib.rs
src/lib.rs
#![cfg_attr(docsrs, feature(doc_cfg))] /*! # Example: ```no_run use tun_rs::DeviceBuilder; let dev = DeviceBuilder::new() .name("utun7") .ipv4("10.0.0.12", 24, None) .ipv6("CDCD:910A:2222:5498:8475:1111:3900:2021", 64) .mtu(1400) .build_sync() .unwrap(); let mut buf = [0;65535]; loop { let len = dev.recv(&mut buf).unwrap(); println!("buf= {:?}",&buf[..len]); } ``` # Example IOS/Android/... : ```no_run #[cfg(unix)] { use tun_rs::SyncDevice; // use PacketTunnelProvider/VpnService create tun fd let fd = 7799; let dev = unsafe{SyncDevice::from_fd(fd).unwrap()}; let mut buf = [0;65535]; loop { let len = dev.recv(&mut buf).unwrap(); println!("buf= {:?}",&buf[..len]); } } ``` */ #[cfg(any( target_os = "windows", all(target_os = "linux", not(target_env = "ohos")), target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", ))] pub use crate::builder::*; pub use crate::platform::*; #[cfg_attr(docsrs, doc(cfg(any(feature = "async_io", feature = "async_tokio"))))] #[cfg(any(feature = "async_io", feature = "async_tokio"))] mod async_device; #[cfg_attr(docsrs, doc(cfg(any(feature = "async_io", feature = "async_tokio"))))] #[cfg(any(feature = "async_io", feature = "async_tokio"))] pub use async_device::*; #[cfg(any( target_os = "windows", all(target_os = "linux", not(target_env = "ohos")), target_os = "macos", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", ))] mod builder; mod platform; /// Length of the protocol info header pub const PACKET_INFORMATION_LENGTH: usize = 4;
rust
Apache-2.0
c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7
2026-01-04T20:19:01.665942Z
false
tun-rs/tun-rs
https://github.com/tun-rs/tun-rs/blob/c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7/src/async_device/mod.rs
src/async_device/mod.rs
#[cfg(unix)] pub(crate) mod unix; #[cfg(all(unix, not(target_os = "macos")))] pub use unix::AsyncDevice; #[cfg(target_os = "macos")] mod macos; #[cfg(target_os = "macos")] pub use macos::AsyncDevice; #[cfg(windows)] mod windows; #[cfg(windows)] pub use windows::AsyncDevice; #[cfg(all( any(feature = "async_io", feature = "async_tokio"), feature = "async_framed" ))] #[cfg_attr( docsrs, doc(cfg(all( any(feature = "async_io", feature = "async_tokio"), feature = "async_framed" ))) )] pub mod async_framed; #[cfg(all(feature = "async_tokio", feature = "async_io", not(doc)))] compile_error! {"More than one asynchronous runtime is simultaneously specified in features"} #[cfg(unix)] pub struct BorrowedAsyncDevice<'dev> { dev: AsyncDevice, _phantom: std::marker::PhantomData<&'dev AsyncDevice>, } #[cfg(unix)] impl std::ops::Deref for BorrowedAsyncDevice<'_> { type Target = AsyncDevice; fn deref(&self) -> &Self::Target { &self.dev } } #[cfg(unix)] impl BorrowedAsyncDevice<'_> { /// # Safety /// The fd passed in must be a valid, open file descriptor. /// Unlike [`AsyncDevice::from_fd`], this function does **not** take ownership of `fd`, /// and therefore will not close it when dropped. /// The caller is responsible for ensuring the lifetime and eventual closure of `fd`. pub unsafe fn borrow_raw(fd: std::os::fd::RawFd) -> std::io::Result<Self> { #[allow(unused_unsafe)] unsafe { Ok(Self { dev: AsyncDevice::borrow_raw(fd)?, _phantom: std::marker::PhantomData, }) } } }
rust
Apache-2.0
c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7
2026-01-04T20:19:01.665942Z
false
tun-rs/tun-rs
https://github.com/tun-rs/tun-rs/blob/c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7/src/async_device/async_framed.rs
src/async_device/async_framed.rs
use std::borrow::Borrow; use std::io; use std::pin::Pin; use std::task::{ready, Context, Poll}; use bytes::{BufMut, Bytes, BytesMut}; use futures::Sink; use futures_core::Stream; #[cfg(all(target_os = "linux", not(target_env = "ohos")))] use crate::platform::offload::VirtioNetHdr; use crate::AsyncDevice; #[cfg(all(target_os = "linux", not(target_env = "ohos")))] use crate::{GROTable, IDEAL_BATCH_SIZE, VIRTIO_NET_HDR_LEN}; pub trait Decoder { /// The type of decoded frames. type Item; /// The type of unrecoverable frame decoding errors. type Error: From<io::Error>; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error>; fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { match self.decode(buf)? { Some(frame) => Ok(Some(frame)), None => { if buf.is_empty() { Ok(None) } else { Err(io::Error::other("bytes remaining on stream").into()) } } } } } impl<T: Decoder> Decoder for &mut T { type Item = T::Item; type Error = T::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { T::decode(self, src) } } pub trait Encoder<Item> { /// The type of encoding errors. type Error: From<io::Error>; /// Encodes a frame into the buffer provided. fn encode(&mut self, item: Item, dst: &mut BytesMut) -> Result<(), Self::Error>; } impl<T: Encoder<Item>, Item> Encoder<Item> for &mut T { type Error = T::Error; fn encode(&mut self, item: Item, dst: &mut BytesMut) -> Result<(), Self::Error> { T::encode(self, item, dst) } } /// A unified `Stream` and `Sink` interface over an `AsyncDevice`, /// using `Encoder` and `Decoder` traits to frame packets as higher-level messages. /// /// Raw device interfaces (such as TUN/TAP) operate on individual packets, /// but higher-level protocols often work with logical frames. This struct /// provides an abstraction layer that decodes incoming packets into frames, /// and encodes outgoing frames into packet buffers. /// /// On Linux, this struct also supports Generic Segmentation Offload (GSO) for sending /// and Generic Receive Offload (GRO) for receiving, allowing multiple small packets /// to be aggregated or split transparently for performance optimization. /// /// This struct combines both reading and writing into a single object. If separate /// control over read/write is needed, consider calling `.split()` to obtain /// [`DeviceFramedRead`] and [`DeviceFramedWrite`] separately. /// /// You can also create multiple independent framing streams using: /// `DeviceFramed::new(dev.clone(), BytesCodec::new())`, with the device wrapped /// in `Arc<AsyncDevice>`. /// /// A unified async read/write interface for TUN/TAP devices using framed I/O /// /// Combines an async device with a codec to provide `Stream` and `Sink` implementations /// for reading and writing framed packets. /// /// # Examples /// /// ## Basic usage with BytesCodec /// /// ```no_run /// use bytes::BytesMut; /// use futures::{SinkExt, StreamExt}; /// use tun_rs::async_framed::{BytesCodec, DeviceFramed}; /// use tun_rs::DeviceBuilder; /// /// #[tokio::main] /// async fn main() -> std::io::Result<()> { /// // Create a TUN device with IPv4 configuration /// let dev = DeviceBuilder::new() /// .name("tun0") /// .mtu(1500) /// .ipv4("10.0.0.1", "255.255.255.0", None) /// .build_async()?; /// /// // Create a framed device with BytesCodec /// let mut framed = DeviceFramed::new(dev, BytesCodec::new()); /// /// // Send a frame (Replace with real IP message) /// let packet = b"[IP Packet: 10.0.0.1 -> 10.0.0.2] Hello, TUN!"; /// framed.send(BytesMut::from(packet)).await?; /// /// // Receive frames /// while let Some(frame) = framed.next().await { /// match frame { /// Ok(bytes) => println!("Received: {:?}", bytes), /// Err(e) => eprintln!("Error receiving frame: {}", e), /// } /// } /// Ok(()) /// } /// ``` pub struct DeviceFramed<C, T = AsyncDevice> { dev: T, codec: C, r_state: ReadState, w_state: WriteState, } impl<C, T> Unpin for DeviceFramed<C, T> {} impl<C, T> Stream for DeviceFramed<C, T> where T: Borrow<AsyncDevice>, C: Decoder, { type Item = Result<C::Item, C::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let pin = self.get_mut(); DeviceFramedReadInner::new(&pin.dev, &mut pin.codec, &mut pin.r_state).poll_next(cx) } } impl<I, C, T> Sink<I> for DeviceFramed<C, T> where T: Borrow<AsyncDevice>, C: Encoder<I>, { type Error = C::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.w_state).poll_ready(cx) } fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.w_state).start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.w_state).poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.w_state).poll_close(cx) } } impl<C, T> DeviceFramed<C, T> where T: Borrow<AsyncDevice>, { /// Construct from a [`AsyncDevice`] with a specific codec pub fn new(dev: T, codec: C) -> DeviceFramed<C, T> { let buffer_size = compute_buffer_size(&dev); DeviceFramed { r_state: ReadState::new(buffer_size, dev.borrow()), w_state: WriteState::new(buffer_size, dev.borrow()), dev, codec, } } pub fn read_buffer_size(&self) -> usize { self.r_state.read_buffer_size() } pub fn write_buffer_size(&self) -> usize { self.w_state.write_buffer_size() } /// Sets the size of the read buffer in bytes. /// /// Must be at least as large as the MTU to ensure complete packet reception. pub fn set_read_buffer_size(&mut self, read_buffer_size: usize) { self.r_state.set_read_buffer_size(read_buffer_size); } /// Sets the size of the write buffer in bytes. /// /// On Linux, if GSO (Generic Segmentation Offload) is enabled, this setting is ignored, /// and the send buffer size is fixed to a larger value to accommodate large TCP segments. /// /// If the current buffer size is already greater than or equal to the requested size, /// this call has no effect. /// /// # Parameters /// - `write_buffer_size`: Desired size in bytes for the write buffer. pub fn set_write_buffer_size(&mut self, write_buffer_size: usize) { self.w_state.set_write_buffer_size(write_buffer_size); } /// Returns a reference to the read buffer. pub fn read_buffer(&self) -> &BytesMut { &self.r_state.rd } /// Returns a mutable reference to the read buffer. pub fn read_buffer_mut(&mut self) -> &mut BytesMut { &mut self.r_state.rd } /// Consumes the `Framed`, returning its underlying I/O stream. pub fn into_inner(self) -> T { self.dev } } impl<C, T> DeviceFramed<C, T> where T: Borrow<AsyncDevice> + Clone, C: Clone, { /// Split the framed device to read-half and write-half /// /// # Example /// ``` /// use std::net::Ipv4Addr; /// use std::sync::Arc; /// use tun_rs::{ /// async_framed::{BytesCodec, DeviceFramed}, /// DeviceBuilder, /// }; /// let dev = Arc::new( /// DeviceBuilder::new() /// .ipv4(Ipv4Addr::new(10, 0, 0, 21), 24, None) /// .build_async()?, /// ); /// let (r, w) = DeviceFramed::new(dev, BytesCodec::new()).split(); /// ``` pub fn split(self) -> (DeviceFramedRead<C, T>, DeviceFramedWrite<C, T>) { let dev = self.dev; let codec = self.codec; ( DeviceFramedRead::new(dev.clone(), codec.clone()), DeviceFramedWrite::new(dev, codec), ) } } /// A `Stream`-only abstraction over an `AsyncDevice`, using a `Decoder` to /// /// # Examples /// /// ```no_run /// use futures::StreamExt; /// use tun_rs::async_framed::{BytesCodec, DeviceFramedRead}; /// use tun_rs::DeviceBuilder; /// /// #[tokio::main] /// async fn main() -> std::io::Result<()> { /// // Create a TUN device with IPv4 configuration /// let dev = DeviceBuilder::new() /// .name("tun0") /// .mtu(1500) /// .ipv4("10.0.0.1", "255.255.255.0", None) /// .build_async()?; /// /// // Create a read-only framed device /// let mut framed_read = DeviceFramedRead::new(dev, BytesCodec::new()); /// /// // Receive frames /// while let Some(frame) = framed_read.next().await { /// match frame { /// Ok(bytes) => println!("Received: {:?}", bytes), /// Err(e) => eprintln!("Error receiving frame: {}", e), /// } /// } /// Ok(()) /// } /// ``` /// /// extract frames from raw packet input. /// /// This struct provides a read-only framing interface for the underlying device, /// decoupled from writing. It is useful when the reading and writing logic /// need to be handled independently, such as in split or concurrent tasks. /// /// Internally, it maintains a receipt buffer and optional packet splitter /// for GRO (Generic Receive Offload) support on Linux. /// /// See [`DeviceFramed`] for a unified read/write interface. pub struct DeviceFramedRead<C, T = AsyncDevice> { dev: T, codec: C, state: ReadState, } impl<C, T> DeviceFramedRead<C, T> where T: Borrow<AsyncDevice>, { /// Construct from a [`AsyncDevice`] with a specific codec. /// /// The read side of the framed device. /// # Example /// ``` /// use std::net::Ipv4Addr; /// use std::sync::Arc; /// use tun_rs::{ /// async_framed::{BytesCodec, DeviceFramedRead, DeviceFramedWrite}, /// DeviceBuilder, /// }; /// let dev = Arc::new( /// DeviceBuilder::new() /// .ipv4(Ipv4Addr::new(10, 0, 0, 21), 24, None) /// .build_async()?, /// ); /// let mut w = DeviceFramedWrite::new(dev.clone(), BytesCodec::new()); /// let mut r = DeviceFramedRead::new(dev, BytesCodec::new()); /// ``` /// # Note /// An efficient way is to directly use [`DeviceFramed::split`] if the device is cloneable pub fn new(dev: T, codec: C) -> DeviceFramedRead<C, T> { let buffer_size = compute_buffer_size(&dev); DeviceFramedRead { state: ReadState::new(buffer_size, dev.borrow()), dev, codec, } } pub fn read_buffer_size(&self) -> usize { self.state.read_buffer_size() } /// Sets the size of the read buffer in bytes. /// /// Must be at least as large as the MTU to ensure complete packet reception. pub fn set_read_buffer_size(&mut self, read_buffer_size: usize) { self.state.set_read_buffer_size(read_buffer_size); } /// Consumes the `Framed`, returning its underlying I/O stream. pub fn into_inner(self) -> T { self.dev } } impl<C, T> Unpin for DeviceFramedRead<C, T> {} impl<C, T> Stream for DeviceFramedRead<C, T> where T: Borrow<AsyncDevice>, C: Decoder, { type Item = Result<C::Item, C::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let pin = self.get_mut(); DeviceFramedReadInner::new(&pin.dev, &mut pin.codec, &mut pin.state).poll_next(cx) } } /// A `Sink`-only abstraction over an `AsyncDevice`, using an `Encoder` to /// /// # Examples /// /// ```no_run /// use bytes::BytesMut; /// use futures::SinkExt; /// use tun_rs::async_framed::{BytesCodec, DeviceFramedWrite}; /// use tun_rs::DeviceBuilder; /// /// #[tokio::main] /// async fn main() -> std::io::Result<()> { /// // Create a TUN device with IPv4 configuration /// let dev = DeviceBuilder::new() /// .name("tun0") /// .mtu(1500) /// .ipv4("10.0.0.1", "255.255.255.0", None) /// .build_async()?; /// /// // Create a write-only framed device /// let mut framed_write = DeviceFramedWrite::new(dev, BytesCodec::new()); /// /// // Send a frame (Replace with real IP message) /// let packet = b"[IP Packet: 10.0.0.1 -> 10.0.0.2] Hello, TUN!"; /// framed_write.send(BytesMut::from(packet)).await?; /// /// Ok(()) /// } /// ``` /// /// serialize outbound frames into raw packets. /// /// This struct provides a write-only framing interface for the underlying device, /// allowing decoupled and concurrent handling of outbound data. It is especially /// useful in async contexts where reads and writes occur in different tasks. /// /// Internally, it manages a send buffer and optional packet aggregator /// for GSO (Generic Segmentation Offload) support on Linux. /// /// See [`DeviceFramed`] for a unified read/write interface. pub struct DeviceFramedWrite<C, T = AsyncDevice> { dev: T, codec: C, state: WriteState, } impl<C, T> DeviceFramedWrite<C, T> where T: Borrow<AsyncDevice>, { /// Construct from a [`AsyncDevice`] with a specific codec. /// /// The write side of the framed device. /// # Example /// ``` /// use std::net::Ipv4Addr; /// use std::sync::Arc; /// use tun_rs::{ /// async_framed::{BytesCodec, DeviceFramedRead, DeviceFramedWrite}, /// DeviceBuilder, /// }; /// let dev = Arc::new( /// DeviceBuilder::new() /// .ipv4(Ipv4Addr::new(10, 0, 0, 21), 24, None) /// .build_async()?, /// ); /// let mut w = DeviceFramedWrite::new(dev.clone(), BytesCodec::new()); /// let mut r = DeviceFramedRead::new(dev, BytesCodec::new()); /// ``` /// # Note /// An efficient way is to directly use [`DeviceFramed::split`] if the device is cloneable pub fn new(dev: T, codec: C) -> DeviceFramedWrite<C, T> { let buffer_size = compute_buffer_size(&dev); DeviceFramedWrite { state: WriteState::new(buffer_size, dev.borrow()), dev, codec, } } pub fn write_buffer_size(&self) -> usize { self.state.send_buffer_size } /// Sets the size of the write buffer in bytes. /// /// On Linux, if GSO (Generic Segmentation Offload) is enabled, this setting is ignored, /// and the send buffer size is fixed to a larger value to accommodate large TCP segments. /// /// If the current buffer size is already greater than or equal to the requested size, /// this call has no effect. /// /// # Parameters /// - `write_buffer_size`: Desired size in bytes for the write buffer. pub fn set_write_buffer_size(&mut self, write_buffer_size: usize) { self.state.set_write_buffer_size(write_buffer_size); } /// Consumes the `Framed`, returning its underlying I/O stream. pub fn into_inner(self) -> T { self.dev } } impl<C, T> Unpin for DeviceFramedWrite<C, T> {} impl<I, C, T> Sink<I> for DeviceFramedWrite<C, T> where T: Borrow<AsyncDevice>, C: Encoder<I>, { type Error = C::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.state).poll_ready(cx) } fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.state).start_send(item) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.state).poll_flush(cx) } fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { let pin = self.get_mut(); DeviceFramedWriteInner::new(&pin.dev, &mut pin.codec, &mut pin.state).poll_close(cx) } } fn compute_buffer_size<T: Borrow<AsyncDevice>>(_dev: &T) -> usize { #[cfg(any( target_os = "windows", all(target_os = "linux", not(target_env = "ohos")), target_os = "macos", target_os = "freebsd", target_os = "openbsd", ))] let mtu = _dev.borrow().mtu().map(|m| m as usize).unwrap_or(4096); #[cfg(not(any( target_os = "windows", all(target_os = "linux", not(target_env = "ohos")), target_os = "macos", target_os = "freebsd", target_os = "openbsd", )))] let mtu = 4096usize; #[cfg(windows)] { let mtu_v6 = _dev.borrow().mtu_v6().map(|m| m as usize).unwrap_or(4096); mtu.max(mtu_v6) } #[cfg(not(windows))] mtu } struct ReadState { recv_buffer_size: usize, rd: BytesMut, #[cfg(all(target_os = "linux", not(target_env = "ohos")))] packet_splitter: Option<PacketSplitter>, } impl ReadState { pub(crate) fn new(recv_buffer_size: usize, _device: &AsyncDevice) -> ReadState { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] let packet_splitter = if _device.tcp_gso() { Some(PacketSplitter::new(recv_buffer_size)) } else { None }; ReadState { recv_buffer_size, rd: BytesMut::with_capacity(recv_buffer_size), #[cfg(all(target_os = "linux", not(target_env = "ohos")))] packet_splitter, } } pub(crate) fn read_buffer_size(&self) -> usize { self.recv_buffer_size } pub(crate) fn set_read_buffer_size(&mut self, read_buffer_size: usize) { self.recv_buffer_size = read_buffer_size; #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_splitter) = &mut self.packet_splitter { packet_splitter.set_recv_buffer_size(read_buffer_size); } } } struct WriteState { send_buffer_size: usize, wr: BytesMut, #[cfg(all(target_os = "linux", not(target_env = "ohos")))] packet_arena: Option<PacketArena>, } impl WriteState { pub(crate) fn new(send_buffer_size: usize, _device: &AsyncDevice) -> WriteState { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] let packet_arena = if _device.tcp_gso() { Some(PacketArena::new()) } else { None }; WriteState { send_buffer_size, wr: BytesMut::new(), #[cfg(all(target_os = "linux", not(target_env = "ohos")))] packet_arena, } } pub(crate) fn write_buffer_size(&self) -> usize { self.send_buffer_size } pub(crate) fn set_write_buffer_size(&mut self, write_buffer_size: usize) { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if self.packet_arena.is_some() { // When GSO is enabled, send_buffer_size is no longer controlled by this parameter. return; } if self.send_buffer_size >= write_buffer_size { return; } self.send_buffer_size = write_buffer_size; } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] pub struct BytesCodec(()); impl BytesCodec { /// Creates a new `BytesCodec` for shipping around raw bytes. pub fn new() -> BytesCodec { BytesCodec(()) } } impl Decoder for BytesCodec { type Item = BytesMut; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<BytesMut>, io::Error> { if !buf.is_empty() { let rs = buf.clone(); buf.clear(); Ok(Some(rs)) } else { Ok(None) } } } impl Encoder<Bytes> for BytesCodec { type Error = io::Error; fn encode(&mut self, data: Bytes, buf: &mut BytesMut) -> Result<(), io::Error> { buf.reserve(data.len()); buf.put(data); Ok(()) } } impl Encoder<BytesMut> for BytesCodec { type Error = io::Error; fn encode(&mut self, data: BytesMut, buf: &mut BytesMut) -> Result<(), io::Error> { buf.reserve(data.len()); buf.put(data); Ok(()) } } #[cfg(all(target_os = "linux", not(target_env = "ohos")))] struct PacketSplitter { bufs: Vec<BytesMut>, sizes: Vec<usize>, recv_index: usize, recv_num: usize, recv_buffer_size: usize, } #[cfg(all(target_os = "linux", not(target_env = "ohos")))] impl PacketSplitter { fn new(recv_buffer_size: usize) -> PacketSplitter { let bufs = vec![BytesMut::zeroed(recv_buffer_size); IDEAL_BATCH_SIZE]; let sizes = vec![0usize; IDEAL_BATCH_SIZE]; Self { bufs, sizes, recv_index: 0, recv_num: 0, recv_buffer_size, } } fn handle(&mut self, dev: &AsyncDevice, input: &mut [u8]) -> io::Result<()> { if input.len() <= VIRTIO_NET_HDR_LEN { Err(io::Error::other(format!( "length of packet ({}) <= VIRTIO_NET_HDR_LEN ({VIRTIO_NET_HDR_LEN})", input.len(), )))? } for buf in &mut self.bufs { buf.resize(self.recv_buffer_size, 0); } let hdr = VirtioNetHdr::decode(&input[..VIRTIO_NET_HDR_LEN])?; let num = dev.handle_virtio_read( hdr, &mut input[VIRTIO_NET_HDR_LEN..], &mut self.bufs, &mut self.sizes, 0, )?; for i in 0..num { self.bufs[i].truncate(self.sizes[i]); } self.recv_num = num; self.recv_index = 0; Ok(()) } fn next(&mut self) -> Option<&mut BytesMut> { if self.recv_index >= self.recv_num { None } else { let buf = &mut self.bufs[self.recv_index]; self.recv_index += 1; Some(buf) } } fn set_recv_buffer_size(&mut self, recv_buffer_size: usize) { self.recv_buffer_size = recv_buffer_size; } } #[cfg(all(target_os = "linux", not(target_env = "ohos")))] struct PacketArena { gro_table: GROTable, offset: usize, bufs: Vec<BytesMut>, send_index: usize, } #[cfg(all(target_os = "linux", not(target_env = "ohos")))] impl PacketArena { fn new() -> PacketArena { Self { gro_table: Default::default(), offset: 0, bufs: Vec::with_capacity(IDEAL_BATCH_SIZE), send_index: 0, } } fn get(&mut self) -> &mut BytesMut { if self.offset < self.bufs.len() { let buf = &mut self.bufs[self.offset]; self.offset += 1; buf.clear(); buf.reserve(VIRTIO_NET_HDR_LEN + 65536); return buf; } assert_eq!(self.offset, self.bufs.len()); self.bufs .push(BytesMut::with_capacity(VIRTIO_NET_HDR_LEN + 65536)); let idx = self.offset; self.offset += 1; &mut self.bufs[idx] } fn handle(&mut self, dev: &AsyncDevice) -> io::Result<()> { if self.offset == 0 { return Ok(()); } if !self.gro_table.to_write.is_empty() { return Ok(()); } crate::platform::offload::handle_gro( &mut self.bufs[..self.offset], VIRTIO_NET_HDR_LEN, &mut self.gro_table.tcp_gro_table, &mut self.gro_table.udp_gro_table, dev.udp_gso, &mut self.gro_table.to_write, ) } fn poll_send_bufs(&mut self, cx: &mut Context<'_>, dev: &AsyncDevice) -> Poll<io::Result<()>> { if self.offset == 0 { return Poll::Ready(Ok(())); } let gro_table = &mut self.gro_table; let bufs = &self.bufs[..self.offset]; for buf_idx in &gro_table.to_write[self.send_index..] { let rs = dev.poll_send(cx, &bufs[*buf_idx]); match rs { Poll::Ready(Ok(_)) => { self.send_index += 1; } Poll::Ready(Err(e)) => { self.send_index += 1; if self.send_index >= gro_table.to_write.len() { self.reset(); } return Poll::Ready(Err(e)); } Poll::Pending => { return Poll::Pending; } } } self.reset(); Poll::Ready(Ok(())) } fn reset(&mut self) { self.gro_table.reset(); for buf in self.bufs[..self.offset].iter_mut() { buf.clear(); } self.offset = 0; self.send_index = 0; } fn is_idle(&self) -> bool { IDEAL_BATCH_SIZE > self.offset && self.gro_table.to_write.is_empty() } } struct DeviceFramedReadInner<'a, C, T = AsyncDevice> { dev: &'a T, codec: &'a mut C, state: &'a mut ReadState, } impl<'a, C, T> DeviceFramedReadInner<'a, C, T> where T: Borrow<AsyncDevice>, C: Decoder, { fn new( dev: &'a T, codec: &'a mut C, state: &'a mut ReadState, ) -> DeviceFramedReadInner<'a, C, T> { DeviceFramedReadInner { dev, codec, state } } fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Result<C::Item, C::Error>>> { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_splitter) = &mut self.state.packet_splitter { if let Some(buf) = packet_splitter.next() { if let Some(frame) = self.codec.decode_eof(buf)? { return Poll::Ready(Some(Ok(frame))); } } } self.state.rd.clear(); #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if self.state.packet_splitter.is_some() { self.state.rd.reserve(VIRTIO_NET_HDR_LEN + 65536); } self.state.rd.reserve(self.state.recv_buffer_size); let buf = unsafe { &mut *(self.state.rd.chunk_mut() as *mut _ as *mut [u8]) }; let len = ready!(self.dev.borrow().poll_recv(cx, buf))?; unsafe { self.state.rd.advance_mut(len) }; #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_splitter) = &mut self.state.packet_splitter { packet_splitter.handle(self.dev.borrow(), &mut self.state.rd)?; if let Some(buf) = packet_splitter.next() { if let Some(frame) = self.codec.decode_eof(buf)? { return Poll::Ready(Some(Ok(frame))); } } return Poll::Ready(None); } if let Some(frame) = self.codec.decode_eof(&mut self.state.rd)? { return Poll::Ready(Some(Ok(frame))); } Poll::Ready(None) } } struct DeviceFramedWriteInner<'a, C, T = AsyncDevice> { dev: &'a T, codec: &'a mut C, state: &'a mut WriteState, } impl<'a, C, T> DeviceFramedWriteInner<'a, C, T> where T: Borrow<AsyncDevice>, { fn new( dev: &'a T, codec: &'a mut C, state: &'a mut WriteState, ) -> DeviceFramedWriteInner<'a, C, T> { DeviceFramedWriteInner { dev, codec, state } } fn poll_ready<I>(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), C::Error>> where C: Encoder<I>, { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_arena) = &self.state.packet_arena { if packet_arena.is_idle() { return Poll::Ready(Ok(())); } } ready!(self.poll_flush(cx))?; Poll::Ready(Ok(())) } fn start_send<I>(&mut self, item: I) -> Result<(), C::Error> where C: Encoder<I>, { #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_arena) = &mut self.state.packet_arena { let buf = packet_arena.get(); buf.resize(VIRTIO_NET_HDR_LEN, 0); self.codec.encode(item, buf)?; return Ok(()); } let buf = &mut self.state.wr; buf.clear(); buf.reserve(self.state.send_buffer_size); self.codec.encode(item, buf)?; Ok(()) } fn poll_flush<I>(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), C::Error>> where C: Encoder<I>, { let dev = self.dev.borrow(); #[cfg(all(target_os = "linux", not(target_env = "ohos")))] if let Some(packet_arena) = &mut self.state.packet_arena { packet_arena.handle(dev)?; ready!(packet_arena.poll_send_bufs(cx, dev))?; return Poll::Ready(Ok(())); } // On non-Linux systems or when GSO is disabled on Linux, `wr` will contain at most one element if !self.state.wr.is_empty() { let rs = ready!(dev.poll_send(cx, &self.state.wr)); self.state.wr.clear(); rs?; } Poll::Ready(Ok(())) } fn poll_close<I>(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), C::Error>> where C: Encoder<I>, { ready!(self.poll_flush(cx))?; Poll::Ready(Ok(())) } }
rust
Apache-2.0
c8e1cd8eb96adf915f0ae95e7c502e0f9ffd91a7
2026-01-04T20:19:01.665942Z
false