lang
stringclasses
3 values
file_path
stringlengths
5
150
repo_name
stringlengths
6
110
commit
stringlengths
40
40
file_code
stringlengths
1.52k
18.9k
prefix
stringlengths
82
16.5k
suffix
stringlengths
0
15.1k
middle
stringlengths
121
8.18k
strategy
stringclasses
8 values
context_items
listlengths
0
100
Rust
lib_gbemulation/src/cpu/instructions/cb_instructions.rs
p4ddy1/gbemulator
1fed41d25fbbfb3e73c616612b5ccf338f6fed39
use crate::cpu::cpu::Cpu; use crate::cpu::instructions::{ functions, read_hl_addr, write_hl_addr, ExecutionType, Instruction, }; use crate::memory::mmu::{Mmu, Opcode}; use crate::util::binary::{reset_bit_in_byte, set_bit_in_byte}; macro_rules! bit { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "BIT $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { functions::check_bit(cpu, read_by_opcode(op_code, cpu), $bit); ExecutionType::None }, }) }; } macro_rules! bit_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 12, clock_cycles_condition: None, description: "BIT $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { functions::check_bit(cpu, read_hl_addr(cpu, mmu), $bit); ExecutionType::None }, }) }; } macro_rules! res { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RES $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let result = reset_bit_in_byte(read_by_opcode(op_code, cpu), $bit); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }) }; } macro_rules! res_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RES $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = reset_bit_in_byte(read_hl_addr(cpu, mmu), $bit); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }) }; } macro_rules! set { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SET $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let result = set_bit_in_byte(read_by_opcode(op_code, cpu), $bit); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }) }; } macro_rules! set_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SET $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = set_bit_in_byte(read_hl_addr(cpu, mmu), $bit); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }) }; } pub fn get_instruction(op_code: &u8) -> Option<&Instruction> { match op_code { 0x00..=0x05 | 0x07 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RLC (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_left(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x06 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RLC (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_left(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x08..=0x0D | 0x0F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RRC (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_right(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x0E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RRC (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_right(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x10..=0x15 | 0x17 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RL (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_left_through_carry(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x16 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RL (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_left_through_carry(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x18..=0x1D | 0x1F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RR (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_right_through_carry(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x1E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RR (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_right_through_carry(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x20..=0x25 | 0x27 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SLA (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::sla(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x26 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SLA (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::sla(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x28..=0x2D | 0x2F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SRA (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::sra(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x2E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SRA (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::sra(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x30..=0x35 | 0x37 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SWAP (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::swap_nibbles(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x36 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SWAP (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::swap_nibbles(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x38..=0x3D | 0x3F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SRL (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::srl(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x3E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SRL (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::srl(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x40..=0x45 | 0x47 => bit!(0), 0x46 => bit_hl!(0), 0x48..=0x4D | 0x4F => bit!(1), 0x4E => bit_hl!(1), 0x50..=0x55 | 0x57 => bit!(2), 0x56 => bit_hl!(2), 0x58..=0x5D | 0x5F => bit!(3), 0x5E => bit_hl!(3), 0x60..=0x65 | 0x67 => bit!(4), 0x66 => bit_hl!(4), 0x68..=0x6D | 0x6F => bit!(5), 0x6E => bit_hl!(5), 0x70..=0x75 | 0x77 => bit!(6), 0x76 => bit_hl!(6), 0x78..=0x7D | 0x7F => bit!(7), 0x7E => bit_hl!(7), 0x80..=0x85 | 0x87 => res!(0), 0x86 => res_hl!(0), 0x88..=0x8D | 0x8F => res!(1), 0x8E => res_hl!(1), 0x90..=0x95 | 0x97 => res!(2), 0x96 => res_hl!(2), 0x98..=0x9D | 0x9F => res!(3), 0x9E => res_hl!(3), 0xA0..=0xA5 | 0xA7 => res!(4), 0xA6 => res_hl!(4), 0xA8..=0xAD | 0xAF => res!(5), 0xAE => res_hl!(5), 0xB0..=0xB5 | 0xB7 => res!(6), 0xB6 => res_hl!(6), 0xB8..=0xBD | 0xBF => res!(7), 0xBE => res_hl!(7), 0xC0..=0xC5 | 0xC7 => set!(0), 0xC6 => set_hl!(0), 0xC8..=0xCD | 0xCF => set!(1), 0xCE => set_hl!(1), 0xD0..=0xD5 | 0xD7 => set!(2), 0xD6 => set_hl!(2), 0xD8..=0xDD | 0xDF => set!(3), 0xDE => set_hl!(3), 0xE0..=0xE5 | 0xE7 => set!(4), 0xE6 => set_hl!(4), 0xE8..=0xED | 0xEF => set!(5), 0xEE => set_hl!(5), 0xF0..=0xF5 | 0xF7 => set!(6), 0xF6 => set_hl!(6), 0xF8..=0xFD | 0xFF => set!(7), 0xFE => set_hl!(7), _ => None, } } fn read_by_opcode(op_code: &Opcode, cpu: &Cpu) -> u8 { match get_lower_nibble_of_opcode(op_code) { 0x00 | 0x80 => cpu.registers.b, 0x10 | 0x90 => cpu.registers.c, 0x20 | 0xA0 => cpu.registers.d, 0x30 | 0xB0 => cpu.registers.e, 0x40 | 0xC0 => cpu.registers.h, 0x50 | 0xD0 => cpu.registers.l, 0x70 | 0xF0 => cpu.registers.a, _ => panic!("Unknown register"), } } fn write_by_opcode(op_code: &Opcode, value: u8, cpu: &mut Cpu) { match get_lower_nibble_of_opcode(op_code) { 0x00 | 0x80 => cpu.registers.b = value, 0x10 | 0x90 => cpu.registers.c = value, 0x20 | 0xA0 => cpu.registers.d = value, 0x30 | 0xB0 => cpu.registers.e = value, 0x40 | 0xC0 => cpu.registers.h = value, 0x50 | 0xD0 => cpu.registers.l = value, 0x70 | 0xF0 => cpu.registers.a = value, _ => panic!("Unknown register"), } } fn get_lower_nibble_of_opcode(op_code: &Opcode) -> u8 { let op_val = match op_code { Opcode::CB(value) => value, _ => panic!("No CB Opcode"), }; op_val << 4 }
use crate::cpu::cpu::Cpu; use crate::cpu::instructions::{ functions, read_hl_addr, write_hl_addr, ExecutionType, Instruction, }; use crate::memory::mmu::{Mmu, Opcode}; use crate::util::binary::{reset_bit_in_byte, set_bit_in_byte}; macro_rules! bit { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "BIT $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { functions::check_bit(cpu, read_by_opcode(op_code, cpu), $bit); ExecutionType::None }, }) }; } macro_rules! bit_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 12, clock_cycles_condition: None, description: "BIT $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { functions::check_bit(cpu, read_hl_addr(cpu, mmu), $bit); ExecutionType::None }, }) }; } macro_rules! res { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RES $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let result = reset_bit_in_byte(read_by_opcode(op_code, cpu), $bit); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }) }; } macro_rules! res_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RES $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = reset_bit_in_byte(read_hl_addr(cpu, mmu), $bit); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }) }; } macro_rules! set { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SET $bit,(B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_
pcode| { let result = set_bit_in_byte(read_hl_addr(cpu, mmu), $bit); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }) }; } pub fn get_instruction(op_code: &u8) -> Option<&Instruction> { match op_code { 0x00..=0x05 | 0x07 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RLC (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_left(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x06 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RLC (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_left(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x08..=0x0D | 0x0F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RRC (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_right(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x0E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RRC (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_right(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x10..=0x15 | 0x17 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RL (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_left_through_carry(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x16 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RL (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_left_through_carry(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x18..=0x1D | 0x1F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "RR (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::rotate_right_through_carry(cpu, value, true); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x1E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "RR (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::rotate_right_through_carry(cpu, read_hl_addr(cpu, mmu), true); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x20..=0x25 | 0x27 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SLA (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::sla(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x26 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SLA (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::sla(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x28..=0x2D | 0x2F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SRA (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::sra(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x2E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SRA (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::sra(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x30..=0x35 | 0x37 => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SWAP (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::swap_nibbles(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x36 => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SWAP (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::swap_nibbles(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x38..=0x3D | 0x3F => Some(&Instruction { length: 2, clock_cycles: 8, clock_cycles_condition: None, description: "SRL (B..A)", handler: |cpu: &mut Cpu, _: &mut Mmu, op_code: &Opcode| { let value = read_by_opcode(op_code, cpu); let result = functions::srl(cpu, value); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }), 0x3E => Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SRL (HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &Opcode| { let result = functions::srl(cpu, read_hl_addr(cpu, mmu)); write_hl_addr(result, cpu, mmu); ExecutionType::None }, }), 0x40..=0x45 | 0x47 => bit!(0), 0x46 => bit_hl!(0), 0x48..=0x4D | 0x4F => bit!(1), 0x4E => bit_hl!(1), 0x50..=0x55 | 0x57 => bit!(2), 0x56 => bit_hl!(2), 0x58..=0x5D | 0x5F => bit!(3), 0x5E => bit_hl!(3), 0x60..=0x65 | 0x67 => bit!(4), 0x66 => bit_hl!(4), 0x68..=0x6D | 0x6F => bit!(5), 0x6E => bit_hl!(5), 0x70..=0x75 | 0x77 => bit!(6), 0x76 => bit_hl!(6), 0x78..=0x7D | 0x7F => bit!(7), 0x7E => bit_hl!(7), 0x80..=0x85 | 0x87 => res!(0), 0x86 => res_hl!(0), 0x88..=0x8D | 0x8F => res!(1), 0x8E => res_hl!(1), 0x90..=0x95 | 0x97 => res!(2), 0x96 => res_hl!(2), 0x98..=0x9D | 0x9F => res!(3), 0x9E => res_hl!(3), 0xA0..=0xA5 | 0xA7 => res!(4), 0xA6 => res_hl!(4), 0xA8..=0xAD | 0xAF => res!(5), 0xAE => res_hl!(5), 0xB0..=0xB5 | 0xB7 => res!(6), 0xB6 => res_hl!(6), 0xB8..=0xBD | 0xBF => res!(7), 0xBE => res_hl!(7), 0xC0..=0xC5 | 0xC7 => set!(0), 0xC6 => set_hl!(0), 0xC8..=0xCD | 0xCF => set!(1), 0xCE => set_hl!(1), 0xD0..=0xD5 | 0xD7 => set!(2), 0xD6 => set_hl!(2), 0xD8..=0xDD | 0xDF => set!(3), 0xDE => set_hl!(3), 0xE0..=0xE5 | 0xE7 => set!(4), 0xE6 => set_hl!(4), 0xE8..=0xED | 0xEF => set!(5), 0xEE => set_hl!(5), 0xF0..=0xF5 | 0xF7 => set!(6), 0xF6 => set_hl!(6), 0xF8..=0xFD | 0xFF => set!(7), 0xFE => set_hl!(7), _ => None, } } fn read_by_opcode(op_code: &Opcode, cpu: &Cpu) -> u8 { match get_lower_nibble_of_opcode(op_code) { 0x00 | 0x80 => cpu.registers.b, 0x10 | 0x90 => cpu.registers.c, 0x20 | 0xA0 => cpu.registers.d, 0x30 | 0xB0 => cpu.registers.e, 0x40 | 0xC0 => cpu.registers.h, 0x50 | 0xD0 => cpu.registers.l, 0x70 | 0xF0 => cpu.registers.a, _ => panic!("Unknown register"), } } fn write_by_opcode(op_code: &Opcode, value: u8, cpu: &mut Cpu) { match get_lower_nibble_of_opcode(op_code) { 0x00 | 0x80 => cpu.registers.b = value, 0x10 | 0x90 => cpu.registers.c = value, 0x20 | 0xA0 => cpu.registers.d = value, 0x30 | 0xB0 => cpu.registers.e = value, 0x40 | 0xC0 => cpu.registers.h = value, 0x50 | 0xD0 => cpu.registers.l = value, 0x70 | 0xF0 => cpu.registers.a = value, _ => panic!("Unknown register"), } } fn get_lower_nibble_of_opcode(op_code: &Opcode) -> u8 { let op_val = match op_code { Opcode::CB(value) => value, _ => panic!("No CB Opcode"), }; op_val << 4 }
code: &Opcode| { let result = set_bit_in_byte(read_by_opcode(op_code, cpu), $bit); write_by_opcode(op_code, result, cpu); ExecutionType::None }, }) }; } macro_rules! set_hl { ($bit: expr) => { Some(&Instruction { length: 2, clock_cycles: 16, clock_cycles_condition: None, description: "SET $bit,(HL)", handler: |cpu: &mut Cpu, mmu: &mut Mmu, _: &O
random
[ { "content": "pub fn call(cpu: &mut Cpu, mmu: &mut Mmu) {\n\n //Put address of next instruction onto stack and jump to aa\n\n cpu.registers.sp = cpu.registers.sp.wrapping_sub(2);\n\n mmu.write_word(cpu.registers.sp, cpu.registers.pc + 3);\n\n cpu.registers.pc = bytes_to_word(get_argument(cpu, mmu, 1...
Rust
fhir-bench-orchestrator/src/servers/mod.rs
karlmdavis/fhir-benchmarks
e1af68545f202c40d68fed623891898c78fdbf31
use crate::{ config::AppConfig, sample_data::SampleResource, servers::docker_compose::DockerComposeServerPlugin, AppState, }; use async_trait::async_trait; use eyre::Result; use serde::{Deserialize, Serialize}; use tracing::info; use url::Url; mod docker_compose; #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] pub struct ServerName(pub String); impl ServerName { fn as_str(&self) -> &str { &self.0 } } impl std::fmt::Display for ServerName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl From<&str> for ServerName { fn from(server_name: &str) -> Self { ServerName(server_name.to_owned()) } } #[async_trait] pub trait ServerHandle: Sync { fn plugin(&self) -> &ServerPluginWrapper; fn base_url(&self) -> Url; fn client(&self) -> Result<reqwest::Client>; fn request_builder( &self, client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { request_builder_default(client, method, url) } fn emit_logs(&self) -> Result<String>; fn emit_logs_info(&self) -> Result<()> { info!( "Full docker-compose logs for '{}' server:\n{}", self.plugin().server_name(), self.emit_logs()? ); Ok(()) } async fn expunge_all_content(&self, app_state: &AppState) -> Result<()>; fn shutdown(&self) -> Result<()>; } pub fn client_default() -> Result<reqwest::Client> { let client_builder = reqwest::ClientBuilder::new(); let client_builder = client_builder.danger_accept_invalid_certs(true); Ok(client_builder.build()?) } fn request_builder_default( client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { client.request(method, url) } pub fn request_builder_ibm_fhir( client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { request_builder_default(client, method, url).basic_auth("fhiruser", Some("change-password")) } #[async_trait] pub trait ServerPlugin: Clone { fn server_name(&self) -> &ServerName; async fn launch(&self, app_state: &AppState) -> Result<Box<dyn ServerHandle>>; fn fudge_sample_resource(&self, sample_resource: SampleResource) -> SampleResource { /* * Design thoughts: * * In general, I'm not a fan of "fixing" noncompliant servers: I'd rather let them fail and have * that reflected in their benchmark results. Sometimes, though, I'm MORE interested in seeing * their performance. This is a tricky balance to strike, and so all such hacks need to be * documented in the project's `doc/server-compliance.md` file. */ /* * Most servers are compliant, thankfully, so we provide this default no-op implementation. */ sample_resource } } #[derive(Clone, Debug)] pub enum ServerPluginWrapper { DockerComposeServerPlugin(DockerComposeServerPlugin), } #[async_trait] impl ServerPlugin for ServerPluginWrapper { fn server_name(&self) -> &ServerName { match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.server_name() } } } async fn launch(&self, app_state: &AppState) -> Result<Box<dyn ServerHandle>> { match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.launch(app_state).await } } } } pub fn create_server_plugins(config: &AppConfig) -> Result<Vec<ServerPluginWrapper>> { /* * Design note: Why are these wrapped in Arcs? Great question! Each ServerHandle needs an owned copy of * them and we can't have the trait extend Copy or Clone, as that would make it not object safe. */ Ok(vec![ ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "firely_spark".into(), config .benchmark_dir()? .join("server_builds") .join("firely_spark") .join("docker_compose_firely_spark.sh"), Url::parse("http://localhost:5555/fhir/").expect("Unable to parse URL."), request_builder_default, )), ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "hapi_jpaserver_starter".into(), config .benchmark_dir()? .join("server_builds") .join("hapi_jpaserver_starter") .join("docker_compose_hapi_jpaserver_starter.sh"), Url::parse("http://localhost:8080/fhir/").expect("Unable to parse URL."), request_builder_default, )), ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "ibm_fhir".into(), config .benchmark_dir()? .join("server_builds") .join("ibm_fhir") .join("docker_compose_ibm_fhir.sh"), Url::parse("https://localhost:9443/fhir-server/api/v4/").expect("Unable to parse URL."), request_builder_ibm_fhir, )), ]) }
use crate::{ config::AppConfig, sample_data::SampleResource, servers::docker_compose::DockerComposeServerPlugin, AppState, }; use async_trait::async_trait; use eyre::Result; use serde::{Deserialize, Serialize}; use tracing::info; use url::Url; mod docker_compose; #[derive(Debug, PartialEq, Clone, Deserialize, Serialize)] pub struct ServerName(pub String); impl ServerName { fn as_str(&self) -> &str { &self.0 } } impl std::fmt::Display for ServerName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl From<&str> for ServerName { fn from(server_name: &str) -> Self { ServerName(server_name.to_owned()) } } #[async_trait] pub trait ServerHandle: Sync { fn plugin(&self) -> &ServerPluginWrapper; fn base_url(&self) -> Url; fn client(&self) -> Result<reqwest::Client>; fn request_builder( &self, client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { request_builder_default(client, method, url) } fn emit_logs(&self) -> Result<String>; fn emit_logs_info(&self) -> Result<()> { info!( "Full docker-compose logs for '{}' server:\n{}", self.plugin().server_name(), self.emit_logs()? ); Ok(()) } async fn expunge_all_content(&self, app_state: &AppState) -> Result<()>; fn shutdown(&self) -> Result<()>; } pub fn client_default() -> Result<reqwest::Client> { let client_builder = reqwest::ClientBuilder::new(); let client_builder = client_builder.danger_accept_invalid_certs(true); Ok(client_builder.build()?) } fn request_builder_default( client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { client.request(method, url) } pub fn request_builder_ibm_fhir( client: reqwest::Client, method: http::Method, url: Url, ) -> reqwest::RequestBuilder { request_builder_default(client, method, url).basic_auth("fhiruser", Some("change-password")) } #[async_trait] pub trait ServerPlugin: Clone { fn server_name(&self) -> &ServerName; async fn launch(&self, app_state: &AppState) -> Result<Box<dyn ServerHandle>>; fn fudge_sample_resource(&self, sample_resource: SampleResource) -> SampleResource { /* * Design thoughts: * * In general, I'm not a fan of "fixing" noncompliant servers: I'd rather let them fail and have * that reflected in their benchmark results. Sometimes, though, I'm MORE interested in seeing * their performance. This is a tricky balance to strike, and so all such hacks need to be * documented in the project's `doc/server-compliance.md` file. */ /* * Most servers are compliant, thankfully, so we provide this default no-op implementation. */ sample_resource } } #[derive(Clone, Debug)] pub enum ServerPluginWrapper { DockerComposeServerPlugin(DockerComposeServerPlugin), } #[async_trait] impl ServerPlugin for ServerPluginWrapper { fn server_name(&self) -> &ServerName {
} async fn launch(&self, app_state: &AppState) -> Result<Box<dyn ServerHandle>> { match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.launch(app_state).await } } } } pub fn create_server_plugins(config: &AppConfig) -> Result<Vec<ServerPluginWrapper>> { /* * Design note: Why are these wrapped in Arcs? Great question! Each ServerHandle needs an owned copy of * them and we can't have the trait extend Copy or Clone, as that would make it not object safe. */ Ok(vec![ ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "firely_spark".into(), config .benchmark_dir()? .join("server_builds") .join("firely_spark") .join("docker_compose_firely_spark.sh"), Url::parse("http://localhost:5555/fhir/").expect("Unable to parse URL."), request_builder_default, )), ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "hapi_jpaserver_starter".into(), config .benchmark_dir()? .join("server_builds") .join("hapi_jpaserver_starter") .join("docker_compose_hapi_jpaserver_starter.sh"), Url::parse("http://localhost:8080/fhir/").expect("Unable to parse URL."), request_builder_default, )), ServerPluginWrapper::DockerComposeServerPlugin(DockerComposeServerPlugin::new( "ibm_fhir".into(), config .benchmark_dir()? .join("server_builds") .join("ibm_fhir") .join("docker_compose_ibm_fhir.sh"), Url::parse("https://localhost:9443/fhir-server/api/v4/").expect("Unable to parse URL."), request_builder_ibm_fhir, )), ]) }
match self { ServerPluginWrapper::DockerComposeServerPlugin(server_plugin) => { server_plugin.server_name() } }
if_condition
[ { "content": "/// Converts [Duration] instances to ISO-8601 string values, for use in JSON.\n\n///\n\n/// Parameters:\n\n/// * `duration`: the [Duration] instance to be serialized\n\n/// * `serializer`: the Serde [Serializer] to use\n\n///\n\n/// Returns the [Serializer] result.\n\npub fn serialize<S>(duration:...
Rust
lib.rs
Lesterrry/Ferret-Interface
95026ad1798c992c5952133039a5b7b39c9b114e
extern crate termion; use std::io::{Write, stdout}; use termion::{terminal_size, color, style, raw::IntoRawMode, input::TermRead}; use std::{thread, time}; pub struct Misc; impl Misc { #[allow(dead_code)] fn overwrite(){ let stdout = stdout(); let mut stdout = stdout.lock().into_raw_mode().unwrap(); write!(stdout, "{}", termion::cursor::Goto(1, 1)).unwrap(); let pres = terminal_size().unwrap().0; for _i in 0..pres{ for _j in 0..terminal_size().unwrap().1{ print!(" "); } } write!(stdout, "{}", termion::cursor::Goto(1, 1)).unwrap(); } } #[allow(dead_code)] #[derive(PartialEq, Clone)] enum FerretColor{ Red, Blue, Gray } enum AlertButton{ Right, Left } pub struct Alert; impl Alert { #[allow(dead_code)] fn invoke(message: String, buttons: (String, String), color: FerretColor) -> AlertButton { Alert::draw(message.clone(), buttons.clone(), (false, false), (false, false), color.clone()); let mut set = 0; let stdout = stdout(); let stdout = stdout.into_raw_mode().unwrap(); let mut stdin = termion::async_stdin().keys(); loop { let input = stdin.next(); if let Some(Ok(key)) = input { match key { termion::event::Key::Char('1') | termion::event::Key::Char('Y') | termion::event::Key::Char('y') => { Alert::draw(message.clone(), buttons.clone(), (true, false), (true, false), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Left }, termion::event::Key::Char('2') | termion::event::Key::Char('N') | termion::event::Key::Char('n') => { Alert::draw(message.clone(), buttons.clone(), (false, true), (false, true), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Right }, termion::event::Key::Right => set = 2, termion::event::Key::Left => set = 1, termion::event::Key::Char('\n') | termion::event::Key::Char(' ') => { match set { 1 => { Alert::draw(message.clone(), buttons.clone(), (true, false), (true, false), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Left }, 2 => {Alert::draw(message.clone(), buttons.clone(), (false, true), (false, true), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Right }, 0 | _ => () } }, _ => () } stdout.lock().flush().unwrap(); match set { 1 => Alert::draw(message.clone(), buttons.clone(), (true, false), (false, false), color.clone()), 2 => Alert::draw(message.clone(), buttons.clone(), (false, true), (false, false), color.clone()), 0 | _ => Alert::draw(message.clone(), buttons.clone(), (false, false), (false, false), color.clone()), } } thread::sleep(time::Duration::from_millis(30)); } } fn draw(message: String, buttons: (String, String), selection: (bool, bool), pushing:(bool, bool), color: FerretColor){ if message.len() > 38 || buttons.0.len() > 10 || buttons.1.len() > 10 {panic!("Message is too long")} let offset = (terminal_size().unwrap().0 / 2 - 20, terminal_size().unwrap().1 / 2 - 4); let offset_message = 20 - message.len() / 2; let offset_buttons = (9 - buttons.0.len() / 2, 31 - buttons.1.len() / 2); let mut colors_sel = [0,0]; if selection.0 == true { colors_sel[0] = 1}; if selection.1 == true { colors_sel[0] = 1}; print!("{}{}{}", termion::cursor::Goto(offset.0, offset.1), if color == FerretColor::Red { "\x1b[48;5;88m" } else if color == FerretColor::Gray { "\x1b[48;5;238m" } else {"\x1b[48;5;24m"}, "\x1b[38;5;243m"); for i in 0..8{ match i { 1 => print!("┌─────────────────────────────────────┐" ), 2 => { let mut j = 0; loop{ if j == offset_message { print!("{}{}{}", color::Fg(color::White), message, "\x1b[38;5;243m"); j += message.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 4 => if pushing == (false, false){ print!(" {}┌{}──────────{}┐ {}┌{}──────────{}┐{} ", if selection.0 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.0 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.0 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.1 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, "\x1b[38;5;243m") }else { if pushing.0 == true { print!("{} ┌┬──────────┬┐ ", "\x1b[38;5;243m") } else {print!("{} ┌┬──────────┬┐ ", "\x1b[38;5;243m" )} }, 5 => if pushing == (false, false){ let mut j = 0; loop{ if j == offset_buttons.0 { print!("{}{}{}", color::Fg(color::White), buttons.0, color::Fg(color::LightBlack)); j += buttons.0.len(); } else if j == offset_buttons.1 { print!("{}{}{}", color::Fg(color::White), buttons.1, color::Fg(color::LightBlack)); j += buttons.1.len() - 1; } else {print!(" ")} j += 1; if j > 39 {break;} } }else{ if pushing.1 == true { print!("{} ┌┬──────────┬┐ ", "\x1b[37m") } else {print!("{} ┌┬──────────┬┐ ", "\x1b[37m" )} }, 6 => print!(" {}└{}──────────{}┘ {}└{}──────────{}┘{} ", if selection.0 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.0 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.0 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.1 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, color::Fg(color::LightBlack)), 7 => print!("└─────────────────────────────────────┘" ), _ => print!(" " ), } print!("{}", termion::cursor::Goto(offset.0, offset.1 + i)); } println!("{}", style::Reset); } } pub struct ProgressBar{ max: usize, progression: usize, message: String, color: FerretColor } impl ProgressBar{ fn new(message: String, max: usize, color: FerretColor) -> Self{ ProgressBar{ max, progression: 0, message, color } } fn invoke(&mut self){ ProgressBar::draw(self.message.clone(), self.progression.to_string() + "/" + &self.max.to_string(), self.progression / 27, self.color.clone()); } fn increase(&mut self){ self.progression += 1; ProgressBar::invoke(self); } fn draw(message: String, description: String, position: usize, color: FerretColor){ if message.len() > 38 {panic!("Message is too long")} let offset = (terminal_size().unwrap().0 / 2 - 20, terminal_size().unwrap().1 / 2 - 4); let offset_message = 20 - message.len() / 2; let offset_description = 20 - description.len() / 2; print!("{}{}{}", termion::cursor::Goto(offset.0, offset.1), if color == FerretColor::Red { "\x1b[48;5;88m" } else if color == FerretColor::Gray { "\x1b[48;5;238m" } else {"\x1b[48;5;24m"}, "\x1b[38;5;243m"); for i in 0..8{ match i { 1 => print!("┌─────────────────────────────────────┐" ), 2 => { let mut j = 0; loop{ if j == offset_message { print!("{}{}{}", color::Fg(color::White), message, "\x1b[38;5;243m"); j += message.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 3 => { let mut j = 0; loop{ if j == offset_description { print!("{}{}{}", color::Fg(color::White), description, "\x1b[38;5;243m"); j += description.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 5 => { for _i in 0..5{ print!(" {}", "\x1b[37m"); } for _i in 0..position{ print!("━"); } for _i in 0..34 - position{ print!(" {}", "\x1b[38;5;243m"); } }, 6 => print!(" └─────────────────────────────┘ " ), 7 => print!("└─────────────────────────────────────┘" ), _ => print!(" " ), } print!("{}", termion::cursor::Goto(offset.0, offset.1 + i)); } println!("{}", style::Reset); } }
extern crate termion; use std::io::{Write, stdout}; use termion::{terminal_size, color, style, raw::IntoRawMode, input::TermRead}; use std::{thread, time}; pub struct Misc; impl Misc { #[allow(dead_code)] fn overwrite(){ let stdout = stdout(); let mut stdout = stdout.lock().into_raw_mode().unwrap(); write!(stdout, "{}", termion::cursor::Goto(1, 1)).unwrap(); let pres = terminal_size().unwrap().0; for _i in 0..pres{ for _j in 0..terminal_size().unwrap().1{ print!(" "); } } write!(stdout, "{}", termion::cursor::Goto(1, 1)).unwrap(); } } #[allow(dead_code)] #[derive(PartialEq, Clone)] enum FerretColor{ Red, Blue, Gray } enum AlertButton{ Right, Left } pub struct Alert; impl Alert { #[allow(dead_code)] fn invoke(message: String, buttons: (String, String), color: FerretColor) -> AlertButton { Alert::draw(message.clone(), buttons.clone(), (false, false), (false, false), color.clone()); let mut set = 0; let stdout = stdout(); let stdout = stdout.into_raw_mode().unwrap(); let mut stdin = termion::async_stdin().keys(); loop { let input = stdin.next(); if let Some(Ok(key)) = input { match key { termion::event::Key::Char('1') | termion::event::Key::Char('Y') | termion::event::Key::Char('y') => { Alert::draw(message.clone(), buttons.clone(), (true, false), (true, false), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Left }, termion::event::Key::Char('2') | termion::event::Key::Char('N') | termion::event::Key::Char('n') => { Alert::draw(message.clone(), buttons.clone(), (false, true), (false, true), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Right }, termion::event::Key::Right => set = 2, termion::event::Key::Left => set = 1, termion::event::Key::Char('\n') | termion::event::Key::Char(' ') => { match set { 1 => { Alert::draw(message.clone(), buttons.clone(), (true, false), (true, false), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Left }, 2 => {Alert::draw(message.clone(), buttons.clone(), (false, true), (false, true), color.clone()); thread::sleep(time::Duration::from_millis(200)); Misc::overwrite(); return AlertButton::Right }, 0 | _ => () } }, _ => () } stdout.lock().flush().unwrap(); match set { 1 => Alert::draw(message.clone(), buttons.clone(), (true, false), (false, false), color.clone()), 2 => Alert::draw(message.clone(), buttons.clone(), (false, true), (false, false), color.clone()), 0 | _ => Alert::draw(message.clone(), buttons.clone(), (false, false), (false, false), color.clone()), } } thread::sleep(time::Duration::from_millis(30)); } } fn draw(message: String, buttons: (String, String), selection: (bool, bool), pushing:(bool, bool), color: FerretColor){ if message.len() > 38 || buttons.0.len() > 10 || buttons.1.len() > 10 {panic!("Message is too long")} let offset = (terminal_size().unwrap().0 / 2 - 20, terminal_size().unwrap().1 / 2 - 4); let offset_message = 20 - message.len() / 2; let offset_buttons = (9 - buttons.0.len() / 2, 31 - buttons.1.len() / 2); let mut colors_sel = [0,0]; if selection.0 == true { colors_sel[0] = 1}; if selection.1 == true { colors_sel[0] = 1}; print!("{}{}{}", termion::cursor::Goto(offset.0, offset.1), if color == FerretColor::Red { "\x1b[48;5;88m" } else if color == FerretColor::Gray { "\x1b[48;5;238m" } else {"\x1b[48;5;24m"}, "\x1b[38;5;243m"); for i in 0..8{ match i { 1 => print!("┌─────────────────────────────────────┐" ), 2 => { let mut j = 0; loop{ if j == offset_message { print!("{}{}{}", color::Fg(color::White), message, "\x1b[38;5;243m"); j += message.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 4 => if pushing == (false, false){ print!(" {}┌{}──────────{}┐ {}┌{}──────────{}┐{} ", if selection.0 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.0 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.0 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.1 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m┬"} else {"\x1b[38;5;243m─"}, "\x1b[38;5;243m") }else { if pushing.0 == true { print!("{} ┌┬──────────┬┐ ", "\x1b[38;5;243m") } else {print!("{} ┌┬──────────┬┐ ", "\x1b[38;5;243m" )} }, 5 => if pushing == (false, false){ let mut j = 0; loop{ if j == offset_buttons.0 { print!("{}{}{}", color::Fg(color::White), buttons.0, color::Fg(color::LightBlack)); j += buttons.0.len(); } else if j == offset_buttons.1 { print!("{}{}{}", color::Fg(color::White), buttons.1, color::Fg(color::LightBlack)); j += buttons.1.len() - 1; } else {print!(" ")} j += 1; if j > 39 {break;} } }else{ if pushing.1 == true { print!("{} ┌┬──────────┬┐ ", "\x1b[37m") } else {print!("{} ┌┬──────────┬┐ ", "\x1b[37m" )} }, 6 => print!(" {}└{}──────────{}┘ {}└{}──────────{}┘{} ", if selection.0 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.0 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.0 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m"} else {"\x1b[38;5;243m"}, if selection.1 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, if selection.1 == true {"\x1b[37m┴"} else {"\x1b[38;5;243m─"}, color::Fg(color::LightBlack)), 7 => print!("└─────────────────────────────────────┘" ), _ => print!(" " ), } print!("{}", termion::cursor::Goto(offset.0, offset.1 + i)); } println!("{}", style::Reset); } } pub struct ProgressBar{ max: usize, progression: usize, message: String, color: FerretColor } impl ProgressBar{
fn invoke(&mut self){ ProgressBar::draw(self.message.clone(), self.progression.to_string() + "/" + &self.max.to_string(), self.progression / 27, self.color.clone()); } fn increase(&mut self){ self.progression += 1; ProgressBar::invoke(self); } fn draw(message: String, description: String, position: usize, color: FerretColor){ if message.len() > 38 {panic!("Message is too long")} let offset = (terminal_size().unwrap().0 / 2 - 20, terminal_size().unwrap().1 / 2 - 4); let offset_message = 20 - message.len() / 2; let offset_description = 20 - description.len() / 2; print!("{}{}{}", termion::cursor::Goto(offset.0, offset.1), if color == FerretColor::Red { "\x1b[48;5;88m" } else if color == FerretColor::Gray { "\x1b[48;5;238m" } else {"\x1b[48;5;24m"}, "\x1b[38;5;243m"); for i in 0..8{ match i { 1 => print!("┌─────────────────────────────────────┐" ), 2 => { let mut j = 0; loop{ if j == offset_message { print!("{}{}{}", color::Fg(color::White), message, "\x1b[38;5;243m"); j += message.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 3 => { let mut j = 0; loop{ if j == offset_description { print!("{}{}{}", color::Fg(color::White), description, "\x1b[38;5;243m"); j += description.len(); } else {print!(" ")} j += 1; if j > 39 {break;} } }, 5 => { for _i in 0..5{ print!(" {}", "\x1b[37m"); } for _i in 0..position{ print!("━"); } for _i in 0..34 - position{ print!(" {}", "\x1b[38;5;243m"); } }, 6 => print!(" └─────────────────────────────┘ " ), 7 => print!("└─────────────────────────────────────┘" ), _ => print!(" " ), } print!("{}", termion::cursor::Goto(offset.0, offset.1 + i)); } println!("{}", style::Reset); } }
fn new(message: String, max: usize, color: FerretColor) -> Self{ ProgressBar{ max, progression: 0, message, color } }
function_block-full_function
[ { "content": "fn main() {\n\n\tMisc::overwrite();\n\n\tloop{\n\n\t\tlet mut progress_bar = ProgressBar::new(\"LOADING...\".to_string(), 800, FerretColor::Blue);\n\n\t\tfor _i in 0..800{\n\n\t\t\tthread::sleep(time::Duration::from_millis(10));\n\n\t\t\tprogress_bar.increase();\n\n\t\t}\n\n\t\tmatch Alert::invoke...
Rust
algebra/src/curves/mod.rs
knarz/zexe
e094e2127430521b7a882b0773bf1dc6852237b4
use crate::{ bytes::{FromBytes, ToBytes}, fields::{Field, PrimeField, SquareRootField}, groups::Group, }; use crate::UniformRand; use std::{ fmt::{Debug, Display}, hash::Hash, ops::{Add, AddAssign, Neg, Sub, SubAssign}, }; pub mod bls12_377; pub mod bls12_381; pub mod edwards_bls12; pub mod edwards_sw6; pub mod jubjub; pub mod mnt6; pub mod models; pub mod sw6; #[cfg(test)] pub mod tests; pub use self::models::*; pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { type Fr: PrimeField + SquareRootField + Into<<Self::Fr as PrimeField>::BigInt>; type G1Projective: ProjectiveCurve< BaseField = Self::Fq, ScalarField = Self::Fr, Affine = Self::G1Affine, > + From<Self::G1Affine>; type G1Affine: AffineCurve< BaseField = Self::Fq, ScalarField = Self::Fr, Projective = Self::G1Projective, > + PairingCurve<PairWith = Self::G2Affine, PairingResult = Self::Fqk> + From<Self::G1Projective>; type G2Projective: ProjectiveCurve< BaseField = Self::Fqe, ScalarField = Self::Fr, Affine = Self::G2Affine, > + From<Self::G2Affine>; type G2Affine: AffineCurve< BaseField = Self::Fqe, ScalarField = Self::Fr, Projective = Self::G2Projective, > + PairingCurve<PairWith = Self::G1Affine, PairingResult = Self::Fqk> + From<Self::G2Projective>; type Fq: PrimeField + SquareRootField; type Fqe: SquareRootField; type Fqk: Field; #[must_use] fn miller_loop<'a, I>(i: I) -> Self::Fqk where I: IntoIterator< Item = &'a ( &'a <Self::G1Affine as PairingCurve>::Prepared, &'a <Self::G2Affine as PairingCurve>::Prepared, ), >; #[must_use] fn final_exponentiation(_: &Self::Fqk) -> Option<Self::Fqk>; #[must_use] fn product_of_pairings<'a, I>(i: I) -> Self::Fqk where I: IntoIterator< Item = &'a ( &'a <Self::G1Affine as PairingCurve>::Prepared, &'a <Self::G2Affine as PairingCurve>::Prepared, ), >, { Self::final_exponentiation(&Self::miller_loop(i)).unwrap() } #[must_use] fn pairing<G1, G2>(p: G1, q: G2) -> Self::Fqk where G1: Into<Self::G1Affine>, G2: Into<Self::G2Affine>, { Self::final_exponentiation(&Self::miller_loop( [(&(p.into().prepare()), &(q.into().prepare()))].iter(), )) .unwrap() } } pub trait ProjectiveCurve: Eq + Sized + ToBytes + FromBytes + Copy + Clone + Default + Send + Sync + Hash + Debug + Display + UniformRand + 'static + Neg<Output = Self> + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + for<'a> AddAssign<&'a Self> + for<'a> SubAssign<&'a Self> { type ScalarField: PrimeField + SquareRootField + Into<<Self::ScalarField as PrimeField>::BigInt>; type BaseField: Field; type Affine: AffineCurve<Projective = Self, ScalarField = Self::ScalarField>; #[must_use] fn zero() -> Self; #[must_use] fn prime_subgroup_generator() -> Self; #[must_use] fn is_zero(&self) -> bool; fn batch_normalization(v: &mut [Self]); #[must_use] fn is_normalized(&self) -> bool; #[must_use] fn double(&self) -> Self { let mut copy = *self; copy.double_in_place(); copy } fn double_in_place(&mut self) -> &mut Self; fn add_assign_mixed(&mut self, other: &Self::Affine); fn mul_assign<S: Into<<Self::ScalarField as PrimeField>::BigInt>>(&mut self, other: S); #[must_use] fn into_affine(&self) -> Self::Affine; #[must_use] fn recommended_wnaf_for_scalar(scalar: <Self::ScalarField as PrimeField>::BigInt) -> usize; #[must_use] fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize; } pub trait AffineCurve: Eq + Sized + ToBytes + FromBytes + Copy + Clone + Default + Send + Sync + Hash + Debug + Display + Neg<Output = Self> + 'static { type ScalarField: PrimeField + SquareRootField + Into<<Self::ScalarField as PrimeField>::BigInt>; type BaseField: Field; type Projective: ProjectiveCurve<Affine = Self, ScalarField = Self::ScalarField>; #[must_use] fn zero() -> Self; #[must_use] fn prime_subgroup_generator() -> Self; #[must_use] fn is_zero(&self) -> bool; #[must_use] fn mul<S: Into<<Self::ScalarField as PrimeField>::BigInt>>(&self, other: S) -> Self::Projective; #[must_use] fn into_projective(&self) -> Self::Projective; #[must_use] fn mul_by_cofactor(&self) -> Self; #[must_use] fn mul_by_cofactor_inv(&self) -> Self; } pub trait PairingCurve: AffineCurve { type Engine: PairingEngine<Fr = Self::ScalarField>; type Prepared: ToBytes + Default + Clone + Send + Sync + Debug + 'static; type PairWith: PairingCurve<PairWith = Self>; type PairingResult: Field; #[must_use] fn prepare(&self) -> Self::Prepared; #[must_use] fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult; } impl<C: ProjectiveCurve> Group for C { type ScalarField = C::ScalarField; #[must_use] fn zero() -> Self { <C as ProjectiveCurve>::zero() } #[must_use] fn is_zero(&self) -> bool { <C as ProjectiveCurve>::is_zero(&self) } #[inline] #[must_use] fn double(&self) -> Self { let mut tmp = *self; tmp += self; tmp } #[inline] fn double_in_place(&mut self) -> &mut Self { <C as ProjectiveCurve>::double_in_place(self) } }
use crate::{ bytes::{FromBytes, ToBytes}, fields::{Field, PrimeField, SquareRootField}, groups::Group, }; use crate::UniformRand; use std::{ fmt::{Debug, Display}, hash::Hash, ops::{Add, AddAssign, Neg, Sub, SubAssign}, }; pub mod bls12_377; pub mod bls12_381; pub mod edwards_bls12; pub mod edwards_sw6; pub mod jubjub; pub mod mnt6; pub mod models; pub mod sw6; #[cfg(test)] pub mod tests; pub use self::models::*; pub trait PairingEngine: Sized + 'static + Copy + Debug + Sync + Send { type Fr: PrimeField + SquareRootField + Into<<Self::Fr as PrimeField>::BigInt>; type G1Projective: ProjectiveCurve< BaseField = Self::Fq, ScalarField = Self::Fr, Affine = Self::G1Affine, > + From<Self::G1Affine>; type G1Affine: AffineCurve< BaseField = Self::Fq, ScalarField = Self::Fr, Projective = Self::G1Projective, > + PairingCurve<PairWith = Self::G2Affine, PairingResult = Self::Fqk> + From<Self::G1Projective>; type G2Projective: ProjectiveCurve< BaseField = Self::Fqe, ScalarField = Self::Fr, Affine = Self::G2Affine, > + From<Self::G2Affine>; type G2Affine: AffineCurve< BaseField = Self::Fqe, ScalarField = Self::Fr, Projective = Self::G2Projective, > + PairingCurve<PairWith = Self::G1Affine, PairingResult = Self::Fqk> + From<Self::G2Projective>; type Fq: PrimeField + SquareRootField; type Fqe: SquareRootField; type Fqk: Field; #[must_use] fn miller_loop<'a, I>(i: I) -> Self::Fqk where I: IntoIterator< Item = &'a ( &'a <Self::G1Affine as PairingCurve>::Prepared, &'a <Self::G2Affine as PairingCurve>::Prepared, ), >; #[must_use] fn final_exponentiation(_: &Self::Fqk) -> Option<Self::Fqk>; #[must_use] fn product_of_pairings<'a, I>(i: I) -> Self::Fqk where I: IntoIterator< Item = &'a ( &'a <Self::G1Affine as PairingCurve>::Prepared, &'a <Self::G2Affine as PairingCurve>::Prepared, ), >, { Self::final_exponentiation(&Self::miller_loop(i)).unwrap() } #[must_use]
} pub trait ProjectiveCurve: Eq + Sized + ToBytes + FromBytes + Copy + Clone + Default + Send + Sync + Hash + Debug + Display + UniformRand + 'static + Neg<Output = Self> + for<'a> Add<&'a Self, Output = Self> + for<'a> Sub<&'a Self, Output = Self> + for<'a> AddAssign<&'a Self> + for<'a> SubAssign<&'a Self> { type ScalarField: PrimeField + SquareRootField + Into<<Self::ScalarField as PrimeField>::BigInt>; type BaseField: Field; type Affine: AffineCurve<Projective = Self, ScalarField = Self::ScalarField>; #[must_use] fn zero() -> Self; #[must_use] fn prime_subgroup_generator() -> Self; #[must_use] fn is_zero(&self) -> bool; fn batch_normalization(v: &mut [Self]); #[must_use] fn is_normalized(&self) -> bool; #[must_use] fn double(&self) -> Self { let mut copy = *self; copy.double_in_place(); copy } fn double_in_place(&mut self) -> &mut Self; fn add_assign_mixed(&mut self, other: &Self::Affine); fn mul_assign<S: Into<<Self::ScalarField as PrimeField>::BigInt>>(&mut self, other: S); #[must_use] fn into_affine(&self) -> Self::Affine; #[must_use] fn recommended_wnaf_for_scalar(scalar: <Self::ScalarField as PrimeField>::BigInt) -> usize; #[must_use] fn recommended_wnaf_for_num_scalars(num_scalars: usize) -> usize; } pub trait AffineCurve: Eq + Sized + ToBytes + FromBytes + Copy + Clone + Default + Send + Sync + Hash + Debug + Display + Neg<Output = Self> + 'static { type ScalarField: PrimeField + SquareRootField + Into<<Self::ScalarField as PrimeField>::BigInt>; type BaseField: Field; type Projective: ProjectiveCurve<Affine = Self, ScalarField = Self::ScalarField>; #[must_use] fn zero() -> Self; #[must_use] fn prime_subgroup_generator() -> Self; #[must_use] fn is_zero(&self) -> bool; #[must_use] fn mul<S: Into<<Self::ScalarField as PrimeField>::BigInt>>(&self, other: S) -> Self::Projective; #[must_use] fn into_projective(&self) -> Self::Projective; #[must_use] fn mul_by_cofactor(&self) -> Self; #[must_use] fn mul_by_cofactor_inv(&self) -> Self; } pub trait PairingCurve: AffineCurve { type Engine: PairingEngine<Fr = Self::ScalarField>; type Prepared: ToBytes + Default + Clone + Send + Sync + Debug + 'static; type PairWith: PairingCurve<PairWith = Self>; type PairingResult: Field; #[must_use] fn prepare(&self) -> Self::Prepared; #[must_use] fn pairing_with(&self, other: &Self::PairWith) -> Self::PairingResult; } impl<C: ProjectiveCurve> Group for C { type ScalarField = C::ScalarField; #[must_use] fn zero() -> Self { <C as ProjectiveCurve>::zero() } #[must_use] fn is_zero(&self) -> bool { <C as ProjectiveCurve>::is_zero(&self) } #[inline] #[must_use] fn double(&self) -> Self { let mut tmp = *self; tmp += self; tmp } #[inline] fn double_in_place(&mut self) -> &mut Self { <C as ProjectiveCurve>::double_in_place(self) } }
fn pairing<G1, G2>(p: G1, q: G2) -> Self::Fqk where G1: Into<Self::G1Affine>, G2: Into<Self::G2Affine>, { Self::final_exponentiation(&Self::miller_loop( [(&(p.into().prepare()), &(q.into().prepare()))].iter(), )) .unwrap() }
function_block-full_function
[ { "content": "/// A trait that defines parameters for a prime field.\n\npub trait FpParameters: 'static + Send + Sync + Sized {\n\n type BigInt: BigInteger;\n\n\n\n /// The modulus of the field.\n\n const MODULUS: Self::BigInt;\n\n\n\n /// The number of bits needed to represent the `Self::MODULUS`.\...
Rust
old/marker.rs
Cognoscan/fog_pack
7b3af246faa851bfc2aa09cc186ff2332124e791
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Marker { PosFixInt(u8), FixMap(u8), FixArray(u8), FixStr(u8), Nil, Reserved, False, True, Bin8, Bin16, Bin32, Ext8, Ext16, Ext32, F32, F64, UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, FixExt1, FixExt2, FixExt4, FixExt8, FixExt16, Str8, Str16, Str32, Array16, Array32, Map16, Map32, NegFixInt(i8), } impl Marker { pub fn from_u8(n: u8) -> Marker { match n { 0x00 ..= 0x7f => Marker::PosFixInt(n), 0x80 ..= 0x8f => Marker::FixMap(n & 0x0F), 0x90 ..= 0x9f => Marker::FixArray(n & 0x0F), 0xa0 ..= 0xbf => Marker::FixStr(n & 0x1F), 0xc0 => Marker::Nil, 0xc1 => Marker::Reserved, 0xc2 => Marker::False, 0xc3 => Marker::True, 0xc4 => Marker::Bin8, 0xc5 => Marker::Bin16, 0xc6 => Marker::Bin32, 0xc7 => Marker::Ext8, 0xc8 => Marker::Ext16, 0xc9 => Marker::Ext32, 0xca => Marker::F32, 0xcb => Marker::F64, 0xcc => Marker::UInt8, 0xcd => Marker::UInt16, 0xce => Marker::UInt32, 0xcf => Marker::UInt64, 0xd0 => Marker::Int8, 0xd1 => Marker::Int16, 0xd2 => Marker::Int32, 0xd3 => Marker::Int64, 0xd4 => Marker::FixExt1, 0xd5 => Marker::FixExt2, 0xd6 => Marker::FixExt4, 0xd7 => Marker::FixExt8, 0xd8 => Marker::FixExt16, 0xd9 => Marker::Str8, 0xda => Marker::Str16, 0xdb => Marker::Str32, 0xdc => Marker::Array16, 0xdd => Marker::Array32, 0xde => Marker::Map16, 0xdf => Marker::Map32, 0xe0 ..= 0xff => Marker::NegFixInt(n as i8), } } pub fn into_u8(self) -> u8 { match self { Marker::PosFixInt(val) => val, Marker::FixMap(len) => 0x80 | len, Marker::FixArray(len) => 0x90 | len, Marker::FixStr(len) => 0xa0 | len, Marker::Nil => 0xc0, Marker::Reserved => 0xc1, Marker::False => 0xc2, Marker::True => 0xc3, Marker::Bin8 => 0xc4, Marker::Bin16 => 0xc5, Marker::Bin32 => 0xc6, Marker::Ext8 => 0xc7, Marker::Ext16 => 0xc8, Marker::Ext32 => 0xc9, Marker::F32 => 0xca, Marker::F64 => 0xcb, Marker::UInt8 => 0xcc, Marker::UInt16 => 0xcd, Marker::UInt32 => 0xce, Marker::UInt64 => 0xcf, Marker::Int8 => 0xd0, Marker::Int16 => 0xd1, Marker::Int32 => 0xd2, Marker::Int64 => 0xd3, Marker::FixExt1 => 0xd4, Marker::FixExt2 => 0xd5, Marker::FixExt4 => 0xd6, Marker::FixExt8 => 0xd7, Marker::FixExt16 => 0xd8, Marker::Str8 => 0xd9, Marker::Str16 => 0xda, Marker::Str32 => 0xdb, Marker::Array16 => 0xdc, Marker::Array32 => 0xdd, Marker::Map16 => 0xde, Marker::Map32 => 0xdf, Marker::NegFixInt(val) => val as u8, } } } impl From<u8> for Marker { fn from(val: u8) -> Marker { Marker::from_u8(val) } } impl From<Marker> for u8 { fn from(val: Marker) -> u8 { val.into_u8() } } #[derive(Debug,PartialEq,Eq)] pub enum ExtType { Timestamp, Hash, Identity, Lockbox, } impl ExtType { pub fn into_i8(self) -> i8 { match self { ExtType::Timestamp => -1, ExtType::Hash => 1, ExtType::Identity => 2, ExtType::Lockbox => 3, } } pub fn from_i8(v: i8) -> Option<ExtType> { match v { -1 => Some(ExtType::Timestamp), 1 => Some(ExtType::Hash), 2 => Some(ExtType::Identity), 3 => Some(ExtType::Lockbox), _ => None, } } } impl From<ExtType> for i8 { fn from(val: ExtType) -> i8 { val.into_i8() } } impl From<ExtType> for u8 { fn from(val: ExtType) -> u8 { val.into_i8() as u8 } } #[derive(Debug)] pub enum MarkerType { Null, Boolean(bool), NegInt((usize, i8)), PosInt((usize, u8)), String(usize), F32, F64, Binary(usize), Array(usize), Object(usize), Hash(usize), Identity(usize), Lockbox(usize), Timestamp(usize), } impl MarkerType { pub fn from_ext_i8(len: usize, v: i8) -> Option<MarkerType> { match v { -1 => Some(MarkerType::Timestamp(len)), 1 => Some(MarkerType::Hash(len)), 2 => Some(MarkerType::Identity(len)), 3 => Some(MarkerType::Lockbox(len)), _ => None, } } }
#[derive(Clone, Copy, Debug, PartialEq)] pub enum Marker { PosFixInt(u8), FixMap(u8), FixArray(u8), FixStr(u8), Nil, Reserved, False, True, Bin8, Bin16, Bin32, Ext8, Ext16, Ext32, F32, F64, UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, FixExt1, FixExt2, FixExt4, FixExt8, FixExt16, Str8, Str16, Str32, Array16, Array32, Map16, Map32, NegFixInt(i8), } impl Marker { pub fn from_u8(n: u8) -> Marker { match n { 0x00 ..= 0x7f => Marker::PosFixInt(n), 0x80 ..= 0x8f => Marker::FixMap(n & 0x0F), 0x90 ..= 0x9f => Marker::FixArray(n & 0x0F), 0xa0 ..= 0xbf => Marker::FixStr(n & 0x1F), 0xc0 => Marker::Nil, 0xc1 => Marker::Reserved, 0xc2 => Marker::False, 0xc3 => Marker::True, 0xc4 => Marker::Bin8, 0xc5 => Marker::Bin16, 0xc6 => Marker::Bin32, 0xc7 => Marker::Ext8, 0xc8 => Marker::Ext16, 0xc9 => Marker::Ext32, 0xca => Marker::F32, 0xcb => Marker::F64, 0xcc => Marker::UInt8, 0xcd => Marker::UInt16, 0xce => Marker::UInt32, 0xcf => Marker::UInt64, 0xd0 => Marker::Int8, 0xd1 => Marker::Int16, 0xd2 => Marker::Int32, 0xd3 => Marker::Int64, 0xd4 => Marker::FixExt1, 0xd5 => Marker::FixExt2, 0xd6 => Marker::FixExt4, 0xd7 => Marker::FixExt8, 0xd8 => Marker::FixExt16, 0xd9 => Marker::Str8, 0xda => Marker::Str16, 0xdb => Marker::Str32, 0xdc => Marker::Array16, 0xdd => Marker::Array32, 0xde => Marker::Map16, 0xdf => Marker::Map32, 0xe0 ..= 0xff => Marker::NegFixInt(n as i8), } }
} impl From<u8> for Marker { fn from(val: u8) -> Marker { Marker::from_u8(val) } } impl From<Marker> for u8 { fn from(val: Marker) -> u8 { val.into_u8() } } #[derive(Debug,PartialEq,Eq)] pub enum ExtType { Timestamp, Hash, Identity, Lockbox, } impl ExtType { pub fn into_i8(self) -> i8 { match self { ExtType::Timestamp => -1, ExtType::Hash => 1, ExtType::Identity => 2, ExtType::Lockbox => 3, } } pub fn from_i8(v: i8) -> Option<ExtType> { match v { -1 => Some(ExtType::Timestamp), 1 => Some(ExtType::Hash), 2 => Some(ExtType::Identity), 3 => Some(ExtType::Lockbox), _ => None, } } } impl From<ExtType> for i8 { fn from(val: ExtType) -> i8 { val.into_i8() } } impl From<ExtType> for u8 { fn from(val: ExtType) -> u8 { val.into_i8() as u8 } } #[derive(Debug)] pub enum MarkerType { Null, Boolean(bool), NegInt((usize, i8)), PosInt((usize, u8)), String(usize), F32, F64, Binary(usize), Array(usize), Object(usize), Hash(usize), Identity(usize), Lockbox(usize), Timestamp(usize), } impl MarkerType { pub fn from_ext_i8(len: usize, v: i8) -> Option<MarkerType> { match v { -1 => Some(MarkerType::Timestamp(len)), 1 => Some(MarkerType::Hash(len)), 2 => Some(MarkerType::Identity(len)), 3 => Some(MarkerType::Lockbox(len)), _ => None, } } }
pub fn into_u8(self) -> u8 { match self { Marker::PosFixInt(val) => val, Marker::FixMap(len) => 0x80 | len, Marker::FixArray(len) => 0x90 | len, Marker::FixStr(len) => 0xa0 | len, Marker::Nil => 0xc0, Marker::Reserved => 0xc1, Marker::False => 0xc2, Marker::True => 0xc3, Marker::Bin8 => 0xc4, Marker::Bin16 => 0xc5, Marker::Bin32 => 0xc6, Marker::Ext8 => 0xc7, Marker::Ext16 => 0xc8, Marker::Ext32 => 0xc9, Marker::F32 => 0xca, Marker::F64 => 0xcb, Marker::UInt8 => 0xcc, Marker::UInt16 => 0xcd, Marker::UInt32 => 0xce, Marker::UInt64 => 0xcf, Marker::Int8 => 0xd0, Marker::Int16 => 0xd1, Marker::Int32 => 0xd2, Marker::Int64 => 0xd3, Marker::FixExt1 => 0xd4, Marker::FixExt2 => 0xd5, Marker::FixExt4 => 0xd6, Marker::FixExt8 => 0xd7, Marker::FixExt16 => 0xd8, Marker::Str8 => 0xd9, Marker::Str16 => 0xda, Marker::Str32 => 0xdb, Marker::Array16 => 0xdc, Marker::Array32 => 0xdd, Marker::Map16 => 0xde, Marker::Map32 => 0xdf, Marker::NegFixInt(val) => val as u8, } }
function_block-full_function
[ { "content": "/// Attempt to read a F32 from a fogpack data structure. Fails if invalid F64 retrieved.\n\npub fn read_f64(buf: &mut &[u8]) -> crate::Result<f64> {\n\n let fail_len = buf.len();\n\n let marker = read_marker(buf)?;\n\n if let MarkerType::F64 = marker {\n\n Ok(buf.read_f64::<BigEndi...
Rust
src/viewed_date.rs
tommket/chrono-datepicker-core
392903f18fc33bfa1f4e75cf866867d9835c5ac6
use std::ops::RangeInclusive; use chrono::{Datelike, NaiveDate}; use crate::dialog_view_type::DialogViewType; pub const YEARS_IN_YEAR_SELECTION: i32 = 20; pub type YearNumber = i32; pub type MonthNumber = u32; pub type DayNumber = u32; pub trait ViewedDate { fn previous_month(&self) -> NaiveDate; fn next_month(&self) -> NaiveDate; fn previous_year(&self) -> NaiveDate; fn next_year(&self) -> NaiveDate; fn previous_year_group(&self) -> NaiveDate; fn next_year_group(&self) -> NaiveDate; fn first_day_of_month(&self) -> NaiveDate; fn contains(&self, dialog_view_type: &DialogViewType, date: &NaiveDate) -> bool; } impl ViewedDate for NaiveDate { fn previous_month(&self) -> NaiveDate { let mut year = self.year(); let mut month = self.month(); if month == 1 { month = 12; year -= 1; } else { month -= 1; } NaiveDate::from_ymd(year, month, 1) } fn next_month(&self) -> NaiveDate { let mut year = self.year(); let mut month = self.month(); if month == 12 { month = 1; year += 1; } else { month += 1; } NaiveDate::from_ymd(year, month, 1) } fn previous_year(&self) -> NaiveDate { NaiveDate::from_ymd(self.year() - 1, 1, 1) } fn next_year(&self) -> NaiveDate { NaiveDate::from_ymd(self.year() + 1, 1, 1) } fn previous_year_group(&self) -> NaiveDate { NaiveDate::from_ymd(year_group_start(self.year()) - 1, 1, 1) } fn next_year_group(&self) -> NaiveDate { NaiveDate::from_ymd(year_group_end(self.year()) + 1, 1, 1) } fn first_day_of_month(&self) -> NaiveDate { NaiveDate::from_ymd(self.year(), self.month(), 1) } fn contains(&self, dialog_view_type: &DialogViewType, date: &NaiveDate) -> bool { match dialog_view_type { DialogViewType::Years => self.year() == date.year(), DialogViewType::Months => self.year() == date.year() && self.month() == date.month(), DialogViewType::Days => self == date, } } } pub fn year_group_start(year: YearNumber) -> YearNumber { year - (year % YEARS_IN_YEAR_SELECTION) } pub fn year_group_end(year: YearNumber) -> YearNumber { year_group_start(year) + (YEARS_IN_YEAR_SELECTION - 1) } pub fn year_group_range(year: YearNumber) -> RangeInclusive<YearNumber> { year_group_start(year)..=year_group_end(year) } #[cfg(test)] mod tests { use crate::rstest_utils::create_date; use rstest::*; use super::*; #[rstest( expected, given, case::from_january(create_date(1989, 12, 1), create_date(1990, 1, 15)), case::not_from_january(create_date(1990, 2, 1), create_date(1990, 3, 22)), )] fn previous_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_month()); } #[rstest( expected, given, case::from_december(create_date(1991, 1, 1), create_date(1990, 12, 22)), case::not_from_december(create_date(1990, 4, 1), create_date(1990, 3, 15)), )] fn next_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_month()); } #[rstest( expected, given, case(create_date(1989, 1, 1), create_date(1990, 12, 25)), case(create_date(1990, 1, 1), create_date(1991, 3, 22)), )] fn previous_year(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_year()); } #[rstest( expected, given, case(create_date(1991, 1, 1), create_date(1990, 12, 25)), case(create_date(1992, 1, 1), create_date(1991, 3, 22)), )] fn next_year(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_year()); } #[rstest( expected, given, case::in_middle(create_date(1979, 1, 1), create_date(1990, 1, 1)), case::at_start(create_date(1979, 1, 1), create_date(1980, 3, 20)), case::at_end(create_date(1979, 1, 1), create_date(1999, 7, 24)), case::next_group(create_date(1999, 1, 1), create_date(2000, 8, 22)), )] fn previous_year_group(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_year_group()); } #[rstest( expected, given, case::in_middle(create_date(2000, 1, 1), create_date(1990, 1, 1)), case::at_start(create_date(2000, 1, 1), create_date(1980, 3, 20)), case::at_end(create_date(2000, 1, 1), create_date(1999, 7, 24)), case::next_group(create_date(2020, 1, 1), create_date(2000, 8, 22)), )] fn next_year_group(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_year_group()); } #[rstest( expected, given, case(create_date(1990, 12, 1), create_date(1990, 12, 15)), case(create_date(1991, 3, 1), create_date(1991, 3, 24)), )] fn first_day_of_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.first_day_of_month()); } #[rstest( expected, viewed_date, dialog_view_type, tested_date, case::years_different(false, create_date(1990, 1, 1), DialogViewType::Years, create_date(1989, 1, 1)), case::years_equal(true, create_date(1990, 1, 1), DialogViewType::Years, create_date(1990, 5, 15)), case::months_different_year(false, create_date(1990, 3, 1), DialogViewType::Months, create_date(1989, 3, 1)), case::months_different_month(false, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 4, 1)), case::months_equal(true, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 3, 15)), case::days_different_year(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1989, 3, 1)), case::days_different_month(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1990, 4, 1)), case::days_different_day(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1990, 3, 15)), case::months_equal(true, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 3, 15)), )] fn contains( expected: bool, viewed_date: NaiveDate, dialog_view_type: DialogViewType, tested_date: NaiveDate, ) { assert_eq!( expected, viewed_date.contains(&dialog_view_type, &tested_date) ); } #[rstest( expected, input, case::at_zero(0, 0), case::in_middle(1980, 1990), case::at_start(1980, 1980), case::at_end(1980, 1999), case::after_end(2000, 2000) )] fn test_year_group_start(expected: YearNumber, input: YearNumber) { assert_eq!(expected, year_group_start(input)); } #[rstest( expected, input, case::at_zero(19, 0), case::in_middle(1999, 1990), case::at_start(1999, 1980), case::at_end(1999, 1999), case::after_end(2019, 2000) )] fn test_year_group_end(expected: YearNumber, input: YearNumber) { assert_eq!(expected, year_group_end(input)); } #[rstest( expected, input, case::at_zero(0..=19, 0), case::in_middle(1980..=1999, 1990), case::at_start(1980..=1999, 1980), case::at_end(1980..=1999, 1999), case::after_end(2000..=2019, 2000) )] fn test_year_group_range(expected: RangeInclusive<YearNumber>, input: YearNumber) { assert_eq!(expected, year_group_range(input)); } }
use std::ops::RangeInclusive; use chrono::{Datelike, NaiveDate}; use crate::dialog_view_type::DialogViewType; pub const YEARS_IN_YEAR_SELECTION: i32 = 20; pub type YearNumber = i32; pub type MonthNumber = u32; pub type DayNumber = u32; pub trait ViewedDate { fn previous_month(&self) -> NaiveDate; fn next_month(&self) -> NaiveDate; fn previous_year(&self) -> NaiveDate; fn next_year(&self) -> NaiveDate; fn previous_year_group(&self) -> NaiveDate; fn next_year_group(&self) -> NaiveDate; fn first_day_of_month(&self) -> NaiveDate; fn contains(&self, dialog_view_type: &DialogViewType, date: &NaiveDate) -> bool; } impl ViewedDate for NaiveDate { fn previous_month(&self) -> NaiveDate { let mut year = self.year(); let mut month = self.month(); if month == 1 { month = 12; year -= 1; } else { month -= 1; } NaiveDate::from_ymd(year, month, 1) } fn next_month(&self) -> NaiveDate { let mut year = self.year(); let mut month = self.month(); if month == 12 { month = 1; year += 1; } else { month += 1; } NaiveDate::from_ymd(year, month, 1) } fn previous_year(&self) -> NaiveDate { NaiveDate::from_ymd(self.year() - 1, 1, 1) } fn next_year(&self) -> NaiveDate { NaiveDate::from_ymd(self.year() + 1, 1, 1) } fn previous_year_group(&self) -> NaiveDate { NaiveDate::from_ymd(year_group_start(self.year()) - 1, 1, 1) } fn next_year_group(&self) -> NaiveDate { NaiveDate::from_ymd(year_group_end(self.year()) + 1, 1, 1) } fn first_day_of_month(&self) -> NaiveDate { NaiveDate::from_ymd(self.year(), self.month(), 1) } fn contains(&self, dialog_view_type: &DialogViewType, date: &NaiveDate) -> bool {
} pub fn year_group_start(year: YearNumber) -> YearNumber { year - (year % YEARS_IN_YEAR_SELECTION) } pub fn year_group_end(year: YearNumber) -> YearNumber { year_group_start(year) + (YEARS_IN_YEAR_SELECTION - 1) } pub fn year_group_range(year: YearNumber) -> RangeInclusive<YearNumber> { year_group_start(year)..=year_group_end(year) } #[cfg(test)] mod tests { use crate::rstest_utils::create_date; use rstest::*; use super::*; #[rstest( expected, given, case::from_january(create_date(1989, 12, 1), create_date(1990, 1, 15)), case::not_from_january(create_date(1990, 2, 1), create_date(1990, 3, 22)), )] fn previous_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_month()); } #[rstest( expected, given, case::from_december(create_date(1991, 1, 1), create_date(1990, 12, 22)), case::not_from_december(create_date(1990, 4, 1), create_date(1990, 3, 15)), )] fn next_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_month()); } #[rstest( expected, given, case(create_date(1989, 1, 1), create_date(1990, 12, 25)), case(create_date(1990, 1, 1), create_date(1991, 3, 22)), )] fn previous_year(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_year()); } #[rstest( expected, given, case(create_date(1991, 1, 1), create_date(1990, 12, 25)), case(create_date(1992, 1, 1), create_date(1991, 3, 22)), )] fn next_year(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_year()); } #[rstest( expected, given, case::in_middle(create_date(1979, 1, 1), create_date(1990, 1, 1)), case::at_start(create_date(1979, 1, 1), create_date(1980, 3, 20)), case::at_end(create_date(1979, 1, 1), create_date(1999, 7, 24)), case::next_group(create_date(1999, 1, 1), create_date(2000, 8, 22)), )] fn previous_year_group(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.previous_year_group()); } #[rstest( expected, given, case::in_middle(create_date(2000, 1, 1), create_date(1990, 1, 1)), case::at_start(create_date(2000, 1, 1), create_date(1980, 3, 20)), case::at_end(create_date(2000, 1, 1), create_date(1999, 7, 24)), case::next_group(create_date(2020, 1, 1), create_date(2000, 8, 22)), )] fn next_year_group(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.next_year_group()); } #[rstest( expected, given, case(create_date(1990, 12, 1), create_date(1990, 12, 15)), case(create_date(1991, 3, 1), create_date(1991, 3, 24)), )] fn first_day_of_month(expected: NaiveDate, given: NaiveDate) { assert_eq!(expected, given.first_day_of_month()); } #[rstest( expected, viewed_date, dialog_view_type, tested_date, case::years_different(false, create_date(1990, 1, 1), DialogViewType::Years, create_date(1989, 1, 1)), case::years_equal(true, create_date(1990, 1, 1), DialogViewType::Years, create_date(1990, 5, 15)), case::months_different_year(false, create_date(1990, 3, 1), DialogViewType::Months, create_date(1989, 3, 1)), case::months_different_month(false, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 4, 1)), case::months_equal(true, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 3, 15)), case::days_different_year(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1989, 3, 1)), case::days_different_month(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1990, 4, 1)), case::days_different_day(false, create_date(1990, 3, 1), DialogViewType::Days, create_date(1990, 3, 15)), case::months_equal(true, create_date(1990, 3, 1), DialogViewType::Months, create_date(1990, 3, 15)), )] fn contains( expected: bool, viewed_date: NaiveDate, dialog_view_type: DialogViewType, tested_date: NaiveDate, ) { assert_eq!( expected, viewed_date.contains(&dialog_view_type, &tested_date) ); } #[rstest( expected, input, case::at_zero(0, 0), case::in_middle(1980, 1990), case::at_start(1980, 1980), case::at_end(1980, 1999), case::after_end(2000, 2000) )] fn test_year_group_start(expected: YearNumber, input: YearNumber) { assert_eq!(expected, year_group_start(input)); } #[rstest( expected, input, case::at_zero(19, 0), case::in_middle(1999, 1990), case::at_start(1999, 1980), case::at_end(1999, 1999), case::after_end(2019, 2000) )] fn test_year_group_end(expected: YearNumber, input: YearNumber) { assert_eq!(expected, year_group_end(input)); } #[rstest( expected, input, case::at_zero(0..=19, 0), case::in_middle(1980..=1999, 1990), case::at_start(1980..=1999, 1980), case::at_end(1980..=1999, 1999), case::after_end(2000..=2019, 2000) )] fn test_year_group_range(expected: RangeInclusive<YearNumber>, input: YearNumber) { assert_eq!(expected, year_group_range(input)); } }
match dialog_view_type { DialogViewType::Years => self.year() == date.year(), DialogViewType::Months => self.year() == date.year() && self.month() == date.month(), DialogViewType::Days => self == date, } }
function_block-function_prefix_line
[ { "content": "#[fixture(year = 1990, month = 1, day = 1)]\n\npub fn create_date(year: YearNumber, month: MonthNumber, day: DayNumber) -> NaiveDate {\n\n NaiveDate::from_ymd(year, month, day)\n\n}\n", "file_path": "src/rstest_utils.rs", "rank": 0, "score": 126217.50530730654 }, { "content"...
Rust
src/server/route.rs
fairingrey/tide
dd9d42d4c8e01299a1c7f69e0f56b8f06cc47b8f
use crate::utils::BoxFuture; use crate::{router::Router, Endpoint, Response}; #[allow(missing_debug_implementations)] pub struct Route<'a, State> { router: &'a mut Router<State>, path: String, prefix: bool, } impl<'a, State: 'static> Route<'a, State> { pub(crate) fn new(router: &'a mut Router<State>, path: String) -> Route<'a, State> { Route { router, path, prefix: false, } } pub fn at<'b>(&'b mut self, path: &str) -> Route<'b, State> { let mut p = self.path.clone(); if !p.ends_with('/') && !path.starts_with('/') { p.push_str("/"); } if path != "/" { p.push_str(path); } Route { router: &mut self.router, path: p, prefix: false, } } #[cfg(any(feature = "unstable", feature = "docs"))] #[cfg_attr(feature = "docs", doc(cfg(unstable)))] pub fn strip_prefix(&mut self) -> &mut Self { self.prefix = true; self } pub fn nest<InnerState>(&mut self, service: crate::Server<InnerState>) -> &mut Self where State: Send + Sync + 'static, InnerState: Send + Sync + 'static, { self.prefix = true; self.all(service.into_http_service()); self.prefix = false; self } pub fn method(&mut self, method: http::Method, ep: impl Endpoint<State>) -> &mut Self { if self.prefix { let ep = StripPrefixEndpoint::new(ep); self.router.add(&self.path, method.clone(), ep.clone()); let wildcard = self.at("*--tide-path-rest"); wildcard.router.add(&wildcard.path, method, ep); } else { self.router.add(&self.path, method, ep); } self } pub fn all(&mut self, ep: impl Endpoint<State>) -> &mut Self { if self.prefix { let ep = StripPrefixEndpoint::new(ep); self.router.add_all(&self.path, ep.clone()); let wildcard = self.at("*--tide-path-rest"); wildcard.router.add_all(&wildcard.path, ep); } else { self.router.add_all(&self.path, ep); } self } pub fn get(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::GET, ep); self } pub fn head(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::HEAD, ep); self } pub fn put(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::PUT, ep); self } pub fn post(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::POST, ep); self } pub fn delete(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::DELETE, ep); self } pub fn options(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::OPTIONS, ep); self } pub fn connect(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::CONNECT, ep); self } pub fn patch(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::PATCH, ep); self } pub fn trace(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::TRACE, ep); self } } #[derive(Debug)] struct StripPrefixEndpoint<E>(std::sync::Arc<E>); impl<E> StripPrefixEndpoint<E> { fn new(ep: E) -> Self { Self(std::sync::Arc::new(ep)) } } impl<E> Clone for StripPrefixEndpoint<E> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<State, E: Endpoint<State>> Endpoint<State> for StripPrefixEndpoint<E> { fn call<'a>(&'a self, mut req: crate::Request<State>) -> BoxFuture<'a, Response> { let rest = req.rest().unwrap_or(""); let mut path_and_query = format!("/{}", rest); let uri = req.uri(); if let Some(query) = uri.query() { path_and_query.push('?'); path_and_query.push_str(query); } let mut new_uri = http::Uri::builder(); if let Some(scheme) = uri.scheme_part() { new_uri.scheme(scheme.clone()); } if let Some(authority) = uri.authority_part() { new_uri.authority(authority.clone()); } new_uri.path_and_query(path_and_query.as_str()); let new_uri = new_uri.build().unwrap(); *req.request.uri_mut() = new_uri; self.0.call(req) } }
use crate::utils::BoxFuture; use crate::{router::Router, Endpoint, Response}; #[allow(missing_debug_implementations)] pub struct Route<'a, State> { router: &'a mut Router<State>, path: String, prefix: bool, } impl<'a, State: 'static> Route<'a, State> { pub(crate) fn new(router: &'a mut Router<State>, path: String) -> Route<'a, State> { Route { router, path, prefix: false, } } pub fn at<'b>(&'b mut self, path: &str) -> Route<'b, State> { let mut p = self.path.clone(); if !p.ends_with('/') && !path.starts_with('/') { p.push_str("/"); } if path != "/" { p.push_str(path); } Route { router: &mut self.router, path: p, prefix: false, } } #[cfg(any(feature = "unstable", feature = "docs"))] #[cfg_attr(feature = "docs", doc(cfg(unstable)))] pub fn strip_prefix(&mut self) -> &mut Self { self.prefix = true; self } pub fn nest<InnerState>(&mut self, service: crate::Server<InnerState>) -> &mut Self where State: Send + Sync + 'static, InnerState: Send + Sync + 'static, { self.prefix = true; self.all(service.into_http_service()); self.prefix = false; self } pub fn method(&mut self, method: http::Method, ep: impl Endpoint<State>) -> &mut Self { if self.prefix { let ep = StripPrefixEndpoint::new(ep); self.router.add(&self.path, method.clone(), ep.clone()); let wildcard = self.at("*--tide-path-rest"); wildcard.router.add(&wildcard.path, method, ep); } else { self.router.add(&self.path, method, ep); } self } pub fn all(&mut self, ep: impl Endpoint<State>) -> &mut Self { if self.prefix { let ep = StripPrefixEndpoint::new(ep); self.router.add_all(&self.path, ep.clone()); let wildcard = self.at("*--tide-path-rest"); wildcard.router.add_all(&wildcard.path, ep); } else { self.router.add_all(&self.path, ep); } self } pub fn get(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::GET, ep); self } pub fn head(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::HEAD, ep); self } pub fn put(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::PUT, ep); self } pub fn post(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::POST, ep); self } pub fn delete(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::DELETE, ep); self } pub fn options(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::OPTIONS, ep); self } pub fn connect(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::CONNECT, ep); self } pub fn patch(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::PATCH, ep); self } pub fn trace(&mut self, ep: impl Endpoint<State>) -> &mut Self { self.method(http::Method::TRACE, ep); self } } #[derive(Debug)] struct StripPrefixEndpoint<E>(std::sync::Arc<E>); impl<E> StripPrefixEndpoint<E> { fn new(ep: E) -> Self { Self(std::sync::Arc::new(ep)) } } impl<E> Clone for StripPrefixEndpoint<E> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<State, E: Endpoint<State>> Endpoint<State> for StripPrefixEndpoint<E> { fn call<'a>(&'a self, mut req: crate::Request<State>) -> BoxFuture<'a, Response> { let rest = req.rest().unwrap_or(""); let mut path_and_query = format!("/{}", rest); let uri = req.uri()
rity_part() { new_uri.authority(authority.clone()); } new_uri.path_and_query(path_and_query.as_str()); let new_uri = new_uri.build().unwrap(); *req.request.uri_mut() = new_uri; self.0.call(req) } }
; if let Some(query) = uri.query() { path_and_query.push('?'); path_and_query.push_str(query); } let mut new_uri = http::Uri::builder(); if let Some(scheme) = uri.scheme_part() { new_uri.scheme(scheme.clone()); } if let Some(authority) = uri.autho
function_block-random_span
[ { "content": "/// An HTTP request handler.\n\n///\n\n/// This trait is automatically implemented for `Fn` types, and so is rarely implemented\n\n/// directly by Tide users.\n\n///\n\n/// In practice, endpoints are functions that take a `Request<State>` as an argument and\n\n/// return a type `T` that implements...
Rust
src/lib.rs
jdisanti/hassel_wasm_dbg
9b3804d4f42d2310151007e2e10a15c06c3954c0
extern crate hassel_emu; mod debug; use debug::{DebuggingEmulator, StepResult}; use std::os::raw::c_void; use std::mem; #[no_mangle] pub fn alloc(len: usize) -> *mut c_void { let mut memory = Vec::with_capacity(len); let ptr = memory.as_mut_ptr(); mem::forget(memory); ptr as *mut c_void } #[no_mangle] pub fn dealloc(ptr: *mut c_void, len: usize) { unsafe { Vec::from_raw_parts(ptr, 0, len); } } #[no_mangle] pub fn emulator_new(rom_ptr: *mut u8, rom_length: usize) -> *mut DebuggingEmulator { let rom = if rom_length == 0x2000 { unsafe { Vec::from_raw_parts(rom_ptr, rom_length, rom_length) } } else { vec![0; 0x2000] }; let emulator = Box::new(DebuggingEmulator::new(rom)); Box::into_raw(emulator) } #[no_mangle] pub fn emulator_delete(emulator_ptr: *mut DebuggingEmulator) { let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; drop(emulator); } fn with_emu<F, R>(emulator_ptr: *mut DebuggingEmulator, func: F) -> R where F: Fn(&mut DebuggingEmulator) -> R, { let mut emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let result = func(&mut *emulator); mem::forget(emulator); return result; } #[no_mangle] pub fn emulator_reset(emulator_ptr: *mut DebuggingEmulator) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.reset(); }); } #[no_mangle] pub fn emulator_step(emulator_ptr: *mut DebuggingEmulator) -> usize { with_emu( emulator_ptr, &|emulator: &mut DebuggingEmulator| match emulator.step() { StepResult::Ok(cycles) => cycles, StepResult::HitBreakpoint(cycles, _) => cycles, }, ) } #[no_mangle] pub fn emulator_key_down(emulator_ptr: &mut DebuggingEmulator, key_code: u8) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.key_down(key_code); }); } #[no_mangle] pub fn emulator_key_up(emulator_ptr: &mut DebuggingEmulator, key_code: u8) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.key_up(key_code); }); } #[no_mangle] pub fn emulator_add_breakpoint(emulator_ptr: *mut DebuggingEmulator, address: u16) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.add_breakpoint(address); }); } #[no_mangle] pub fn emulator_remove_breakpoint(emulator_ptr: *mut DebuggingEmulator, address: u16) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.remove_breakpoint(address); }); } #[no_mangle] pub fn emulator_remove_all_breakpoints(emulator_ptr: *mut DebuggingEmulator) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.remove_all_breakpoints(); }); } #[no_mangle] pub fn emulator_play(emulator_ptr: *mut DebuggingEmulator, cycles: usize) -> usize { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { let mut cycles_run = 0; while cycles_run <= cycles { cycles_run += match emulator.step() { StepResult::Ok(cycles) => cycles, StepResult::HitBreakpoint(cycles, _pc) => { cycles_run += cycles; return cycles_run; } } } cycles_run }) } #[no_mangle] pub fn emulator_reg_a(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().a }) } #[no_mangle] pub fn emulator_reg_x(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().x }) } #[no_mangle] pub fn emulator_reg_y(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().y }) } #[no_mangle] pub fn emulator_reg_status(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().status.value() }) } #[no_mangle] pub fn emulator_reg_sp(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().sp }) } #[no_mangle] pub fn emulator_reg_pc(emulator_ptr: *mut DebuggingEmulator) -> u16 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().pc }) } #[no_mangle] pub fn emulator_get_memory(emulator_ptr: *mut DebuggingEmulator, buffer_ptr: *mut u8) { let buffer_size: usize = 0x10000; let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let mut buffer = unsafe { Vec::from_raw_parts(buffer_ptr, buffer_size, buffer_size) }; { let debug_read = emulator.cpu().memory().debug_read(); for i in 0..buffer_size { buffer[i] = debug_read.byte(i as u16); } } mem::forget(buffer); mem::forget(emulator); } #[no_mangle] pub fn emulator_get_graphics_data(emulator_ptr: *mut DebuggingEmulator, buffer_ptr: *mut u32) { let buffer_size = 640 * 480; let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let mut buffer = unsafe { Vec::from_raw_parts(buffer_ptr, buffer_size, buffer_size) }; { let graphics = emulator.graphics(); let frame_buffer = graphics.frame_buffer(); for i in 0..buffer_size { buffer[i] = frame_buffer[i]; } } mem::forget(buffer); mem::forget(emulator); }
extern crate hassel_emu; mod debug; use debug::{DebuggingEmulator, StepResult}; use std::os::raw::c_void; use std::mem; #[no_mangle] pub fn alloc(len: usize) -> *mut c_void { let mut memory = Vec::with_capacity(len); let ptr = memory.as_mut_ptr(); mem::forget(memory); ptr as *mut c_void } #[no_mangle] pub fn dealloc(ptr: *mut c_void, len: usize) { unsafe { Vec::from_raw_parts(ptr, 0, len); } } #[no_mangle] pub fn emulator_new(rom_ptr: *mut u8, rom_length: usize) -> *mut DebuggingEmulator { let rom = if rom_length == 0x2000 { unsafe { Vec::from_raw_parts(rom_ptr, rom_length, rom_length) } } else { vec![0; 0x2000] }; let emulator = Box::new(DebuggingEmulator::new(rom)); Box::into_raw(emulator) } #[no_mangle] pub fn emulator_delete(emulator_ptr: *mut DebuggingEmulator) { let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; drop(emulator); } fn with_emu<F, R>(emulator_ptr: *mut DebuggingEmulator, func: F) -> R where F: Fn(&mut DebuggingEmulator) -> R, { let mut emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let result = func(&mut *emulator); mem::forget(emulator); return result; } #[no_mangle] pub fn emulator_reset(emulator_ptr: *mut DebuggingEmulator) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.reset(); }); } #[no_mangle] pub fn emulator_step(emulator_ptr: *mut DebuggingEmulator) -> usize { with_emu( emulator_ptr, &|emulator: &mut DebuggingEmulator| match emulator.step() { StepResult::Ok(cycles) => cycles, StepResult::HitBreakpoint(cycles, _) => cycles, }, ) } #[no_mangle] pub fn emulator_key_down(emulator_ptr: &mut DebuggingEmulator, key_code: u8) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.key_down(key_code); }); } #[no_mangle] pub fn emulator_key_up(emulator_ptr: &mut DebuggingEmulator, key_code: u8) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.key_up(key_code); }); } #[no_mangle] pub fn emulator_add_breakpoint(emulator_ptr: *mut DebuggingEmulator, address: u16) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.add_breakpoint(address); }); } #[no_mangle] pub fn emulator_remove_breakpoint(emulator_ptr: *mut DebuggingEmulator, address: u16) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.remove_breakpoint(address); }); } #[no_mangle] pub fn emulator_remove_all_breakpoints(emulator_ptr: *mut DebuggingEmulator) { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.remove_all_breakpoints(); }); } #[no_mangle] pub fn emulator_play(emulator_ptr: *mut DebuggingEmulator, cycles: usize) -> usize { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { let mut cycles_run = 0; while cycles_run <= cycles { cycles_run += match emulator.step() { StepResult::Ok(cycles) => cycles, StepResult::HitBreakpoint(cycles, _pc) => { cycles_run += cycles; return cycles_run; }
Vec::from_raw_parts(buffer_ptr, buffer_size, buffer_size) }; { let debug_read = emulator.cpu().memory().debug_read(); for i in 0..buffer_size { buffer[i] = debug_read.byte(i as u16); } } mem::forget(buffer); mem::forget(emulator); } #[no_mangle] pub fn emulator_get_graphics_data(emulator_ptr: *mut DebuggingEmulator, buffer_ptr: *mut u32) { let buffer_size = 640 * 480; let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let mut buffer = unsafe { Vec::from_raw_parts(buffer_ptr, buffer_size, buffer_size) }; { let graphics = emulator.graphics(); let frame_buffer = graphics.frame_buffer(); for i in 0..buffer_size { buffer[i] = frame_buffer[i]; } } mem::forget(buffer); mem::forget(emulator); }
} } cycles_run }) } #[no_mangle] pub fn emulator_reg_a(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().a }) } #[no_mangle] pub fn emulator_reg_x(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().x }) } #[no_mangle] pub fn emulator_reg_y(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().y }) } #[no_mangle] pub fn emulator_reg_status(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().status.value() }) } #[no_mangle] pub fn emulator_reg_sp(emulator_ptr: *mut DebuggingEmulator) -> u8 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().sp }) } #[no_mangle] pub fn emulator_reg_pc(emulator_ptr: *mut DebuggingEmulator) -> u16 { with_emu(emulator_ptr, &|emulator: &mut DebuggingEmulator| { emulator.cpu().registers().pc }) } #[no_mangle] pub fn emulator_get_memory(emulator_ptr: *mut DebuggingEmulator, buffer_ptr: *mut u8) { let buffer_size: usize = 0x10000; let emulator: Box<DebuggingEmulator> = unsafe { Box::from_raw(emulator_ptr) }; let mut buffer = unsafe {
random
[ { "content": " public getMemorySlice(start: number, end: number): number[] {\n\n let memory: number[] = [];\n\n if (start < end) {\n\n this.assembly_exports.emulator_get_memory(this.emulator, this.memoryPtr);\n\n let memoryView = new Uint8Array(this.assembly_instance.expor...
Rust
src/tests.rs
duncanrhamill/cell-map
27979d40088f0459c930fa38f2638106b8191005
use nalgebra::{Point2, Vector2}; use super::*; use crate::{cell_map::Bounds, test_utils::TestLayers}; #[test] fn get_cell_positions() { let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.5, 0.5) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(5.5, 5.5) ); assert_eq!(map.index(Point2::new(0.7, 0.1)).unwrap(), Point2::new(0, 0)); assert_eq!(map.index(Point2::new(7.0, 1.0)).unwrap(), Point2::new(7, 1)); assert_eq!( map.index(Point2::new(2.6, 3.999999)).unwrap(), Point2::new(2, 3) ); assert_eq!(map.index(Point2::new(2.6, 4.0)).unwrap(), Point2::new(2, 4)); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.05, 0.05) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(0.55, 0.55) ); assert_eq!(map.index(Point2::new(0.7, 0.1)).unwrap(), Point2::new(7, 1)); assert_eq!( map.index(Point2::new(0.26, 0.3999999)).unwrap(), Point2::new(2, 3) ); assert_eq!( map.index(Point2::new(0.26, 0.4)).unwrap(), Point2::new(2, 4) ); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), position_in_parent: Vector2::new(0.5, 0.5), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.55, 0.55) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(1.05, 1.05) ); assert_eq!(map.index(Point2::new(0.7, 0.6)).unwrap(), Point2::new(2, 1)); assert_eq!( map.index(Point2::new(0.76, 0.8999999)).unwrap(), Point2::new(2, 3) ); assert_eq!( map.index(Point2::new(0.76, 0.9)).unwrap(), Point2::new(2, 4) ); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), position_in_parent: Vector2::new(0.5, 0.5), rotation_in_parent_rad: std::f64::consts::FRAC_PI_4, ..Default::default() }); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map, "trs"); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.5, 0.5707106781186547) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(0.5, 1.2778174593052023) ); assert_eq!(map.index(Point2::new(0.4, 0.7)).unwrap(), Point2::new(0, 2)); assert_eq!(map.index(Point2::new(1.0, 1.2)).unwrap(), Point2::new(8, 1)); assert_eq!( map.index(Point2::new(-0.1, 1.2)).unwrap(), Point2::new(0, 9) ); } #[test] fn test_resize() { let mut map = CellMap::<TestLayers, Option<i32>>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }, Some(1), ); let new_bounds = Bounds::new((-5, 15), (-5, 15)).unwrap(); map.resize(new_bounds); assert_eq!(map.cell_bounds(), new_bounds); assert_eq!(map.num_cells(), Vector2::new(20, 20)); for ((_, idx), &val) in map.iter().indexed().layer(TestLayers::Layer0) { if idx.x < 5 || idx.x >= 15 || idx.y < 5 || idx.y >= 15 { assert_eq!(val, None); } else { assert_eq!(val, Some(1)); } } let new_bounds = Bounds::new((8, 12), (-5, 15)).unwrap(); map.resize(new_bounds); assert_eq!(map.cell_bounds(), new_bounds); assert_eq!(map.num_cells(), Vector2::new(4, 20)); for ((_, idx), &val) in map.iter().indexed().layer(TestLayers::Layer0) { if idx.x >= 2 || idx.y < 5 || idx.y >= 15 { assert_eq!(val, None); } else { assert_eq!(val, Some(1)); } } } #[test] fn test_merge() { let mut map_a = CellMap::<TestLayers, i32>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }, 1, ); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_a, "a"); let mut last_y = 0; print!("\nA:\n "); for ((_, idx), val) in map_a.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); let map_b = CellMap::<TestLayers, i32>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((5, 15), (5, 15)).unwrap(), cell_size: Vector2::new(0.5, 0.5), rotation_in_parent_rad: std::f64::consts::FRAC_PI_4, ..Default::default() }, 2, ); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_b, "b"); let mut last_y = 0; print!("\nB:\n "); for ((_, idx), val) in map_b.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); map_a.merge(&map_b, |&a, bs| { let mut acc = a; for &b in bs { acc += b } (acc as f64 / (bs.len() as f64 + 1.0)).round() as i32 }); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_a, "merged"); let mut last_y = 0; print!("\nA + B:\n "); for ((_, idx), val) in map_a.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); }
use nalgebra::{Point2, Vector2}; use super::*; use crate::{cell_map::Bounds, test_utils::TestLayers}; #[test] fn get_cell_positions() { let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.5, 0.5) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(5.5, 5.5) ); assert_eq!(map.index(Point2::new(0.7, 0.1)).unwrap(), Point2::new(0, 0)); assert_eq!(map.index(Point2::new(7.0, 1.0)).unwrap(), Point2::new(7, 1)); assert_eq!( map.index(Point2::new(2.6, 3.999999)).unwrap(), Point2::new(2, 3) ); assert_eq!(map.index(Point2::new(2.6, 4.0)).unwrap(), Point2::new(2, 4)); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.05, 0.05) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(0.55, 0.55) ); assert_eq!(map.index(Point2::new(0.7, 0.1)).unwrap(), Point2::new(7, 1)); assert_eq!( map.index(Point2::new(0.26, 0.3999999)).unwrap(), Point2::new(2, 3) ); assert_eq!( map.index(Point2::new(0.26, 0.4)).unwrap(), Point2::new(2, 4) ); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), position_in_parent: Vector2::new(0.5, 0.5), ..Default::default() }); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.55, 0.55) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(1.05, 1.05) ); assert_eq!(map.index(Point2::new(0.7, 0.6)).unwrap(), Point2::new(2, 1)); assert_eq!( map.index(Point2::new(0.76, 0.8999999)).unwrap(), Point2::new(2, 3) ); assert_eq!( map.index(Point2::new(0.76, 0.9)).unwrap(), Point2::new(2, 4) ); let map = CellMap::<TestLayers, f64>::new(CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(0.1, 0.1), position_in_parent: Vector2::new(0.5, 0.5), rotation_in_parent_rad: std::f64::consts::FRAC_PI_4, ..Default::default() }); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map, "trs"); assert_f64_iter_eq!( map.position(Point2::new(0, 0)).unwrap(), Point2::new(0.5, 0.5707106781186547) ); assert_f64_iter_eq!( map.position(Point2::new(5, 5)).unwrap(), Point2::new(0.5, 1.2778174593052023) ); assert_eq!(map.index(Point2::new(0.4, 0.7)).unwrap(), Point2::new(0, 2)); assert_eq!(map.index(Point2::new(1.0, 1.2)).unwrap(), Point2::new(8, 1)); assert_eq!( map.index(Point2::new(-0.1, 1.2)).unwrap(), Point2::new(0, 9) ); } #[test] fn test_resize() { let mut map = CellMap::<TestLayers, Option<i32>>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }, Some(1), ); let new_bounds = Bounds::new((-5, 15), (-5, 15)).unwrap(); map.resize(new_bounds); assert_eq!(map.cell_bounds(), new_bounds); assert_eq!(map.num_cells(), Vector2::new(20, 20)); for ((_, idx), &val) in map.iter().indexed().layer(TestLayers::Layer0) { if idx.x < 5 || idx.x >= 15 || idx.y < 5 || idx.y >= 15 { assert_eq!(val, None); } else { assert_eq!(val, Some(1)); } } let new_bounds = Bounds::new((8, 12), (-5, 15)).unwrap(); map.resize(new_bounds); assert_eq!(map.cell_bounds(), new_bounds); assert_eq!(map.num_cells(), Vector2::new(4, 20));
let mut last_y = 0; print!("\nA + B:\n "); for ((_, idx), val) in map_a.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); }
for ((_, idx), &val) in map.iter().indexed().layer(TestLayers::Layer0) { if idx.x >= 2 || idx.y < 5 || idx.y >= 15 { assert_eq!(val, None); } else { assert_eq!(val, Some(1)); } } } #[test] fn test_merge() { let mut map_a = CellMap::<TestLayers, i32>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((0, 10), (0, 10)).unwrap(), cell_size: Vector2::new(1.0, 1.0), ..Default::default() }, 1, ); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_a, "a"); let mut last_y = 0; print!("\nA:\n "); for ((_, idx), val) in map_a.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); let map_b = CellMap::<TestLayers, i32>::new_from_elem( CellMapParams { cell_bounds: Bounds::new((5, 15), (5, 15)).unwrap(), cell_size: Vector2::new(0.5, 0.5), rotation_in_parent_rad: std::f64::consts::FRAC_PI_4, ..Default::default() }, 2, ); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_b, "b"); let mut last_y = 0; print!("\nB:\n "); for ((_, idx), val) in map_b.iter().layer(TestLayers::Layer0).indexed() { if last_y != idx.y { last_y = idx.y; print!("\n "); } print!("{} ", val); } println!(); map_a.merge(&map_b, |&a, bs| { let mut acc = a; for &b in bs { acc += b } (acc as f64 / (bs.len() as f64 + 1.0)).round() as i32 }); #[cfg(feature = "debug_maps")] crate::write_debug_map(&map_a, "merged");
random
[ { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"tests/layer-pass.rs\");\n\n t.compile_fail(\"tests/layer-fail.rs\");\n\n}\n", "file_path": "cell-map-macro/tests/all.rs", "rank": 0, "score": 106619.28868823935 }, { "content": "#[test]\n\nfn ...
Rust
server/src/main.rs
bigbass1997/remote64
8355a3b956b3f8139a913944db9e16781c97503e
extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clap::{AppSettings, Arg, Command}; use crossbeam_queue::SegQueue; use log::LevelFilter; use minifb::{Key, Window, WindowOptions}; use minifb::{Scale, ScaleMode}; use portaudio::DeviceIndex; use v4l::io::traits::OutputStream; use remote64_common::{Feature, Frame}; use remote64_common::util::InfCell; use remote64_common::intercom::{BroadcastNetwork, InterMessage}; use crate::sockets::SocketManager; use crate::recording::Recording; use crate::video::VideoStream; mod sockets; mod recording; mod video; const WIDTH: usize = 720; const HEIGHT: usize = 480; fn main() { let matches = Command::new("remote64-server") .version(clap::crate_version!()) .arg(Arg::new("features") .short('f') .long("feature") .takes_value(true) .multiple_occurrences(true) .possible_values(["LivePlayback", "AudioRecording", "InputHandling"]) .help("Specify a feature supported by this server. Use multiple -f/--feature args to specify multiple features.")) .arg(Arg::new("verbose") .short('v') .long("verbose") .takes_value(true) .default_missing_value("debug") .default_value("info") .possible_values(["error", "warn", "info", "debug", "trace"]) .help("Specify the console log level. Environment variable 'RUST_LOG' will override this option.")) .next_line_help(true) .setting(AppSettings::DeriveDisplayOrder) .get_matches(); let level = match std::env::var("RUST_LOG").unwrap_or(matches.value_of("verbose").unwrap_or("info").to_owned()).as_str() { "error" => LevelFilter::Error, "warn" => LevelFilter::Warn, "info" => LevelFilter::Info, "debug" => LevelFilter::Debug, "trace" => LevelFilter::Trace, _ => LevelFilter::Info }; { let mut logbuilder = remote64_common::logger::builder(); logbuilder.filter_level(level); logbuilder.init(); } let features: Vec<Feature> = matches.values_of("features").unwrap_or_default().map(|feat| Feature::from_str(feat).unwrap_or_default()).collect(); let mut intercom = BroadcastNetwork::<InterMessage>::new(); SocketManager::init(features, intercom.endpoint()); let mut window_buf: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut window = Window::new("remote64-server", WIDTH, HEIGHT, WindowOptions { borderless: false, title: false, resize: false, scale: Scale::X1, scale_mode: ScaleMode::AspectRatioStretch, topmost: false, transparency: false, none: false }).unwrap(); window.limit_update_rate(Some(Duration::from_secs_f32(1.0/60.0))); let pa = portaudio::PortAudio::new().unwrap(); let mut input_device_id = DeviceIndex(0); for device in pa.devices().unwrap() { let (idx, info) = device.unwrap(); if info.name.contains("pulse") { input_device_id = idx; } } let input_device_info = pa.device_info(input_device_id).unwrap(); let latency = input_device_info.default_low_input_latency; let input_params = portaudio::StreamParameters::<f32>::new(input_device_id, 2, true, latency); let output_device_id = pa.default_output_device().unwrap(); let output_device_info = pa.device_info(output_device_id).unwrap(); let latency = output_device_info.default_low_output_latency; let output_params = portaudio::StreamParameters::<f32>::new(output_device_id, 2, true, latency); pa.is_duplex_format_supported(input_params, output_params, 44100.0).unwrap(); let settings = portaudio::DuplexStreamSettings::new(input_params, output_params, 44100.0, 512); let recording = InfCell::new(Recording::new(WIDTH as u32, HEIGHT as u32)); let audio_recording = recording.get_mut(); let video_recording = recording.get_mut(); for _ in 0..15 { video_recording.frame(); } let manage_recording = recording.get_mut(); let recording_endpoint = intercom.endpoint(); std::thread::spawn(move || { while let Ok(msg) = recording_endpoint.recv.recv() { match msg { InterMessage::StartRecording => { info!("Recording started."); manage_recording.start(); }, InterMessage::StopRecording => { info!("Recording ended."); manage_recording.end(); }, _ => () } } info!("Recording endpoint died."); }); let audio_endpoint = intercom.endpoint(); drop(audio_endpoint.recv); let samples = Arc::new(SegQueue::<f32>::new()); let callback_samples = samples.clone(); let callback = move |portaudio::stream::DuplexCallbackArgs { in_buffer, out_buffer, frames: _, flags, time: _, }| { if !flags.is_empty() { debug!("flags: {:?}", flags); } for (output_sample, input_sample) in out_buffer.iter_mut().zip(in_buffer.iter()) { *output_sample = *input_sample; callback_samples.push(*input_sample); if audio_recording.started() { audio_recording.sample(*input_sample); } } portaudio::Continue }; let mut audio_stream = pa.open_non_blocking_stream(settings, callback).unwrap(); audio_stream.start().unwrap(); let video_endpoint = intercom.endpoint(); drop(video_endpoint.recv); std::thread::spawn(move || { intercom.start(); }); let mut video_capture = VideoStream::new().unwrap(); window_buf.fill(0); let mut socket_buf = vec![0; window_buf.len() * 3]; while window.is_open() && !window.is_key_down(Key::Escape) { let (stream_buf, _meta) = video_capture.stream.next().unwrap(); for i in (0..stream_buf.len()).step_by(2) { let r = stream_buf[i + 1] & 0b11111000; let g = ((stream_buf[i + 1] & 0b00000111) << 5) | ((stream_buf[i] & 0b11100000) >> 3); let b = (stream_buf[i] & 0b00011111) << 3; let color = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32); let i = i / 2; window_buf[i] = color; socket_buf[(i * 3) + 0] = r; socket_buf[(i * 3) + 1] = g; socket_buf[(i * 3) + 2] = b; video_recording.set_pixel_i(i as u32, r, g, b); } window.update_with_buffer(&window_buf, WIDTH, HEIGHT).unwrap(); video_recording.frame(); let len = samples.len(); let mut sample_buf = Vec::with_capacity(len); for _ in 0..len { sample_buf.push(samples.pop().unwrap()); } video_endpoint.send.try_send(InterMessage::LatestFrame(Frame::new(socket_buf.clone(), sample_buf))).unwrap_or_default(); } audio_stream.stop().unwrap(); recording.get_mut().end(); }
extern crate env_logger; #[macro_use] extern crate log; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use clap::{AppSettings, Arg, Command}; use crossbeam_queue::SegQueue; use log::LevelFilter; use minifb::{Key, Window, WindowOptions}; use minifb::{Scale, ScaleMode}; use portaudio::DeviceIndex; use v4l::io::traits::OutputStream; use remote64_common::{Feature, Frame}; use remote64_common::util::InfCell; use remote64_common::intercom::{BroadcastNetwork, InterMessage}; use crate::sockets::SocketManager; use crate::recording::Recording; use crate::video::VideoStream; mod sockets; mod recording; mod video; const WIDTH: usize = 720; const HEIGHT: usize = 480;
fn main() { let matches = Command::new("remote64-server") .version(clap::crate_version!()) .arg(Arg::new("features") .short('f') .long("feature") .takes_value(true) .multiple_occurrences(true) .possible_values(["LivePlayback", "AudioRecording", "InputHandling"]) .help("Specify a feature supported by this server. Use multiple -f/--feature args to specify multiple features.")) .arg(Arg::new("verbose") .short('v') .long("verbose") .takes_value(true) .default_missing_value("debug") .default_value("info") .possible_values(["error", "warn", "info", "debug", "trace"]) .help("Specify the console log level. Environment variable 'RUST_LOG' will override this option.")) .next_line_help(true) .setting(AppSettings::DeriveDisplayOrder) .get_matches(); let level = match std::env::var("RUST_LOG").unwrap_or(matches.value_of("verbose").unwrap_or("info").to_owned()).as_str() { "error" => LevelFilter::Error, "warn" => LevelFilter::Warn, "info" => LevelFilter::Info, "debug" => LevelFilter::Debug, "trace" => LevelFilter::Trace, _ => LevelFilter::Info }; { let mut logbuilder = remote64_common::logger::builder(); logbuilder.filter_level(level); logbuilder.init(); } let features: Vec<Feature> = matches.values_of("features").unwrap_or_default().map(|feat| Feature::from_str(feat).unwrap_or_default()).collect(); let mut intercom = BroadcastNetwork::<InterMessage>::new(); SocketManager::init(features, intercom.endpoint()); let mut window_buf: Vec<u32> = vec![0; WIDTH * HEIGHT]; let mut window = Window::new("remote64-server", WIDTH, HEIGHT, WindowOptions { borderless: false, title: false, resize: false, scale: Scale::X1, scale_mode: ScaleMode::AspectRatioStretch, topmost: false, transparency: false, none: false }).unwrap(); window.limit_update_rate(Some(Duration::from_secs_f32(1.0/60.0))); let pa = portaudio::PortAudio::new().unwrap(); let mut input_device_id = DeviceIndex(0); for device in pa.devices().unwrap() { let (idx, info) = device.unwrap(); if info.name.contains("pulse") { input_device_id = idx; } } let input_device_info = pa.device_info(input_device_id).unwrap(); let latency = input_device_info.default_low_input_latency; let input_params = portaudio::StreamParameters::<f32>::new(input_device_id, 2, true, latency); let output_device_id = pa.default_output_device().unwrap(); let output_device_info = pa.device_info(output_device_id).unwrap(); let latency = output_device_info.default_low_output_latency; let output_params = portaudio::StreamParameters::<f32>::new(output_device_id, 2, true, latency); pa.is_duplex_format_supported(input_params, output_params, 44100.0).unwrap(); let settings = portaudio::DuplexStreamSettings::new(input_params, output_params, 44100.0, 512); let recording = InfCell::new(Recording::new(WIDTH as u32, HEIGHT as u32)); let audio_recording = recording.get_mut(); let video_recording = recording.get_mut(); for _ in 0..15 { video_recording.frame(); } let manage_recording = recording.get_mut(); let recording_endpoint = intercom.endpoint(); std::thread::spawn(move || { while let Ok(msg) = recording_endpoint.recv.recv() { match msg { InterMessage::StartRecording => { info!("Recording started."); manage_recording.start(); }, InterMessage::StopRecording => { info!("Recording ended."); manage_recording.end(); }, _ => () } } info!("Recording endpoint died."); }); let audio_endpoint = intercom.endpoint(); drop(audio_endpoint.recv); let samples = Arc::new(SegQueue::<f32>::new()); let callback_samples = samples.clone(); let callback = move |portaudio::stream::DuplexCallbackArgs { in_buffer, out_buffer, frames: _, flags, time: _, }| { if !flags.is_empty() { debug!("flags: {:?}", flags); } for (output_sample, input_sample) in out_buffer.iter_mut().zip(in_buffer.iter()) { *output_sample = *input_sample; callback_samples.push(*input_sample); if audio_recording.started() { audio_recording.sample(*input_sample); } } portaudio::Continue }; let mut audio_stream = pa.open_non_blocking_stream(settings, callback).unwrap(); audio_stream.start().unwrap(); let video_endpoint = intercom.endpoint(); drop(video_endpoint.recv); std::thread::spawn(move || { intercom.start(); }); let mut video_capture = VideoStream::new().unwrap(); window_buf.fill(0); let mut socket_buf = vec![0; window_buf.len() * 3]; while window.is_open() && !window.is_key_down(Key::Escape) { let (stream_buf, _meta) = video_capture.stream.next().unwrap(); for i in (0..stream_buf.len()).step_by(2) { let r = stream_buf[i + 1] & 0b11111000; let g = ((stream_buf[i + 1] & 0b00000111) << 5) | ((stream_buf[i] & 0b11100000) >> 3); let b = (stream_buf[i] & 0b00011111) << 3; let color = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32); let i = i / 2; window_buf[i] = color; socket_buf[(i * 3) + 0] = r; socket_buf[(i * 3) + 1] = g; socket_buf[(i * 3) + 2] = b; video_recording.set_pixel_i(i as u32, r, g, b); } window.update_with_buffer(&window_buf, WIDTH, HEIGHT).unwrap(); video_recording.frame(); let len = samples.len(); let mut sample_buf = Vec::with_capacity(len); for _ in 0..len { sample_buf.push(samples.pop().unwrap()); } video_endpoint.send.try_send(InterMessage::LatestFrame(Frame::new(socket_buf.clone(), sample_buf))).unwrap_or_default(); } audio_stream.stop().unwrap(); recording.get_mut().end(); }
function_block-full_function
[ { "content": " }\n\n \n\n /// Attempts to resize the resolution of the captured video.\n\n /// \n\n /// Returns the resulting format.\n\n pub fn resize(&mut self, width: u32, height: u32) -> Format {\n\n let mut fmt = self.dev.format().unwrap();\n\n fmt.width = width;\n\n ...
Rust
server/entity/src/object/falling_block.rs
nobbele/feather
5599851800624086fd1b049bdd1894b2aa637a03
use feather_core::blocks::{BlockId, SimplifiedBlockKind}; use feather_core::entitymeta::{EntityMetadata, META_INDEX_FALLING_BLOCK_SPAWN_POSITION}; use feather_core::network::packets::{Effect, SpawnObject}; use feather_core::network::Packet; use feather_core::util::{BlockPosition, Position}; use feather_server_types::{ BlockUpdateCause, BumpVec, EntityLandEvent, EntitySpawnEvent, Game, NetworkId, PhysicsBuilder, SpawnPacketCreator, Uuid, Velocity, }; use feather_server_util::{ degrees_to_stops, protocol_velocity, BlockNotifyBlock, BlockNotifyFallingBlock, BlockNotifyPosition, }; use fecs::{component, EntityBuilder, EntityRef, IntoQuery, Read, World}; #[derive(Copy, Clone, Debug)] pub struct FallingBlock; #[derive(Copy, Clone, Debug)] pub struct FallingBlockType(pub BlockId); #[fecs::system] pub fn spawn_falling_blocks(game: &mut Game, world: &mut World) { let mut actions = BumpVec::new_in(game.bump()); actions.extend( <(Read<BlockNotifyBlock>, Read<BlockNotifyPosition>)>::query() .filter(component::<BlockNotifyFallingBlock>()) .iter_entities(world.inner()) .map(|(entity, (block, position))| { let builder = if game.block_at(position.0 - BlockPosition::new(0, 1, 0)) == Some(BlockId::air()) { Some( create(block.0, position.0) .with(position.0.position() + position!(0.0, -0.5, 0.0)), ) } else { None }; (entity, builder, position.0) }), ); for (entity_to_delete, entity_builder, block_to_clear) in actions { world.despawn(entity_to_delete); if let Some(entity_builder) = entity_builder { let created_entity = entity_builder.build().spawn_in(world); game.handle( world, EntitySpawnEvent { entity: created_entity, }, ); game.set_block_at( world, block_to_clear, BlockId::air(), BlockUpdateCause::Unknown, ); } } } #[fecs::event_handler] pub fn on_entity_land_remove_falling_block( event: &EntityLandEvent, game: &mut Game, world: &mut World, ) { if let Some(block) = world .try_get::<FallingBlockType>(event.entity) .map(|block| block.0) { let pos = event.pos.block(); game.set_block_at(world, pos, block, BlockUpdateCause::Unknown); game.despawn(event.entity, world); if block.simplified_kind() == SimplifiedBlockKind::Anvil { game.broadcast_chunk_update( world, Effect { effect_id: 1031, location: pos, data: 0, disable_relative_volume: false, }, event.pos.chunk(), None, ); } } } pub fn create(ty: BlockId, spawn_pos: BlockPosition) -> EntityBuilder { let meta = EntityMetadata::entity_base().with(META_INDEX_FALLING_BLOCK_SPAWN_POSITION, spawn_pos); crate::base() .with(FallingBlock) .with(FallingBlockType(ty)) .with(SpawnPacketCreator(&create_spawn_packet)) .with( PhysicsBuilder::new() .bbox(0.98, 0.98, 0.98) .drag(0.98) .gravity(-0.04) .build(), ) .with(meta) } fn create_spawn_packet(accessor: &EntityRef) -> Box<dyn Packet> { let data = i32::from(accessor.get::<FallingBlockType>().0.vanilla_id()); let position = accessor.get::<Position>(); let entity_id = accessor.get::<NetworkId>().0; let velocity = accessor.get::<Velocity>().0; let (velocity_x, velocity_y, velocity_z) = protocol_velocity(velocity); let packet = SpawnObject { entity_id, object_uuid: Uuid::new_v4(), ty: 70, x: position.x, y: position.y, z: position.z, pitch: degrees_to_stops(position.pitch), yaw: degrees_to_stops(position.yaw), data, velocity_x, velocity_y, velocity_z, }; Box::new(packet) }
use feather_core::blocks::{BlockId, SimplifiedBlockKind}; use feather_core::entitymeta::{EntityMetadata, META_INDEX_FALLING_BLOCK_SPAWN_POSITION}; use feather_core::network::packets::{Effect, SpawnObject}; use feather_core::network::Packet; use feather_core::util::{BlockPosition, Position}; use feather_server_types::{ BlockUpdateCause, BumpVec, EntityLandEvent, EntitySpawnEvent, Game, NetworkId, PhysicsBuilder, SpawnPacketCreator, Uuid, Velocity, }; use feather_server_util::{ degrees_to_stops, protocol_velocity, BlockNotifyBlock, BlockNotifyFallingBlock, BlockNotifyPosition, }; use fecs::{component, EntityBuilder, EntityRef, IntoQuery, Read, World}; #[derive(Copy, Clone, Debug)] pub struct FallingBlock; #[derive(Copy, Clone, Debug)] pub struct FallingBlockType(pub BlockId); #[fecs::system] pub fn spawn_falling_blocks(game: &mut Game, world: &mut World) { let mut actions = BumpVec::new_in(game.bump()); actions.extend( <(Read<BlockNotifyBlock>, Read<BlockNotifyPosition>)>::query() .filter(component::<BlockNotifyFallingBlock>()) .iter_entities(world.inner()) .map(|(entity, (block, position))| { let builder = if game.block_at(position.0 - BlockPosition::new(0, 1, 0)) == Some(BlockId::air()) { Some( create(block.0, position.0) .with(position.0.position() + position!(0.0, -0.5, 0.0)), ) } else { None }; (entity, builder, position.0) }), ); for (entity_to_delete, entity_builder, block_to_clear) in actions { world.despawn(entity_to_delete); if let Some(entity_builder) = entity_builder { let created_entity = entity_builder.build().spawn_in(world); game.handle( world, EntitySpawnEvent { entity: created_entity, }, ); game.set_block_at( world, block_to_clear, BlockId::air(), BlockUpdateCause::Unknown, ); } } } #[fecs::event_handler] pub fn on_entity_land_remove_falling_block( event: &EntityLandEvent, game: &mut Game, world: &mut World, ) { if let Some(block) = world .try_get::<FallingBlockType>(event.entity) .map(|block| block.0) { let pos = event.pos.block(); game.set_block_at(world, pos, block, BlockUpdateCause::Unknown); game.despawn(event.entity, world); if block.simplified_kind() == SimplifiedBlockKind::Anvil { game.broadcast_chunk_update( world, Effect { effect_id: 1031, location: pos, data: 0, disable_relative_volume: false, }, event.pos.chunk(), None, ); } } } pub fn create(ty: BlockId, spawn_pos: BlockPosition) -> EntityBuilder { let meta =
fn create_spawn_packet(accessor: &EntityRef) -> Box<dyn Packet> { let data = i32::from(accessor.get::<FallingBlockType>().0.vanilla_id()); let position = accessor.get::<Position>(); let entity_id = accessor.get::<NetworkId>().0; let velocity = accessor.get::<Velocity>().0; let (velocity_x, velocity_y, velocity_z) = protocol_velocity(velocity); let packet = SpawnObject { entity_id, object_uuid: Uuid::new_v4(), ty: 70, x: position.x, y: position.y, z: position.z, pitch: degrees_to_stops(position.pitch), yaw: degrees_to_stops(position.yaw), data, velocity_x, velocity_y, velocity_z, }; Box::new(packet) }
EntityMetadata::entity_base().with(META_INDEX_FALLING_BLOCK_SPAWN_POSITION, spawn_pos); crate::base() .with(FallingBlock) .with(FallingBlockType(ty)) .with(SpawnPacketCreator(&create_spawn_packet)) .with( PhysicsBuilder::new() .bbox(0.98, 0.98, 0.98) .drag(0.98) .gravity(-0.04) .build(), ) .with(meta) }
function_block-function_prefix_line
[ { "content": "#[fecs::event_handler]\n\npub fn on_block_break_drop_loot(event: &BlockUpdateEvent, game: &mut Game, world: &mut World) {\n\n if event.old.is_air() || !event.new.is_air() {\n\n return;\n\n }\n\n\n\n let item = match event.cause {\n\n feather_server_types::BlockUpdateCause::E...
Rust
src/storage/src/range_map.rs
vinimin/fluvio
142c050a2f1aaa83aeda19705fedd670fffaf1a1
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Excluded; use std::ops::Bound::Included; use std::ffi::OsStr; use log::debug; use log::trace; use log::error; use kf_protocol::api::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::ConfigOption; use crate::util::log_path_get_offset; #[derive(Debug)] pub(crate) struct SegmentList { segments: BTreeMap<Offset, ReadSegment>, max_base_offset: Offset, min_base_offset: Offset, } impl SegmentList { pub fn new() -> Self { SegmentList { segments: BTreeMap::new(), max_base_offset: 0, min_base_offset: -1, } } pub async fn from_dir( option: &ConfigOption, ) -> Result<(SegmentList, Option<Offset>), StorageError> { let dirs = option.base_dir.read_dir()?; debug!("reading segments at: {:#?}", dirs); let files: Vec<_> = dirs.into_iter().filter_map(|entry| entry.ok()).collect(); let mut offsets: Vec<Offset> = vec![]; for entry in files { if let Ok(metadata) = entry.metadata() { if metadata.is_file() { let path = entry.path(); trace!("scanning file: {:#?}", path); if path.extension() == Some(OsStr::new("log")) { if let Ok(offset) = log_path_get_offset(&path) { trace!("detected valid log: {}", offset); offsets.push(offset); /* match Segment::open(offset,option).await { Ok(segment) => segments.add_segment(segment), Err(err) => error!("error opening segment: {:#?}",err) } } else { debug!("not log, skipping: {:#?}",path); */ } } } } } offsets.sort(); let last_offset = offsets.pop(); let mut segments = Self::new(); for offset in offsets { match ReadSegment::open_for_read(offset, option).await { Ok(segment) => segments.add_segment(segment), Err(err) => error!("error opening segment: {:#?}", err), } } Ok((segments, last_offset)) } #[allow(dead_code)] pub fn len(&self) -> usize { self.segments.len() } #[allow(dead_code)] pub fn max_offset(&self) -> Offset { self.max_base_offset } pub fn min_offset(&self) -> Offset { self.min_base_offset } pub fn add_segment(&mut self, segment: ReadSegment) { let base_offset = segment.get_base_offset(); debug!("inserting segment base: {}", base_offset); self.max_base_offset = max(self.max_base_offset, base_offset); self.min_base_offset = if self.min_base_offset < 0 { base_offset } else { min(self.min_base_offset, base_offset) }; &self.segments.insert(segment.get_base_offset(), segment); } #[allow(dead_code)] pub fn get_segment(&self, offset: Offset) -> Option<&ReadSegment> { self.segments.get(&offset) } pub fn find_segment(&self, offset: Offset) -> Option<(&Offset, &ReadSegment)> { (&self.segments) .range((Excluded(offset - self.max_base_offset), Included(offset))) .next_back() } } #[cfg(test)] mod tests { use std::env::temp_dir; use std::path::PathBuf; use flv_future_core::test_async; use kf_protocol::api::Offset; use crate::fixture::ensure_new_dir; use super::SegmentList; use crate::StorageError; use crate::segment::MutableSegment; use crate::segment::ReadSegment; use crate::ConfigOption; use crate::fixture::create_batch; const TEST_SEGMENT_DIR: &str = "segmentlist-test"; async fn create_segment( option: &ConfigOption, start: Offset, _offsets: Offset, ) -> Result<ReadSegment, StorageError> { let mut mut_segment = MutableSegment::create(start, option).await?; mut_segment.send(create_batch()).await?; let segment = mut_segment.convert_to_segment().await?; Ok(segment) } fn default_option(base_dir: PathBuf) -> ConfigOption { ConfigOption { segment_max_bytes: 100, base_dir, index_max_bytes: 1000, index_max_interval_bytes: 0, ..Default::default() } } #[test_async] async fn test_find_segment() -> Result<(), StorageError> { let rep_dir = temp_dir().join(TEST_SEGMENT_DIR); ensure_new_dir(&rep_dir)?; let mut list = SegmentList::new(); let option = default_option(rep_dir); list.add_segment(create_segment(&option, 0, 500).await?); list.add_segment(create_segment(&option, 500, 2000).await?); list.add_segment(create_segment(&option, 2000, 1000).await?); list.add_segment(create_segment(&option, 3000, 2000).await?); let index = list.find_segment(1500); assert!(index.is_some()); let (pos, _) = index.unwrap(); assert_eq!(*pos, 500); Ok(()) } const TEST_READ_DIR: &str = "segmentlist-read-many"; #[test_async] async fn test_segment_read_many() -> Result<(), StorageError> { let rep_dir = temp_dir().join(TEST_READ_DIR); ensure_new_dir(&rep_dir)?; let option = default_option(rep_dir); create_segment(&option, 10, 500).await?; create_segment(&option, 500, 2000).await?; create_segment(&option, 2000, 1000).await?; create_segment(&option, 3000, 2000).await?; let (segments, last_offset_res) = SegmentList::from_dir(&option).await?; assert_eq!(segments.len(), 3); assert_eq!(segments.max_offset(), 2000); assert_eq!(segments.min_offset(), 10); let segment1 = segments.get_segment(10).expect("should have segment at 0 "); assert_eq!(segment1.get_base_offset(), 10); let last_offset = last_offset_res.expect("last segment should be there"); assert_eq!(last_offset, 3000); let segment2 = segments .get_segment(500) .expect("should have segment at 500"); assert_eq!(segment2.get_base_offset(), 500); Ok(()) } const TEST_EMPTY_DIR: &str = "segmentlist-read-empty"; #[test_async] async fn test_segment_read_empty() -> Result<(), StorageError> { let rep_dir = temp_dir().join(TEST_EMPTY_DIR); ensure_new_dir(&rep_dir)?; let option = default_option(rep_dir); let (segments, last_segment) = SegmentList::from_dir(&option).await?; assert_eq!(segments.len(), 0); assert!(last_segment.is_none()); Ok(()) } }
use std::cmp::max; use std::cmp::min; use std::collections::BTreeMap; use std::ops::Bound::Excluded; use std::ops::Bound::Included; use std::ffi::OsStr; use log::debug; use log::trace; use log::error; use kf_protocol::api::Offset; use crate::segment::ReadSegment; use crate::StorageError; use crate::ConfigOption; use crate::util::log_path_get_offset; #[derive(Debug)] pub(crate) struct SegmentList { segments: BTreeMap<Offset, ReadSegment>, max_base_offset: Offset, min_base_offset: Offset, } impl SegmentList { pub fn new() -> Self { SegmentList { segments: BTreeMap::new(), max_base_offset: 0, min_base_offset: -1, } } pub async fn from_dir( option: &ConfigOption, ) -> Result<(SegmentList, Option<Offset>), StorageError> { let dirs = option.base_dir.read_dir()?; debug!("reading segments at: {:#?}", dirs); let files: Vec<_> = dirs.into_iter().filter_map(|entry| entry.ok()).collect(); let mut offsets: Vec<Offset> = vec![]; for entry in files { if let Ok(metadata) = entry.metadata() { if metadata.is_file() { let path = entry.path(); trace!("scanning file: {:#?}", path); if path.extension() == Some(OsStr::new("log")) { if let Ok(offset) = log_path_get_offset(&path) { trace!("detected valid log: {}", offset); offsets.push(offset); /* match Segment::open(offset,option).await { Ok(segment) => segments.add_segment(segment), Err(err) => error!("error opening segment: {:#?}",err) } } else { debug!("not log, skipping: {:#?}",path); */ } } } } } offsets.sort(); let last_offset = offsets.pop(); let mut segments = Self::new(); for offset in offsets { match ReadSegment::open_for_read(offset, option).await { Ok(segment) => segments.add_segment(segment), Err(err) => error!("error opening segment: {:#?}", err), } } Ok((segments, last_offset)) } #[allow(dead_code)] pub fn len(&self) -> usize { self.segments.len() } #[allow(dead_code)] pub fn max_offset(&self) -> Offset { self.max_base_offset } pub fn min_offset(&self) -> Offset { self.min_base_offset } pub fn add_segment(&mut self, segment: ReadSegment) { let base_offset = segment.get_base_offset(); debug!("inserting segment base: {}", base_offset); self.max_base_offset = max(self.max_base_offset, base_offset); self.min_base_offset = if self.min_base_offset < 0 { base_offset } else { min(self.min_base_offset, base_offset) }; &self.segments.insert(segment.get_base_offset(), segment); } #[allow(dead_code)] pub fn get_segment(&self, offset: Offset) -> Option<&ReadSegment> { self.segments.get(&offset) } pub fn find_segment(&self, offset: Offset) -> Option<(&Offset, &ReadSegment)> { (&self.segments) .range((Excluded(offset - self.max_base_offset), Included(offset))) .next_back() } } #[cfg(test)] mod tests { use std::env::temp_dir; use std::path::PathBuf; use flv_future_core::test_async; use kf_protocol::api::Offset; use crate::fixture::ensure_new_dir; use super::SegmentList; use crate::StorageError; use crate::segment::MutableSegment; use crate::segment::ReadSegment; use crate::ConfigOption; use crate::fixture::create_batch; const TEST_SEGMENT_DIR: &str = "segmentlist-test"; async fn create_segment( option: &ConfigOption, start: Offset, _offsets: Offset, ) -> Result<ReadSegment, StorageError> { let mut mut_segment = MutableSegment::create(start, option).await?; mut_segment.send(create_batch()).await?; let segment = mut_segment.convert_to_segment().await?; Ok(segment) } fn default_option(base_dir: PathBuf) -> ConfigOption { ConfigOption { segment_max_bytes: 100, base_dir, index_max_bytes: 1000, index_max_interval_bytes: 0, ..Default::default() } } #[test_async] async fn test_find_segment() -> Result<(), StorageError> { let rep_dir = temp_dir().join(TEST_SEGMENT_DIR); ensure_new_dir(&rep_dir)?; let mut list = SegmentList::new(); let option = default_option(rep_dir); list.add_segment(create_segment(&option, 0, 500).await?); list.add_segment(create_segment(&option, 500, 2000).await?); list.add_segment(create_segment(&option, 2000, 1000).await?); list.add_seg
ult<(), StorageError> { let rep_dir = temp_dir().join(TEST_EMPTY_DIR); ensure_new_dir(&rep_dir)?; let option = default_option(rep_dir); let (segments, last_segment) = SegmentList::from_dir(&option).await?; assert_eq!(segments.len(), 0); assert!(last_segment.is_none()); Ok(()) } }
ment(create_segment(&option, 3000, 2000).await?); let index = list.find_segment(1500); assert!(index.is_some()); let (pos, _) = index.unwrap(); assert_eq!(*pos, 500); Ok(()) } const TEST_READ_DIR: &str = "segmentlist-read-many"; #[test_async] async fn test_segment_read_many() -> Result<(), StorageError> { let rep_dir = temp_dir().join(TEST_READ_DIR); ensure_new_dir(&rep_dir)?; let option = default_option(rep_dir); create_segment(&option, 10, 500).await?; create_segment(&option, 500, 2000).await?; create_segment(&option, 2000, 1000).await?; create_segment(&option, 3000, 2000).await?; let (segments, last_offset_res) = SegmentList::from_dir(&option).await?; assert_eq!(segments.len(), 3); assert_eq!(segments.max_offset(), 2000); assert_eq!(segments.min_offset(), 10); let segment1 = segments.get_segment(10).expect("should have segment at 0 "); assert_eq!(segment1.get_base_offset(), 10); let last_offset = last_offset_res.expect("last segment should be there"); assert_eq!(last_offset, 3000); let segment2 = segments .get_segment(500) .expect("should have segment at 500"); assert_eq!(segment2.get_base_offset(), 500); Ok(()) } const TEST_EMPTY_DIR: &str = "segmentlist-read-empty"; #[test_async] async fn test_segment_read_empty() -> Res
random
[ { "content": "/// given parent directory, base offset, extension, generate path\n\npub fn generate_file_name<P>(parent_dir: P, base_offset: Offset, extension: &str) -> PathBuf\n\n where P: AsRef<Path>\n\n {\n\n\n\n let mut file = parent_dir.as_ref().join(format!(\"{:020}\",base_offset));\n\n file.set_e...
Rust
src/dfinity.rs
Zondax/ledger-dfinity-rs
af9f87cade48b3c5ad03e35ef319b9d0e42d5f04
/******************************************************************************* * (c) 2020 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #![deny(warnings, trivial_casts, trivial_numeric_casts)] #![deny(unused_import_braces, unused_qualifications)] #![deny(missing_docs)] use std::str; use ledger_transport::{APDUCommand, APDUErrorCodes, APDUTransport}; use ledger_zondax_generic::{ map_apdu_error_description, AppInfo, ChunkPayloadType, DeviceInfo, LedgerAppError, Version, }; use log::info; use zx_bip44::BIP44Path; const INS_GET_ADDR: u8 = 0x01; const INS_SIGN: u8 = 0x02; const PK_LEN: usize = 65; const ADDR_LEN: usize = 32; const PRINCIPAL_LEN: usize = 29; const ADDR_TEXT_LEN: usize = 20; const PREHASH_LEN: usize = 43; const SIG_LEN: usize = 64; const CLA_DFINITY: u8 = 0x11; pub struct DfinityApp { pub(crate) apdu_transport: APDUTransport, pub(crate) cla: u8, } pub enum AppMode { Standard = 0, Testing = 1, } type PublicKey = [u8; PK_LEN]; type Principal = [u8; PRINCIPAL_LEN]; type Address = [u8; ADDR_LEN]; pub struct DfinityAddress { pub public_key: PublicKey, pub principal: Principal, pub address: Address, pub principal_textual: String, } pub struct Signature { pub pre_signature_hash: [u8; PREHASH_LEN], pub rs: [u8; SIG_LEN], } impl DfinityApp { pub fn new(apdu_transport: APDUTransport) -> Self { DfinityApp { apdu_transport, cla: CLA_DFINITY, } } pub async fn get_version(&self) -> Result<Version, LedgerAppError> { ledger_zondax_generic::get_version(self.cla, &self.apdu_transport).await } pub async fn get_app_info(&self) -> Result<AppInfo, LedgerAppError> { ledger_zondax_generic::get_app_info(&self.apdu_transport).await } pub async fn get_device_info(&self) -> Result<DeviceInfo, LedgerAppError> { ledger_zondax_generic::get_device_info(&self.apdu_transport).await } pub async fn get_address( &self, path: &BIP44Path, require_confirmation: bool, ) -> Result<DfinityAddress, LedgerAppError> { let serialized_path = path.serialize(); let p1 = if require_confirmation { 1 } else { 0 }; let command = APDUCommand { cla: self.cla, ins: INS_GET_ADDR, p1, p2: 0x00, data: serialized_path, }; match self.apdu_transport.exchange(&command).await { Ok(response) => { if response.retcode != APDUErrorCodes::NoError as u16 { info!("get_address: retcode={:X?}", response.retcode); return Err(LedgerAppError::AppSpecific( response.retcode, map_apdu_error_description(response.retcode).to_string(), )); } if response.data.len() < PK_LEN + ADDR_LEN + ADDR_TEXT_LEN { return Err(LedgerAppError::InvalidPK); } let mut address = DfinityAddress { public_key: [0; PK_LEN], principal: [0; PRINCIPAL_LEN], address: [0; ADDR_LEN], principal_textual: "".to_string(), }; address.public_key.copy_from_slice(&response.data[..PK_LEN]); address .principal .copy_from_slice(&response.data[PK_LEN..PK_LEN + PRINCIPAL_LEN]); address.address.copy_from_slice( &response.data[PK_LEN + PRINCIPAL_LEN..PK_LEN + PRINCIPAL_LEN + ADDR_LEN], ); address.principal_textual = str::from_utf8(&response.data[PK_LEN + PRINCIPAL_LEN + ADDR_LEN..]) .map_err(|_e| LedgerAppError::Utf8)? .to_owned(); address.principal_textual = address .principal_textual .chars() .enumerate() .flat_map(|(i, c)| { if i != 0 && i % 5 == 0 { Some('-') } else { None } .into_iter() .chain(std::iter::once(c)) }) .collect::<String>(); Ok(address) } Err(e) => Err(LedgerAppError::TransportError(e)), } } pub async fn sign( &self, path: &BIP44Path, message: &[u8], ) -> Result<Signature, LedgerAppError> { let serialized_path = path.serialize(); let start_command = APDUCommand { cla: self.cla, ins: INS_SIGN, p1: ChunkPayloadType::Init as u8, p2: 0x00, data: serialized_path, }; let response = ledger_zondax_generic::send_chunks(&self.apdu_transport, &start_command, &message) .await?; if response.data.is_empty() && response.retcode == APDUErrorCodes::NoError as u16 { return Err(LedgerAppError::NoSignature); } if response.data.len() <= PREHASH_LEN + SIG_LEN + 2 { return Err(LedgerAppError::InvalidSignature); } let mut sig: Signature = Signature { pre_signature_hash: [0; PREHASH_LEN], rs: [0; SIG_LEN], }; sig.pre_signature_hash .copy_from_slice(&response.data[..PREHASH_LEN]); sig.rs .copy_from_slice(&response.data[PREHASH_LEN..PREHASH_LEN + SIG_LEN]); Ok(sig) } }
/******************************************************************************* * (c) 2020 Zondax GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #![deny(warnings, trivial_casts, trivial_numeric_casts)] #![deny(unused_import_braces, unused_qualifications)] #![deny(missing_docs)] use std::str; use ledger_transport::{APDUCommand, APDUErrorCodes, APDUTransport}; use ledger_zondax_generic::{ map_apdu_error_description, AppInfo, ChunkPayloadType, DeviceInfo, LedgerAppError, Version, }; use log::info; use zx_bip44::BIP44Path; const INS_GET_ADDR: u8 = 0x01; const INS_SIGN: u8 = 0x02; const PK_LEN: usize = 65; const ADDR_LEN: usize = 32; const PRINCIPAL_LEN: usize = 29; const ADDR_TEXT_LEN: usize = 20; const PREHASH_LEN: usize = 43; const SIG_LEN: usize = 64; const CLA_DFINITY: u8 = 0x11; pub struct DfinityApp { pub(crate) apdu_transport: APDUTransport, pub(crate) cla: u8, } pub enum AppMode { Standard = 0, Testing = 1, } type PublicKey = [u8; PK_LEN]; type Principal = [u8; PRINCIPAL_LEN]; type Address = [u8; ADDR_LEN]; pub struct DfinityAddress { pub public_key: PublicKey, pub principal: Principal, pub address: Address, pub principal_textual: String, } pub struct Signature { pub pre_signature_hash: [u8; PREHASH_LEN],
it as u8, p2: 0x00, data: serialized_path, }; let response = ledger_zondax_generic::send_chunks(&self.apdu_transport, &start_command, &message) .await?; if response.data.is_empty() && response.retcode == APDUErrorCodes::NoError as u16 { return Err(LedgerAppError::NoSignature); } if response.data.len() <= PREHASH_LEN + SIG_LEN + 2 { return Err(LedgerAppError::InvalidSignature); } let mut sig: Signature = Signature { pre_signature_hash: [0; PREHASH_LEN], rs: [0; SIG_LEN], }; sig.pre_signature_hash .copy_from_slice(&response.data[..PREHASH_LEN]); sig.rs .copy_from_slice(&response.data[PREHASH_LEN..PREHASH_LEN + SIG_LEN]); Ok(sig) } }
pub rs: [u8; SIG_LEN], } impl DfinityApp { pub fn new(apdu_transport: APDUTransport) -> Self { DfinityApp { apdu_transport, cla: CLA_DFINITY, } } pub async fn get_version(&self) -> Result<Version, LedgerAppError> { ledger_zondax_generic::get_version(self.cla, &self.apdu_transport).await } pub async fn get_app_info(&self) -> Result<AppInfo, LedgerAppError> { ledger_zondax_generic::get_app_info(&self.apdu_transport).await } pub async fn get_device_info(&self) -> Result<DeviceInfo, LedgerAppError> { ledger_zondax_generic::get_device_info(&self.apdu_transport).await } pub async fn get_address( &self, path: &BIP44Path, require_confirmation: bool, ) -> Result<DfinityAddress, LedgerAppError> { let serialized_path = path.serialize(); let p1 = if require_confirmation { 1 } else { 0 }; let command = APDUCommand { cla: self.cla, ins: INS_GET_ADDR, p1, p2: 0x00, data: serialized_path, }; match self.apdu_transport.exchange(&command).await { Ok(response) => { if response.retcode != APDUErrorCodes::NoError as u16 { info!("get_address: retcode={:X?}", response.retcode); return Err(LedgerAppError::AppSpecific( response.retcode, map_apdu_error_description(response.retcode).to_string(), )); } if response.data.len() < PK_LEN + ADDR_LEN + ADDR_TEXT_LEN { return Err(LedgerAppError::InvalidPK); } let mut address = DfinityAddress { public_key: [0; PK_LEN], principal: [0; PRINCIPAL_LEN], address: [0; ADDR_LEN], principal_textual: "".to_string(), }; address.public_key.copy_from_slice(&response.data[..PK_LEN]); address .principal .copy_from_slice(&response.data[PK_LEN..PK_LEN + PRINCIPAL_LEN]); address.address.copy_from_slice( &response.data[PK_LEN + PRINCIPAL_LEN..PK_LEN + PRINCIPAL_LEN + ADDR_LEN], ); address.principal_textual = str::from_utf8(&response.data[PK_LEN + PRINCIPAL_LEN + ADDR_LEN..]) .map_err(|_e| LedgerAppError::Utf8)? .to_owned(); address.principal_textual = address .principal_textual .chars() .enumerate() .flat_map(|(i, c)| { if i != 0 && i % 5 == 0 { Some('-') } else { None } .into_iter() .chain(std::iter::once(c)) }) .collect::<String>(); Ok(address) } Err(e) => Err(LedgerAppError::TransportError(e)), } } pub async fn sign( &self, path: &BIP44Path, message: &[u8], ) -> Result<Signature, LedgerAppError> { let serialized_path = path.serialize(); let start_command = APDUCommand { cla: self.cla, ins: INS_SIGN, p1: ChunkPayloadType::In
random
[ { "content": "/// Create a new connection to a dfinity app\n\npub fn new_dfinity_app(apdu_transport: APDUTransport) -> DfinityApp {\n\n DfinityApp::new(apdu_transport)\n\n}\n", "file_path": "src/lib.rs", "rank": 3, "score": 34796.735529721744 }, { "content": "/****************************...
Rust
src/connectivity/network/ping3/src/tests/mod.rs
wwjiang007/fuchsia-1
0db66b52b5bcd3e27c8b8c2163925309e8522f94
mod integration_tests; use fidl::endpoints::DiscoverableProtocolMarker as _; use fidl_fuchsia_net as fnet; use fidl_fuchsia_net_icmp as fnet_icmp; use fidl_fuchsia_net_stack as fnet_stack; use fidl_fuchsia_net_stack_ext::FidlReturn as _; use fidl_fuchsia_netemul_environment as netemul_environment; use fuchsia_zircon as zx; use anyhow::Context as _; const NETSTACK_URL: &'static str = "fuchsia-pkg://fuchsia.com/ping3-tests#meta/netstack3.cmx"; const PING_URL: &'static str = "fuchsia-pkg://fuchsia.com/ping3-tests#meta/ping3.cmx"; struct EnvConfig { name: String, static_ip: fnet::Subnet, } async fn create_environments<'a>( sandbox: &'a netemul::TestSandbox, test_name: String, on_link_subnet: fnet::Subnet, configs: Vec<EnvConfig>, ) -> Result< (Vec<(netemul::TestEnvironment<'a>, netemul::TestInterface<'a>)>, netemul::TestNetwork<'a>), anyhow::Error, > { let net = sandbox.create_network(test_name.clone()).await.context("create network")?; let mut envs = Vec::with_capacity(configs.len()); for config in configs.into_iter() { let name = format!("{}_{}", test_name, config.name); let env = sandbox .create_environment( name.clone(), vec![ netemul_environment::LaunchService { name: fnet_stack::StackMarker::PROTOCOL_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: Vec::new(), }, netemul_environment::LaunchService { name: fnet_icmp::ProviderMarker::PROTOCOL_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: Vec::new(), }, ], ) .with_context(|| format!("create {} environment", name))?; let ep = net .create_endpoint::<netemul::Ethernet, _>(config.name.clone()) .await .with_context(|| format!("create {} endpoint", config.name))?; let iface = ep.into_interface_in_environment(&env).await.context("into interface in env")?; let () = iface.set_link_up(true).await.context("set link up")?; let () = iface.enable_interface().await.context("enable interface")?; loop { let props = iface.get_info().await.context("get interface info")?.properties; if props.physical_status == fnet_stack::PhysicalStatus::Up && props.administrative_status == fnet_stack::AdministrativeStatus::Enabled { break; } let sleep_ms = 100; eprintln!("interface not ready, waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let () = iface.add_ip_addr(config.static_ip).await.context("add ip addr")?; loop { if iface.get_addrs().await.context("get addrs")?.contains(&config.static_ip) { break; } let sleep_ms = 500; eprintln!("address not ready, waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let stack = env.connect_to_service::<fnet_stack::StackMarker>().context("connect to net stack")?; let () = stack .add_forwarding_entry(&mut fnet_stack::ForwardingEntry { subnet: on_link_subnet, destination: fnet_stack::ForwardingDestination::DeviceId(iface.id()), }) .await .squash_result() .context("Failed to add forwarding entry")?; let () = envs.push((env, iface)); } Ok((envs, net)) } async fn ping3( env: &netemul::TestEnvironment<'_>, args: &str, ) -> Result<fuchsia_component::client::ExitStatus, anyhow::Error> { let launcher = env.get_launcher().context("get launcher").context("get launcher")?; fuchsia_component::client::launch( &launcher, PING_URL.to_string(), Some(args.split(" ").map(String::from).collect()), ) .context("launch ping3 component")? .wait() .await }
mod integration_tests; use fidl::endpoints::DiscoverableProtocolMarker as _; use fidl_fuchsia_net as fnet; use fidl_fuchsia_net_icmp as fnet_icmp; use fidl_fuchsia_net_stack as fnet_stack; use fidl_fuchsia_net_stack_ext::FidlReturn as _; use fidl_fuchsia_netemul_environment as netemul_environment; use fuchsia_zircon as zx; use anyhow::Context as _; const NETSTACK_URL: &'static str = "fuchsia-pkg://fuchsia.com/ping3-tests#meta/netstack3.cmx"; const PING_URL: &'static str = "fuchsia-pkg://fuchsia.com/ping3-tests#meta/ping3.cmx"; struct EnvConfig { name: String, static_ip: fnet::Subnet, } async fn create_environments<'a>( sandbox: &'a netemul::TestSandbox, test_name: String, on_link_subnet: fnet::Subnet, configs: Vec<EnvConfig>, ) -> Result< (Vec<(netemul::TestEnvironment<'a>, netemul::TestInterface<'a>)>, netemul::TestNetwork<'a>), anyhow::Error, > { let net = sandbox.create_network(test_name.clone()).await.context("create network")?; let mut envs = Vec::with_capacity(configs.len()); for config in configs.into_iter() { let name = format!("{}_{}", test_name, config.name); let env = sandbox .create_environment( name.clone(), vec![ netemul_environment::LaunchService { name: fnet_stack::StackMarker::PROTOCOL_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: Vec::new(), }, netemul_environment::LaunchService { name: fnet_icmp::ProviderMarker::PROTOCOL_NAME.to_string(), url: NETSTACK_URL.to_string(), arguments: Vec::new(), }, ], ) .with_context(|| format!("create {} environment", name))?; let ep = net .create_endpoint::<netemul::Ethernet, _>(config.name.clone()) .await .with_context(|| format!("create {} endpoint", config.name))?; let iface = ep.into_interface_in_environment(&env).await.context("into interface in env")?; let () = iface.set_link_up(true).await.context("set link up")?; let () = iface.enable_interface().await.context("enable interface")?; loop { let props = iface.get_info().await.context("get interface info")?.properties; if props.physical_status == fnet_stack::PhysicalStatus::Up && props.administrative_status == fnet_stack::AdministrativeStatus::Enabled { break; } let sleep_ms = 100; eprintln!("interface not ready,
let sleep_ms = 500; eprintln!("address not ready, waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let stack = env.connect_to_service::<fnet_stack::StackMarker>().context("connect to net stack")?; let () = stack .add_forwarding_entry(&mut fnet_stack::ForwardingEntry { subnet: on_link_subnet, destination: fnet_stack::ForwardingDestination::DeviceId(iface.id()), }) .await .squash_result() .context("Failed to add forwarding entry")?; let () = envs.push((env, iface)); } Ok((envs, net)) } async fn ping3( env: &netemul::TestEnvironment<'_>, args: &str, ) -> Result<fuchsia_component::client::ExitStatus, anyhow::Error> { let launcher = env.get_launcher().context("get launcher").context("get launcher")?; fuchsia_component::client::launch( &launcher, PING_URL.to_string(), Some(args.split(" ").map(String::from).collect()), ) .context("launch ping3 component")? .wait() .await }
waiting {}ms...", sleep_ms); let () = zx::Duration::from_millis(sleep_ms).sleep(); } let () = iface.add_ip_addr(config.static_ip).await.context("add ip addr")?; loop { if iface.get_addrs().await.context("get addrs")?.contains(&config.static_ip) { break; }
random
[]
Rust
src/ui/presenter/state/split.rs
MattWindsor91/zombiesplit
9040ac14e1c2a479dbb48f4e80d3c3b49ea9f7ec
use super::super::cursor::SplitPosition; use std::fmt::Display; use crate::model::{ aggregate, attempt::observer::{split, time}, comparison::pace::{self, PacedTime}, short, }; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Set { short_map: short::Map<usize>, vec: Vec<Split>, } impl Set { pub fn handle_event(&mut self, split: short::Name, evt: split::Event) { if let Some(s) = self.lookup_or_create_split(split, &evt) { s.handle_event(evt); } } pub fn reset(&mut self) { for split in &mut self.vec { split.reset(); } } pub fn refresh_cursors(&mut self, position: Option<usize>) { for (i, s) in &mut self.vec.iter_mut().enumerate() { s.position = SplitPosition::new(i, position); } } pub fn set_editor(&mut self, position: Option<usize>, editor: Option<&super::super::Editor>) { for (i, s) in &mut self.vec.iter_mut().enumerate() { s.set_editor(editor.filter(|_| Some(i) == position)); } } #[must_use] pub fn len(&self) -> usize { self.vec.len() } #[must_use] pub fn is_empty(&self) -> bool { self.vec.is_empty() } fn lookup_or_create_split( &mut self, split: short::Name, evt: &split::Event, ) -> Option<&mut Split> { if let split::Event::Init { index, .. } = evt { self.create_split(split, *index) } else { self.at_short_mut(split) } } fn create_split(&mut self, split: short::Name, index: usize) -> Option<&mut Split> { if self.vec.len() <= index { self.set_split_count(index + 1); } self.short_map.insert(split, index); self.vec.get_mut(index) } fn at_short_mut(&mut self, split: short::Name) -> Option<&mut Split> { self.index_of(split).and_then(|x| self.vec.get_mut(x)) } #[must_use] pub fn index_of(&self, split: short::Name) -> Option<usize> { self.short_map.get(&split).copied() } pub fn set_split_count(&mut self, count: usize) { self.vec.resize_with(count, Default::default); } #[must_use] pub fn at_index(&self, index: usize) -> Option<&Split> { self.vec.get(index) } } #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Split { pub num_times: usize, pub name: String, pub aggregates: aggregate::Full, pub pace_in_run: pace::SplitInRun, pub position: SplitPosition, pub editor: Option<super::Editor>, } impl Split { pub fn new<N: Display>(name: N) -> Self { let name = name.to_string(); Self { name, ..Self::default() } } pub fn reset(&mut self) { self.num_times = 0; self.aggregates = aggregate::Full::default(); self.pace_in_run = pace::SplitInRun::default(); } #[must_use] pub fn paced_cumulative(&self) -> PacedTime { let time = self.aggregates[aggregate::Source::Attempt][aggregate::Scope::Cumulative]; PacedTime { pace: self.pace_in_run.overall(), time, } } pub fn handle_event(&mut self, evt: split::Event) { match evt { split::Event::Init { name, .. } => { self.name = name; } split::Event::Time(t, time::Event::Aggregate(kind)) => { self.aggregates[kind.source][kind.scope] = t; } split::Event::Time(_, time::Event::Pushed) => { self.num_times += 1; } split::Event::Time(_, time::Event::Popped) => { self.num_times -= 1; } split::Event::Pace(pace) => { self.pace_in_run = pace; } } } pub fn set_editor(&mut self, editor: Option<&super::super::mode::Editor>) { self.editor = editor.map(|e| { let mut out = super::Editor { hours: e.time.hours.to_string(), mins: e.time.mins.to_string(), secs: e.time.secs.to_string(), msecs: e.time.millis.to_string(), field: None, }; if let Some(ref field) = e.field { let pos = field.position(); out.field = Some(pos); out[pos] = field.to_string(); } out }); } }
use super::super::cursor::SplitPosition; use std::fmt::Display; use crate::model::{ aggregate, attempt::observer::{split, time}, comparison::pace::{self, PacedTime}, short, }; #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Set { short_map: short::Map<usize>, vec: Vec<Split>, } impl Set { pub fn handle_event(&mut self, split: short::Name, evt: split::Event) { if let Some(s) = self.lookup_or_create_split(split, &evt) { s.handle_event(evt); } } pub fn reset(&mut self) { for split in &mut self.vec { split.reset(); } } pub fn refresh_cursors(&mut self, position: Option<usize>) { for (i, s) in &mut self.vec.iter_mut().enumerate() { s.position = SplitPosition::new(i, position); } } pub fn set_editor(&mut self, position: Option<usize>, editor: Option<&super::super::Editor>) { for (i, s) in &mut self.vec.iter_mut().enumerate() { s.set_editor(editor.filter(|_| Some(i) == position)); } } #[must_use] pub fn len(&self) -> usize { self.vec.len() } #[must_use] pub fn is_empty(&self) -> bool { self.vec.is_empty() } fn lookup_or_create_split( &mut self, split: short::Name, evt: &split::Event, ) -> Option<&mut Split> { if let split::Event::Init { index, .. } = evt { self.create_split(split, *index) } else { self.at_short_mut(split) } } fn create_split(&mut self, split: short::Name, index: usize) -> Option<&mut Split> { if self.vec.len() <= index { self.set_split_count(index + 1); } self.short_map.insert(split, index); self.vec.get_mut(index) } fn at_short_mut(&mut self, split: short::Name) -> Option<&mut Split> { self.index_of(split).and_then(|x| self.vec.get_mut(x)) } #[must_use] pub fn index_of(&self, split: short::Name) -> Option<usize> { self.short_map.get(&split).copied() } pub fn set_split_count(&mut self, count: usize) { self.vec.resize_with(count, Default::default); } #[must_use] pub fn at_index(&self, index: usize) -> Option<&Split> { self.vec.get(index) } } #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Split { pub num_times: usize, pub name: String, pub aggregates: aggregate::Full, pub pace_in_run: pace::SplitInRun, pub position: SplitPosition, pub editor: Option<super::Editor>, } impl Split { pub fn new<N: Display>(name: N) -> Self { let name = name.to_string(); Self { name, ..Self::default() } } pub fn reset(&mut self) { self.num_times = 0; self.aggregates = aggregate::Full::default(); self.pace_in_run = pace::SplitInRun::default(); } #[must_use] pub fn paced_cumulative(&self) -> PacedTime { let time = self.aggregates[aggregate::Source::Attempt][aggregate::Scope::Cumulative]; PacedTime { pace: self.pace_in_run.overall(), time, } } pub fn handle_event(&mut self, evt: split::Event) { match evt { split::Event::Init { name, .. } => { self.name = name; } split::Event::Time(t, time::Event::Aggregate(kind)) => { self.aggregates[kind.source][kind.scope] = t; } split::Event::Time(_, time::Event::Pushed) => { self.num_times += 1; } split::Event::Time(_, time::Event::Popped) => { self.num_times -= 1; } split::Event::Pace(pace) => { self.pace_in_run = pace; } } }
}
pub fn set_editor(&mut self, editor: Option<&super::super::mode::Editor>) { self.editor = editor.map(|e| { let mut out = super::Editor { hours: e.time.hours.to_string(), mins: e.time.mins.to_string(), secs: e.time.secs.to_string(), msecs: e.time.millis.to_string(), field: None, }; if let Some(ref field) = e.field { let pos = field.position(); out.field = Some(pos); out[pos] = field.to_string(); } out }); }
function_block-full_function
[ { "content": "fn make_cache(from: &[Split]) -> short::Map<usize> {\n\n from.iter()\n\n .enumerate()\n\n .map(|(i, s)| (s.info.short, i))\n\n .collect()\n\n}\n\n\n", "file_path": "src/model/attempt/split/set.rs", "rank": 0, "score": 242006.49281943368 }, { "content": "...
Rust
execution-engine/engine-tests/src/test/contract_api/create_purse.rs
flowstake/CasperLabs
761910a5957dffb281242d59d11dc017dcaa4104
use crate::support::test_support::{ExecuteRequestBuilder, WasmTestBuilder}; use contract_ffi::base16; use contract_ffi::key::Key; use contract_ffi::value::account::PurseId; use contract_ffi::value::U512; use engine_shared::transform::Transform; use crate::test::{DEFAULT_ACCOUNT_ADDR, DEFAULT_GENESIS_CONFIG, DEFAULT_PAYMENT}; const CONTRACT_CREATE_PURSE_01: &str = "create_purse_01.wasm"; const CONTRACT_TRANSFER_PURSE_TO_ACCOUNT: &str = "transfer_purse_to_account.wasm"; const ACCOUNT_1_ADDR: [u8; 32] = [1u8; 32]; const TEST_PURSE_NAME: &str = "test_purse"; lazy_static! { static ref ACCOUNT_1_INITIAL_BALANCE: U512 = *DEFAULT_PAYMENT; } fn get_purse_key_from_mint_transform(mint_transform: &Transform) -> Key { let keys = if let Transform::AddKeys(keys) = mint_transform { keys } else { panic!( "Mint transform is expected to be an AddKeys variant instead got {:?}", mint_transform ); }; assert_eq!(keys.len(), 1); let (map_key, map_value) = keys.iter().nth(0).unwrap(); assert!( map_key.starts_with("uref-"), format!( "expected uref to start with uref- but the map contains {:?}", keys ) ); let decoded_purse_id = base16::decode_lower(&map_key[5..69]).expect("should decode base16"); assert_eq!(decoded_purse_id.len(), 32); *map_value } #[ignore] #[test] fn should_insert_mint_add_keys_transform() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let mint_transform: &Transform = { let result = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); let mint_contract_uref = result.builder().get_mint_contract_uref(); &result.builder().get_transforms()[0][&mint_contract_uref.remove_access_rights().into()] }; get_purse_key_from_mint_transform(mint_transform); } #[ignore] #[test] fn should_insert_account_into_named_keys() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let account_1 = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish() .builder() .get_account(ACCOUNT_1_ADDR) .expect("should have account"); assert!( account_1.named_keys().contains_key(TEST_PURSE_NAME), "account_1 named_keys should include test purse" ); } #[ignore] #[test] fn should_create_usable_purse_id() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let result = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); let account_1 = result .builder() .get_account(ACCOUNT_1_ADDR) .expect("should have account"); let purse_key = account_1 .named_keys() .get(TEST_PURSE_NAME) .expect("should have known key"); let purse_id = PurseId::new(*purse_key.as_uref().expect("should have uref")); let purse_balance = result.builder().get_purse_balance(purse_id); assert!( purse_balance.is_zero(), "when created directly a purse has 0 balance" ); }
use crate::support::test_support::{ExecuteRequestBuilder, WasmTestBuilder}; use contract_ffi::base16; use contract_ffi::key::Key; use contract_ffi::value::account::PurseId; use contract_ffi::value::U512; use engine_shared::transform::Transform; use crate::test::{DEFAULT_ACCOUNT_ADDR, DEFAULT_GENESIS_CONFIG, DEFAULT_PAYMENT}; const CONTRACT_CREATE_PURSE_01: &str = "create_purse_01.wasm"; const CONTRACT_TRANSFER_PURSE_TO_ACCOUNT: &str = "transfer_purse_to_account.wasm"; const ACCOUNT_1_ADDR: [u8; 32] = [1u8; 32]; const TEST_PURSE_NAME: &str = "test_purse"; lazy_static! { static ref ACCOUNT_1_INITIAL_BALANCE: U512 = *DEFAULT_PAYMENT; } fn get_purse_key_from_mint_transform(mint_transform: &Transform) -> Key { let keys = if let Transform::AddKeys(keys) = mint_transform { keys } else { panic!( "Mint transform is expected to be an AddKeys variant instead got {:?}", mint_transform ); }; assert_eq!(keys.len(), 1); let (map_key, map_value) = keys.iter().nth(0).unwrap(); assert!( map_key.starts_with("uref-"), format!( "expected uref to start with uref- but the map contains {:?}", keys ) ); let decoded_purse_id = base16::decode_lower(&map_key[5..69]).expect("should decode base16"); assert_eq!(decoded_purse_id.len(), 32); *map_value } #[ignore] #[test]
#[ignore] #[test] fn should_insert_account_into_named_keys() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let account_1 = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish() .builder() .get_account(ACCOUNT_1_ADDR) .expect("should have account"); assert!( account_1.named_keys().contains_key(TEST_PURSE_NAME), "account_1 named_keys should include test purse" ); } #[ignore] #[test] fn should_create_usable_purse_id() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let result = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); let account_1 = result .builder() .get_account(ACCOUNT_1_ADDR) .expect("should have account"); let purse_key = account_1 .named_keys() .get(TEST_PURSE_NAME) .expect("should have known key"); let purse_id = PurseId::new(*purse_key.as_uref().expect("should have uref")); let purse_balance = result.builder().get_purse_balance(purse_id); assert!( purse_balance.is_zero(), "when created directly a purse has 0 balance" ); }
fn should_insert_mint_add_keys_transform() { let exec_request_1 = ExecuteRequestBuilder::standard( DEFAULT_ACCOUNT_ADDR, CONTRACT_TRANSFER_PURSE_TO_ACCOUNT, (ACCOUNT_1_ADDR, *ACCOUNT_1_INITIAL_BALANCE), ) .build(); let exec_request_2 = ExecuteRequestBuilder::standard( ACCOUNT_1_ADDR, CONTRACT_CREATE_PURSE_01, (TEST_PURSE_NAME,), ) .build(); let mint_transform: &Transform = { let result = WasmTestBuilder::default() .run_genesis(&DEFAULT_GENESIS_CONFIG) .exec(exec_request_1) .expect_success() .commit() .exec(exec_request_2) .expect_success() .commit() .finish(); let mint_contract_uref = result.builder().get_mint_contract_uref(); &result.builder().get_transforms()[0][&mint_contract_uref.remove_access_rights().into()] }; get_purse_key_from_mint_transform(mint_transform); }
function_block-full_function
[ { "content": "fn get_uref(key: Key) -> URef {\n\n match key {\n\n Key::URef(uref) => uref,\n\n _ => panic!(\"Key {:?} is not an URef\", key),\n\n }\n\n}\n\n\n", "file_path": "execution-engine/engine-tests/src/test/regression/ee_441.rs", "rank": 1, "score": 413384.2920016523 }, ...
Rust
src/http/mod.rs
ml85/iexc-rs
7a97fa89c4a5d4d9ac680c71395594e0c75a9a71
use std::error; use std::io; use std::io::prelude::*; use std::net::TcpStream; use std::sync::Arc; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; pub struct Response { pub protocol_version: String, pub status_code: u16, pub status_message: String, pub headers: Vec<(String, String)>, pub body: String, } impl Response { pub fn parse<R: BufRead>(reader: &mut R) -> Result<Response> { let mut status_line = String::new(); reader.read_line(&mut status_line)?; let (protocol_version, status_code, status_message) = parse_status_line(&status_line)?; let mut headers = Vec::new(); loop { let mut header = String::new(); let bytes_read = reader.read_line(&mut header)?; if bytes_read == 2 { break; } headers.push(parse_header(&header)?); } let content_length = find_content_length(&headers); let mut body = String::new(); reader.take(content_length).read_to_string(&mut body)?; Ok(Response { protocol_version, status_code, status_message, headers, body, }) } } fn parse_status_line(status_line: &str) -> Result<(String, u16, String)> { if let Some((version, rest1)) = status_line.split_once(" ") { if let Some((status_code, rest2)) = rest1.split_once(" ") { Ok(( version.trim().to_string(), status_code.trim().parse::<u16>().unwrap(), rest2.trim().to_string(), )) } else { Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse status code", ))) } } else { Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse protocol version", ))) } } fn parse_header(header_line: &str) -> Result<(String, String)> { match header_line.split_once(":") { Some((key, value)) => Ok(( key.to_ascii_lowercase(), value.trim().to_ascii_lowercase(), )), _ => Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse header line", ))), } } fn find_content_length(headers: &[(String, String)]) -> u64 { match headers.iter().find(|t| t.0.eq("content-length")) { Some(t) => t.1.parse::<u64>().unwrap(), _ => 0, } } trait Stream: io::Read + io::Write {} impl<T: io::Read + io::Write> Stream for T {} pub struct Client { domain: String, port: i16, insecure: bool, } impl Client { pub fn new(domain: String) -> Self { Self { domain, port: 443, insecure: false, } } pub fn _new_insecure(domain: String) -> Self { Self { domain, port: 80, insecure: true, } } pub fn get(&self, path: &str) -> Result<Response> { let mut stream = self.create_stream()?; write!( stream, "GET {} HTTP/1.1\r\n\ Host: {}\r\n\ Accept: */*\r\n\ \r\n", path, self.domain )?; Response::parse(&mut io::BufReader::new(stream)) } fn create_stream(&self) -> Result<Box<dyn Stream>> { if self.insecure { match TcpStream::connect(format!("{}:{}", self.domain, self.port)) { Ok(stream) => Ok(Box::new(stream)), Err(e) => Err(Box::new(e)), } } else { let mut config = rustls::ClientConfig::new(); config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let dns_name = webpki::DNSNameRef::try_from_ascii_str(self.domain.as_str())?; let session = rustls::ClientSession::new(&Arc::new(config), dns_name); let socket = TcpStream::connect(format!("{}:{}", self.domain, self.port))?; Ok(Box::new(rustls::StreamOwned::new(session, socket))) } } } #[cfg(test)] mod tests { use crate::http::Response; #[test] fn test_parse_valid_response() { let mut response = b"HTTP/1.1 200 OK\r\n\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT\r\n\ ETag: \"45b6-834-49130cc1182c0\"\r\n\ Accept-Ranges: bytes\r\n\ Content-Length: 12\r\n\ Connection: close\r\n\ Content-Type: text/html\r\n\ \r\n\ Hello world!" as &[u8]; let resp = Response::parse(&mut response).unwrap(); assert_eq!(resp.protocol_version, "HTTP/1.1"); assert_eq!(resp.status_code, 200); assert_eq!(resp.status_message, "OK"); assert_eq!(resp.body, "Hello world!"); } #[test] fn test_parse_long_status_line() { let mut response = b"HTTP/1.1 301 Moved to some nice place\n\r\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ \r\n" as &[u8]; let resp = Response::parse(&mut response).unwrap(); assert_eq!(resp.protocol_version, "HTTP/1.1"); assert_eq!(resp.status_code, 301); assert_eq!(resp.status_message, "Moved to some nice place"); } #[test] fn test_parse_invalid_status() { let mut response = b"OK\n\r\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ \r\n" as &[u8]; match Response::parse(&mut response) { Ok(_) => assert!(false), Err(_) => (), } } }
use std::error; use std::io; use std::io::prelude::*; use std::net::TcpStream; use std::sync::Arc; type Result<T> = std::result::Result<T, Box<dyn error::Error>>; pub struct Response { pub protocol_version: String, pub status_code: u16, pub status_message: String, pub headers: Vec<(String, String)>, pub body: String, } impl Response { pub fn parse<R: BufRead>(reader: &mut R) -> Result<Response> { let mut status_line = String::new(); reader.read_line(&mut status_line)?; let (protocol_version, status_code, status_message) = parse_status_line(&status_line)?; let mut headers = Vec::new(); loop { let mut header = String::new(); let bytes_read = reader.read_line(&mut header)?; if bytes_read == 2 { break; } headers.push(parse_header(&header)?); } let content_length = find_content_length(&headers); let mut body = String::new(); reader.take(content_length).read_to_string(&mut body)?; Ok(Response { protocol_version, status_code, status_message, headers, body, }) } } fn parse_status_line(status_line: &str) -> Result<(String, u16, String)> { if let Some((version, rest1)) = status_line.split_once(" ") { if let Some((status_code, rest2)) = rest1.split_once(" ") { Ok(( version.trim().to_string(), status_code.trim().parse::<u16>().unwrap(), rest2.trim().to_string(), )) } else { Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse status code", ))) } } else { Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse protocol version", ))) } } fn parse_header(header_line: &str) -> Result<(String, String)> { match header_line.split_once(":") { Some((key, value)) => Ok(( key.to_ascii_lowercase(), value.trim().to_ascii_lowercase(), )), _ => Err(Box::new(io::Error::new( io::ErrorKind::InvalidData, "Unable to parse header line", ))), } } fn find_content_length(headers: &[(String, String)]) -> u64 { match headers.iter().find(|t| t.0.eq("content-length")) { Some(t) => t.1.parse::<u64>().unwrap(), _ => 0, } } trait Stream: io::Read + io::Write {} impl<T: io::Read + io::Write> Stream for T {} pub struct Client { domain: String, port: i16, insecure: bool, } impl Client { pub fn new(domain: String) -> Self { Self { domain, port: 443, insecure: false, } } pub fn _new_insecure(domain: String) -> Self { Self { domain, port: 80, insecure: true, } } pub fn get(&self, path: &str) -> Result<Response> { let mut stream = self.create_stream()?; write!( stream, "GET {} HTTP/1.1\r\n\ Host: {}\r\n\ Accept: */*\r\n\ \r\n", path, self.domain )?; Response::parse(&mut io::BufReader::new(stream)) } fn create_stream(&self) -> Result<Box<dyn Stream>> { if self.insecure {
} else { let mut config = rustls::ClientConfig::new(); config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); let dns_name = webpki::DNSNameRef::try_from_ascii_str(self.domain.as_str())?; let session = rustls::ClientSession::new(&Arc::new(config), dns_name); let socket = TcpStream::connect(format!("{}:{}", self.domain, self.port))?; Ok(Box::new(rustls::StreamOwned::new(session, socket))) } } } #[cfg(test)] mod tests { use crate::http::Response; #[test] fn test_parse_valid_response() { let mut response = b"HTTP/1.1 200 OK\r\n\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT\r\n\ ETag: \"45b6-834-49130cc1182c0\"\r\n\ Accept-Ranges: bytes\r\n\ Content-Length: 12\r\n\ Connection: close\r\n\ Content-Type: text/html\r\n\ \r\n\ Hello world!" as &[u8]; let resp = Response::parse(&mut response).unwrap(); assert_eq!(resp.protocol_version, "HTTP/1.1"); assert_eq!(resp.status_code, 200); assert_eq!(resp.status_message, "OK"); assert_eq!(resp.body, "Hello world!"); } #[test] fn test_parse_long_status_line() { let mut response = b"HTTP/1.1 301 Moved to some nice place\n\r\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ \r\n" as &[u8]; let resp = Response::parse(&mut response).unwrap(); assert_eq!(resp.protocol_version, "HTTP/1.1"); assert_eq!(resp.status_code, 301); assert_eq!(resp.status_message, "Moved to some nice place"); } #[test] fn test_parse_invalid_status() { let mut response = b"OK\n\r\ Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n\ Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g\r\n\ \r\n" as &[u8]; match Response::parse(&mut response) { Ok(_) => assert!(false), Err(_) => (), } } }
match TcpStream::connect(format!("{}:{}", self.domain, self.port)) { Ok(stream) => Ok(Box::new(stream)), Err(e) => Err(Box::new(e)), }
if_condition
[ { "content": "type Result<T> = std::result::Result<T, Box<dyn error::Error>>;\n\n\n\npub enum Endpoint {\n\n Production,\n\n Sandbox,\n\n}\n\n\n\npub struct Client {\n\n http_client: http::Client,\n\n api_token: String,\n\n}\n\n\n\nimpl Client {\n\n pub fn new(endpoint: Endpoint, api_token: Strin...
Rust
edgelet/edgelet-http/src/util/mod.rs
jongio/iotedge
07a7b2071e6d64c934ebf55589416da0c4725093
use std::fmt; use std::io::{self, Read, Write}; use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::net::SocketAddr as UnixSocketAddr; use bytes::{Buf, BufMut}; use edgelet_core::pid::Pid; use futures::Poll; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(windows)] use tokio_named_pipe::PipeStream; #[cfg(unix)] use tokio_uds::UnixStream; #[cfg(unix)] use pid::UnixStreamExt; pub mod connector; mod hyperwrap; pub mod incoming; pub mod proxy; pub use self::connector::UrlConnector; pub use self::incoming::Incoming; pub enum StreamSelector { Tcp(TcpStream), #[cfg(windows)] Pipe(PipeStream), #[cfg(unix)] Unix(UnixStream), } impl StreamSelector { pub fn pid(&self) -> io::Result<Pid> { match *self { StreamSelector::Tcp(_) => Ok(Pid::Any), #[cfg(windows)] StreamSelector::Pipe(_) => Ok(Pid::Any), #[cfg(unix)] StreamSelector::Unix(ref stream) => stream.pid(), } } } impl Read for StreamSelector { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { StreamSelector::Tcp(ref mut stream) => stream.read(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.read(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.read(buf), } } } impl Write for StreamSelector { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match *self { StreamSelector::Tcp(ref mut stream) => stream.write(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.write(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.write(buf), } } fn flush(&mut self) -> io::Result<()> { match *self { StreamSelector::Tcp(ref mut stream) => stream.flush(), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.flush(), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.flush(), } } } impl AsyncRead for StreamSelector { #[inline] unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { match *self { StreamSelector::Tcp(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(windows)] StreamSelector::Pipe(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(unix)] StreamSelector::Unix(ref stream) => stream.prepare_uninitialized_buffer(buf), } } #[inline] fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => stream.read_buf(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.read_buf(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.read_buf(buf), } } } impl AsyncWrite for StreamSelector { fn shutdown(&mut self) -> Poll<(), io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => <&TcpStream>::shutdown(&mut &*stream), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => PipeStream::shutdown(stream), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => <&UnixStream>::shutdown(&mut &*stream), } } #[inline] fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => stream.write_buf(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.write_buf(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.write_buf(buf), } } } pub enum IncomingSocketAddr { Tcp(SocketAddr), #[cfg(unix)] Unix(UnixSocketAddr), } impl fmt::Display for IncomingSocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { IncomingSocketAddr::Tcp(ref socket) => socket.fmt(f), #[cfg(unix)] IncomingSocketAddr::Unix(ref socket) => { if let Some(path) = socket.as_pathname() { write!(f, "{}", path.display()) } else { write!(f, "unknown") } } } } } #[cfg(unix)] #[cfg(test)] mod tests { use tokio_core::reactor::Core; use super::*; #[test] fn test_pid() { let core = Core::new().unwrap(); let (a, b) = UnixStream::pair(&core.handle()).unwrap(); assert_eq!(a.pid().unwrap(), b.pid().unwrap()); match a.pid().unwrap() { Pid::None => panic!("no pid 'a'"), Pid::Any => panic!("any pid 'a'"), Pid::Value(_) => (), } match b.pid().unwrap() { Pid::None => panic!("no pid 'b'"), Pid::Any => panic!("any pid 'b'"), Pid::Value(_) => (), } } }
use std::fmt; use std::io::{self, Read, Write}; use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::net::SocketAddr as UnixSocketAddr; use bytes::{Buf, BufMut}; use edgelet_core::pid::Pid; use futures::Poll; use tokio_core::net::TcpStream; use tokio_io::{AsyncRead, AsyncWrite}; #[cfg(windows)] use tokio_named_pipe::PipeStream; #[cfg(unix)] use tokio_uds::UnixStream; #[cfg(unix)] use pid::UnixStreamExt; pub mod connector; mod hyperwrap; pub mod incoming; pub mod proxy; pub use self::connector::UrlConnector; pub use self::incoming::Incoming; pub enum StreamSelector { Tcp(TcpStream), #[cfg(windows)] Pipe(PipeStream), #[cfg(unix)] Unix(Un
[u8]) -> bool { match *self { StreamSelector::Tcp(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(windows)] StreamSelector::Pipe(ref stream) => stream.prepare_uninitialized_buffer(buf), #[cfg(unix)] StreamSelector::Unix(ref stream) => stream.prepare_uninitialized_buffer(buf), } } #[inline] fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => stream.read_buf(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.read_buf(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.read_buf(buf), } } } impl AsyncWrite for StreamSelector { fn shutdown(&mut self) -> Poll<(), io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => <&TcpStream>::shutdown(&mut &*stream), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => PipeStream::shutdown(stream), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => <&UnixStream>::shutdown(&mut &*stream), } } #[inline] fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { match *self { StreamSelector::Tcp(ref mut stream) => stream.write_buf(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.write_buf(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.write_buf(buf), } } } pub enum IncomingSocketAddr { Tcp(SocketAddr), #[cfg(unix)] Unix(UnixSocketAddr), } impl fmt::Display for IncomingSocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { IncomingSocketAddr::Tcp(ref socket) => socket.fmt(f), #[cfg(unix)] IncomingSocketAddr::Unix(ref socket) => { if let Some(path) = socket.as_pathname() { write!(f, "{}", path.display()) } else { write!(f, "unknown") } } } } } #[cfg(unix)] #[cfg(test)] mod tests { use tokio_core::reactor::Core; use super::*; #[test] fn test_pid() { let core = Core::new().unwrap(); let (a, b) = UnixStream::pair(&core.handle()).unwrap(); assert_eq!(a.pid().unwrap(), b.pid().unwrap()); match a.pid().unwrap() { Pid::None => panic!("no pid 'a'"), Pid::Any => panic!("any pid 'a'"), Pid::Value(_) => (), } match b.pid().unwrap() { Pid::None => panic!("no pid 'b'"), Pid::Any => panic!("any pid 'b'"), Pid::Value(_) => (), } } }
ixStream), } impl StreamSelector { pub fn pid(&self) -> io::Result<Pid> { match *self { StreamSelector::Tcp(_) => Ok(Pid::Any), #[cfg(windows)] StreamSelector::Pipe(_) => Ok(Pid::Any), #[cfg(unix)] StreamSelector::Unix(ref stream) => stream.pid(), } } } impl Read for StreamSelector { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match *self { StreamSelector::Tcp(ref mut stream) => stream.read(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.read(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.read(buf), } } } impl Write for StreamSelector { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match *self { StreamSelector::Tcp(ref mut stream) => stream.write(buf), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.write(buf), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.write(buf), } } fn flush(&mut self) -> io::Result<()> { match *self { StreamSelector::Tcp(ref mut stream) => stream.flush(), #[cfg(windows)] StreamSelector::Pipe(ref mut stream) => stream.flush(), #[cfg(unix)] StreamSelector::Unix(ref mut stream) => stream.flush(), } } } impl AsyncRead for StreamSelector { #[inline] unsafe fn prepare_uninitialized_buffer(&self, buf: &mut
random
[ { "content": "pub trait Recognizer {\n\n type Parameters: 'static;\n\n\n\n fn recognize(\n\n &self,\n\n method: &Method,\n\n path: &str,\n\n ) -> Result<HandlerParamsPair<Self::Parameters>, StatusCode>;\n\n}\n\n\n", "file_path": "edgelet/edgelet-http/src/route/mod.rs", "ran...
Rust
bee-api/bee-rest-api/src/endpoints/routes/api/plugins/debug/white_flag.rs
fossabot/bee-1
15329cb8a0b3bc5512fff2bd782db7e47ccb0ff0
use crate::{ endpoints::{ config::{RestApiConfig, ROUTE_WHITE_FLAG}, filters::{ with_bus, with_message_requester, with_requested_messages, with_rest_api_config, with_storage, with_tangle, }, permission::has_permission, rejection::CustomRejection, storage::StorageBackend, }, types::{body::SuccessBody, responses::WhiteFlagResponse}, }; use bee_ledger::workers::consensus::{self, WhiteFlagMetadata}; use bee_message::{milestone::MilestoneIndex, MessageId}; use bee_protocol::workers::{event::MessageSolidified, request_message, MessageRequesterWorker, RequestedMessages}; use bee_runtime::{event::Bus, resource::ResourceHandle}; use bee_tangle::MsTangle; use futures::channel::oneshot; use serde_json::Value as JsonValue; use tokio::time::timeout; use warp::{reject, Filter, Rejection, Reply}; use std::{ any::TypeId, collections::HashSet, net::IpAddr, sync::{Arc, Mutex}, time::Duration, }; fn path() -> impl Filter<Extract = (), Error = warp::Rejection> + Clone { super::path().and(warp::path("whiteflag")).and(warp::path::end()) } #[allow(clippy::too_many_arguments)] pub(crate) fn filter<B: StorageBackend>( public_routes: Box<[String]>, allowed_ips: Box<[IpAddr]>, storage: ResourceHandle<B>, tangle: ResourceHandle<MsTangle<B>>, bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApiConfig, ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { self::path() .and(warp::post()) .and(has_permission(ROUTE_WHITE_FLAG, public_routes, allowed_ips)) .and(warp::body::json()) .and(with_storage(storage)) .and(with_tangle(tangle)) .and(with_bus(bus)) .and(with_message_requester(message_requester)) .and(with_requested_messages(requested_messages)) .and(with_rest_api_config(rest_api_config)) .and_then(white_flag) } pub(crate) async fn white_flag<B: StorageBackend>( body: JsonValue, storage: ResourceHandle<B>, tangle: ResourceHandle<MsTangle<B>>, bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApiConfig, ) -> Result<impl Reply, Rejection> { let index_json = &body["index"]; let parents_json = &body["parentMessageIds"]; let index = if index_json.is_null() { return Err(reject::custom(CustomRejection::BadRequest( "Invalid index: expected a MilestoneIndex".to_string(), ))); } else { MilestoneIndex(index_json.as_u64().ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid index: expected a MilestoneIndex".to_string(), )) })? as u32) }; let parents = if parents_json.is_null() { return Err(reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), ))); } else { let array = parents_json.as_array().ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })?; let mut message_ids = Vec::new(); for s in array { let message_id = s .as_str() .ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })? .parse::<MessageId>() .map_err(|_| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })?; message_ids.push(message_id); } message_ids }; let to_solidify = Arc::new(Mutex::new(parents.iter().copied().collect::<HashSet<MessageId>>())); let (sender, receiver) = oneshot::channel::<()>(); let sender = Arc::new(Mutex::new(Some(sender))); let task_to_solidify = to_solidify.clone(); let task_sender = sender.clone(); struct Static; bus.add_listener::<Static, _, _>(move |event: &MessageSolidified| { if let Ok(mut to_solidify) = task_to_solidify.lock() { if to_solidify.remove(&event.message_id) && to_solidify.is_empty() { let _ = task_sender.lock().map(|mut s| s.take().map(|s| s.send(()))); } } }); for parent in parents.iter() { if tangle.is_solid_message(parent).await { if let Ok(mut to_solidify) = to_solidify.lock() { to_solidify.remove(parent); } } else { request_message(&*tangle, &message_requester, &*requested_messages, *parent, index).await; } } if let Ok(to_solidify) = to_solidify.lock() { if to_solidify.is_empty() { let _ = sender.lock().map(|mut s| s.take().map(|s| s.send(()))); } } let mut metadata = WhiteFlagMetadata::new(index); let response = match timeout( Duration::from_secs(rest_api_config.white_flag_solidification_timeout()), receiver, ) .await { Ok(_) => { consensus::white_flag::<B>(&tangle, &storage, &parents, &mut metadata) .await .map_err(|e| reject::custom(CustomRejection::BadRequest(e.to_string())))?; Ok(warp::reply::json(&SuccessBody::new(WhiteFlagResponse { merkle_tree_hash: hex::encode(metadata.merkle_proof()), }))) } Err(_) => { Err(reject::custom(CustomRejection::ServiceUnavailable( "parents not solid".to_string(), ))) } }; bus.remove_listeners_by_id(TypeId::of::<Static>()); response }
use crate::{ endpoints::{ config::{RestApiConfig, ROUTE_WHITE_FLAG}, filters::{ with_bus, with_message_requester, with_requested_messages, with_rest_api_config, with_storage, with_tangle, }, permission::has_permission, rejection::CustomRejection, storage::StorageBackend, }, types::{body::SuccessBody, responses::WhiteFlagResponse}, }; use bee_ledger::workers::consensus::{self, WhiteFlagMetadata}; use bee_message::{milestone::MilestoneIndex, MessageId}; use bee_protocol::workers::{event::MessageSolidified, request_message, MessageRequesterWorker, RequestedMessages}; use bee_runtime::{event::Bus, resource::ResourceHandle}; use bee_tangle::MsTangle; use futures::channel::oneshot; use serde_json::Value as JsonValue; use tokio::time::timeout; use warp::{reject, Filter, Rejection, Reply}; use std::{ any::TypeId, collections::HashSet, net::IpAddr, sync::{Arc, Mutex}, time::Duration, }; fn path() -> impl Filter<Extract = (), Error = warp::Rejection> + Clone { super::path().and(warp::path("whiteflag")).and(warp::path::end()) } #[allow(clippy::too_many_arguments)] pub(crate) fn filter<B: StorageBackend>( public_routes: Box<[String]>, allowed_ips: Box<[IpAddr]>, storage: ResourceHandle<B>, tangle: ResourceHandle<MsTangle<B>>,
pub(crate) async fn white_flag<B: StorageBackend>( body: JsonValue, storage: ResourceHandle<B>, tangle: ResourceHandle<MsTangle<B>>, bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApiConfig, ) -> Result<impl Reply, Rejection> { let index_json = &body["index"]; let parents_json = &body["parentMessageIds"]; let index = if index_json.is_null() { return Err(reject::custom(CustomRejection::BadRequest( "Invalid index: expected a MilestoneIndex".to_string(), ))); } else { MilestoneIndex(index_json.as_u64().ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid index: expected a MilestoneIndex".to_string(), )) })? as u32) }; let parents = if parents_json.is_null() { return Err(reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), ))); } else { let array = parents_json.as_array().ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })?; let mut message_ids = Vec::new(); for s in array { let message_id = s .as_str() .ok_or_else(|| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })? .parse::<MessageId>() .map_err(|_| { reject::custom(CustomRejection::BadRequest( "Invalid parents: expected an array of MessageId".to_string(), )) })?; message_ids.push(message_id); } message_ids }; let to_solidify = Arc::new(Mutex::new(parents.iter().copied().collect::<HashSet<MessageId>>())); let (sender, receiver) = oneshot::channel::<()>(); let sender = Arc::new(Mutex::new(Some(sender))); let task_to_solidify = to_solidify.clone(); let task_sender = sender.clone(); struct Static; bus.add_listener::<Static, _, _>(move |event: &MessageSolidified| { if let Ok(mut to_solidify) = task_to_solidify.lock() { if to_solidify.remove(&event.message_id) && to_solidify.is_empty() { let _ = task_sender.lock().map(|mut s| s.take().map(|s| s.send(()))); } } }); for parent in parents.iter() { if tangle.is_solid_message(parent).await { if let Ok(mut to_solidify) = to_solidify.lock() { to_solidify.remove(parent); } } else { request_message(&*tangle, &message_requester, &*requested_messages, *parent, index).await; } } if let Ok(to_solidify) = to_solidify.lock() { if to_solidify.is_empty() { let _ = sender.lock().map(|mut s| s.take().map(|s| s.send(()))); } } let mut metadata = WhiteFlagMetadata::new(index); let response = match timeout( Duration::from_secs(rest_api_config.white_flag_solidification_timeout()), receiver, ) .await { Ok(_) => { consensus::white_flag::<B>(&tangle, &storage, &parents, &mut metadata) .await .map_err(|e| reject::custom(CustomRejection::BadRequest(e.to_string())))?; Ok(warp::reply::json(&SuccessBody::new(WhiteFlagResponse { merkle_tree_hash: hex::encode(metadata.merkle_proof()), }))) } Err(_) => { Err(reject::custom(CustomRejection::ServiceUnavailable( "parents not solid".to_string(), ))) } }; bus.remove_listeners_by_id(TypeId::of::<Static>()); response }
bus: ResourceHandle<Bus<'static>>, message_requester: MessageRequesterWorker, requested_messages: ResourceHandle<RequestedMessages>, rest_api_config: RestApiConfig, ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { self::path() .and(warp::post()) .and(has_permission(ROUTE_WHITE_FLAG, public_routes, allowed_ips)) .and(warp::body::json()) .and(with_storage(storage)) .and(with_tangle(tangle)) .and(with_bus(bus)) .and(with_message_requester(message_requester)) .and(with_requested_messages(requested_messages)) .and(with_rest_api_config(rest_api_config)) .and_then(white_flag) }
function_block-function_prefix_line
[ { "content": "fn path() -> impl Filter<Extract = (MessageId,), Error = Rejection> + Clone {\n\n super::path()\n\n .and(warp::path(\"messages\"))\n\n .and(message_id())\n\n .and(warp::path::end())\n\n}\n\n\n\npub(crate) fn filter<B: StorageBackend>(\n\n public_routes: Box<[String]>,\n\...
Rust
azure_sdk_storage_blob/src/blob/requests/get_blob_builder.rs
imp/AzureSDKForRust
964b95e4a32c457a0a4fa45e9e16064e35f863be
use crate::blob::responses::GetBlobResponse; use crate::blob::{generate_blob_uri, Blob}; use azure_sdk_core::errors::{check_status_extract_headers_and_body, AzureError}; use azure_sdk_core::headers::RANGE_GET_CONTENT_MD5; use azure_sdk_core::lease::LeaseId; use azure_sdk_core::range::Range; use azure_sdk_core::util::RequestBuilderExt; use azure_sdk_core::{ BlobNameRequired, BlobNameSupport, ClientRequestIdOption, ClientRequestIdSupport, ContainerNameRequired, ContainerNameSupport, LeaseIdOption, LeaseIdSupport, No, RangeOption, RangeSupport, SnapshotOption, SnapshotSupport, TimeoutOption, TimeoutSupport, ToAssign, Yes, }; use azure_sdk_storage_core::client::Client; use azure_sdk_storage_core::ClientRequired; use chrono::{DateTime, Utc}; use hyper::{Method, StatusCode}; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { client: &'a Client, p_container_name: PhantomData<ContainerNameSet>, p_blob_name: PhantomData<BlobNameSet>, container_name: Option<&'a str>, blob_name: Option<&'a str>, snapshot: Option<DateTime<Utc>>, timeout: Option<u64>, range: Option<&'a Range>, lease_id: Option<&'a LeaseId>, client_request_id: Option<&'a str>, } impl<'a> GetBlobBuilder<'a, No, No> { #[inline] pub(crate) fn new(client: &'a Client) -> GetBlobBuilder<'a, No, No> { GetBlobBuilder { client, p_container_name: PhantomData {}, container_name: None, p_blob_name: PhantomData {}, blob_name: None, snapshot: None, timeout: None, range: None, lease_id: None, client_request_id: None, } } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequired<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn client(&self) -> &'a Client { self.client } } impl<'a, BlobNameSet> ContainerNameRequired<'a> for GetBlobBuilder<'a, Yes, BlobNameSet> where BlobNameSet: ToAssign, { #[inline] fn container_name(&self) -> &'a str { self.container_name.unwrap() } } impl<'a, ContainerNameSet> BlobNameRequired<'a> for GetBlobBuilder<'a, ContainerNameSet, Yes> where ContainerNameSet: ToAssign, { #[inline] fn blob_name(&self) -> &'a str { self.blob_name.unwrap() } } impl<'a, ContainerNameSet, BlobNameSet> SnapshotOption for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn snapshot(&self) -> Option<DateTime<Utc>> { self.snapshot } } impl<'a, ContainerNameSet, BlobNameSet> TimeoutOption for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn timeout(&self) -> Option<u64> { self.timeout } } impl<'a, ContainerNameSet, BlobNameSet> RangeOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn range(&self) -> Option<&'a Range> { self.range } } impl<'a, ContainerNameSet, BlobNameSet> LeaseIdOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn lease_id(&self) -> Option<&'a LeaseId> { self.lease_id } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequestIdOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn client_request_id(&self) -> Option<&'a str> { self.client_request_id } } impl<'a, ContainerNameSet, BlobNameSet> ContainerNameSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, Yes, BlobNameSet>; #[inline] fn with_container_name(self, container_name: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: Some(container_name), blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> BlobNameSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, Yes>; #[inline] fn with_blob_name(self, blob_name: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: Some(blob_name), snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> SnapshotSupport for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_snapshot(self, snapshot: DateTime<Utc>) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: Some(snapshot), timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> TimeoutSupport for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_timeout(self, timeout: u64) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: Some(timeout), range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> RangeSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_range(self, range: &'a Range) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: Some(range), lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> LeaseIdSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_lease_id(self, lease_id: &'a LeaseId) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: Some(lease_id), client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequestIdSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_client_request_id(self, client_request_id: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: Some(client_request_id), } } } impl<'a, ContainerNameSet, BlobNameSet> GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { } impl<'a> GetBlobBuilder<'a, Yes, Yes> { #[inline] pub async fn finalize(self) -> Result<GetBlobResponse, AzureError> { let container_name = self.container_name().to_owned(); let blob_name = self.blob_name().to_owned(); let snapshot_time = self.snapshot(); let mut uri = generate_blob_uri(&self, None); let mut f_first = true; if let Some(snapshot) = SnapshotOption::to_uri_parameter(&self) { uri = format!("{}?{}", uri, snapshot); f_first = false; } if let Some(timeout) = TimeoutOption::to_uri_parameter(&self) { uri = format!("{}{}{}", uri, if f_first { "?" } else { "&" }, timeout); } trace!("uri == {:?}", uri); let future_response = self.client().perform_request( &uri, &Method::GET, |mut request| { if let Some(r) = self.range() { request = LeaseIdOption::add_header(&self, request); request = RangeOption::add_header(&self, request); if r.len() <= 4 * 1024 * 1024 { request = request.header_static(RANGE_GET_CONTENT_MD5, "true"); } } request }, None, )?; let expected_status_code = if self.range().is_some() { StatusCode::PARTIAL_CONTENT } else { StatusCode::OK }; let (headers, body) = check_status_extract_headers_and_body(future_response, expected_status_code).await?; let blob = Blob::from_headers(&blob_name, &container_name, snapshot_time, &headers)?; GetBlobResponse::from_response(&headers, blob, &body) } }
use crate::blob::responses::GetBlobResponse; use crate::blob::{generate_blob_uri, Blob}; use azure_sdk_core::errors::{check_status_extract_headers_and_body, AzureError}; use azure_sdk_core::headers::RANGE_GET_CONTENT_MD5; use azure_sdk_core::lease::LeaseId; use azure_sdk_core::range::Range; use azure_sdk_core::util::RequestBuilderExt; use azure_sdk_core::{ BlobNameRequired, BlobNameSupport, ClientRequestIdOption, ClientRequestIdSupport, ContainerNameRequired, ContainerNameSupport, LeaseIdOption, LeaseIdSupport, No, RangeOption, RangeSupport, SnapshotOption, SnapshotSupport, TimeoutOption, TimeoutSupport, ToAssign, Yes, }; use azure_sdk_storage_core::client::Client; use azure_sdk_storage_core::ClientRequired; use chrono::{DateTime, Utc}; use hyper::{Method, StatusCode}; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { client: &'a Client, p_container_name: PhantomData<ContainerNameSet>, p_blob_name: PhantomData<BlobNameSet>, container_name: Option<&'a str>, blob_name: Option<&'a str>, snapshot: Option<DateTime<Utc>>, timeout: Option<u64>, range: Option<&'a Range>, lease_id: Option<&'a LeaseId>, client_request_id: Option<&'a str>, } impl<'a> GetBlobBuilder<'a, No, No> { #[inline] pub(crate) fn new(client: &'a Client) -> GetBlobBuilder<'a, No, No> { GetBlobBuilder { client, p_container_name: PhantomData {}, container_name: None, p_blob_name: PhantomData {}, blob_name: None, snapshot: None, timeout: None, range: None, lease_id: None, client_request_id: None, } } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequired<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn client(&self) -> &'a Client { self.client } } impl<'a, BlobNameSet> ContainerNameRequired<'a> for GetBlobBuilder<'a, Yes, BlobNameSet> where BlobNameSet: ToAssign, { #[inline] fn container_name(&self) -> &'a str { self.container_name.unwrap() } } impl<'a, ContainerNameSet> BlobNameRequired<'a> for GetBlobBuilder<'a, ContainerNameSet, Yes> where ContainerNameSet: ToAssign, { #[inline] fn blob_name(&self) -> &'a str { self.blob_name.unwrap() } } impl<'a, ContainerNameSet, BlobNameSet> SnapshotOption for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn snapshot(&self) -> Option<DateTime<Utc>> { self.snapshot } } impl<'a, ContainerNameSet, BlobNameSet> TimeoutOption for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn timeout(&self) -> Option<u64> { self.timeout } } impl<'a, ContainerNameSet, BlobNameSet> RangeOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn range(&self) -> Option<&'a Range> { self.range } } impl<'a, ContainerNameSet, BlobNameSet> LeaseIdOption<'a> for GetBlobBuilder<'a, Conta
if let Some(timeout) = TimeoutOption::to_uri_parameter(&self) { uri = format!("{}{}{}", uri, if f_first { "?" } else { "&" }, timeout); } trace!("uri == {:?}", uri); let future_response = self.client().perform_request( &uri, &Method::GET, |mut request| { if let Some(r) = self.range() { request = LeaseIdOption::add_header(&self, request); request = RangeOption::add_header(&self, request); if r.len() <= 4 * 1024 * 1024 { request = request.header_static(RANGE_GET_CONTENT_MD5, "true"); } } request }, None, )?; let expected_status_code = if self.range().is_some() { StatusCode::PARTIAL_CONTENT } else { StatusCode::OK }; let (headers, body) = check_status_extract_headers_and_body(future_response, expected_status_code).await?; let blob = Blob::from_headers(&blob_name, &container_name, snapshot_time, &headers)?; GetBlobResponse::from_response(&headers, blob, &body) } }
inerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn lease_id(&self) -> Option<&'a LeaseId> { self.lease_id } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequestIdOption<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { #[inline] fn client_request_id(&self) -> Option<&'a str> { self.client_request_id } } impl<'a, ContainerNameSet, BlobNameSet> ContainerNameSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, Yes, BlobNameSet>; #[inline] fn with_container_name(self, container_name: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: Some(container_name), blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> BlobNameSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, Yes>; #[inline] fn with_blob_name(self, blob_name: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: Some(blob_name), snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> SnapshotSupport for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_snapshot(self, snapshot: DateTime<Utc>) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: Some(snapshot), timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> TimeoutSupport for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_timeout(self, timeout: u64) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: Some(timeout), range: self.range, lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> RangeSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_range(self, range: &'a Range) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: Some(range), lease_id: self.lease_id, client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> LeaseIdSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_lease_id(self, lease_id: &'a LeaseId) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: Some(lease_id), client_request_id: self.client_request_id, } } } impl<'a, ContainerNameSet, BlobNameSet> ClientRequestIdSupport<'a> for GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { type O = GetBlobBuilder<'a, ContainerNameSet, BlobNameSet>; #[inline] fn with_client_request_id(self, client_request_id: &'a str) -> Self::O { GetBlobBuilder { client: self.client, p_container_name: PhantomData {}, p_blob_name: PhantomData {}, container_name: self.container_name, blob_name: self.blob_name, snapshot: self.snapshot, timeout: self.timeout, range: self.range, lease_id: self.lease_id, client_request_id: Some(client_request_id), } } } impl<'a, ContainerNameSet, BlobNameSet> GetBlobBuilder<'a, ContainerNameSet, BlobNameSet> where ContainerNameSet: ToAssign, BlobNameSet: ToAssign, { } impl<'a> GetBlobBuilder<'a, Yes, Yes> { #[inline] pub async fn finalize(self) -> Result<GetBlobResponse, AzureError> { let container_name = self.container_name().to_owned(); let blob_name = self.blob_name().to_owned(); let snapshot_time = self.snapshot(); let mut uri = generate_blob_uri(&self, None); let mut f_first = true; if let Some(snapshot) = SnapshotOption::to_uri_parameter(&self) { uri = format!("{}?{}", uri, snapshot); f_first = false; }
random
[ { "content": "pub fn initialize() -> Result<Client<impl CosmosUriBuilder + Clone>, AzureError> {\n\n let account = std::env::var(\"COSMOS_ACCOUNT\").expect(\"Set env variable COSMOS_ACCOUNT first!\");\n\n let key = std::env::var(\"COSMOS_MASTER_KEY\").expect(\"Set env variable COSMOS_KEY first!\");\n\n\n\...
Rust
libafl_frida/src/cmplog_rt.rs
AdrianoPi/LibAFL
cf5b4dfb180d65cb267ec1297df5cb52acbdcfef
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use libafl_targets::CMPLOG_MAP_W; use std::ffi::c_void; extern crate libafl_targets; extern "C" { pub fn __libafl_targets_cmplog_instructions(k: u64, shape: u8, arg1: u64, arg2: u64); } pub struct CmpLogRuntime { ops_save_register_and_blr_to_populate: Option<Box<[u8]>>, ops_handle_tbz_masking: Option<Box<[u8]>>, ops_handle_tbnz_masking: Option<Box<[u8]>>, } impl CmpLogRuntime { #[must_use] pub fn new() -> CmpLogRuntime { Self { ops_save_register_and_blr_to_populate: None, ops_handle_tbz_masking: None, ops_handle_tbnz_masking: None, } } #[allow(clippy::unused_self)] extern "C" fn populate_lists(&mut self, op1: u64, op2: u64, retaddr: u64) { let mut k = (retaddr >> 4) ^ (retaddr << 8); k &= (CMPLOG_MAP_W as u64) - 1; unsafe { __libafl_targets_cmplog_instructions(k, 8, op1, op2); } } #[allow(clippy::similar_names)] fn generate_instrumentation_blobs(&mut self) { macro_rules! blr_to_populate { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x2, x3, [sp, #-0x10]! ; stp x4, x5, [sp, #-0x10]! ; stp x6, x7, [sp, #-0x10]! ; stp x8, x9, [sp, #-0x10]! ; stp x10, x11, [sp, #-0x10]! ; stp x12, x13, [sp, #-0x10]! ; stp x14, x15, [sp, #-0x10]! ; stp x16, x17, [sp, #-0x10]! ; stp x18, x19, [sp, #-0x10]! ; stp x20, x21, [sp, #-0x10]! ; stp x22, x23, [sp, #-0x10]! ; stp x24, x25, [sp, #-0x10]! ; stp x26, x27, [sp, #-0x10]! ; stp x28, x29, [sp, #-0x10]! ; stp x30, xzr, [sp, #-0x10]! ; .dword 0xd53b4218u32 as i32 ; mov x2, x0 ; adr x3, >done ; ldr x4, >populate_lists ; ldr x0, >self_addr ; blr x4 ; .dword 0xd51b4218u32 as i32 ; ldp x30, xzr, [sp], #0x10 ; ldp x28, x29, [sp], #0x10 ; ldp x26, x27, [sp], #0x10 ; ldp x24, x25, [sp], #0x10 ; ldp x22, x23, [sp], #0x10 ; ldp x20, x21, [sp], #0x10 ; ldp x18, x19, [sp], #0x10 ; ldp x16, x17, [sp], #0x10 ; ldp x14, x15, [sp], #0x10 ; ldp x12, x13, [sp], #0x10 ; ldp x10, x11, [sp], #0x10 ; ldp x8, x9, [sp], #0x10 ; ldp x6, x7, [sp], #0x10 ; ldp x4, x5, [sp], #0x10 ; ldp x2, x3, [sp], #0x10 ; b >done ; self_addr: ; .qword self as *mut _ as *mut c_void as i64 ; populate_lists: ; .qword CmpLogRuntime::populate_lists as *mut c_void as i64 ; done: );}; } macro_rules! tbz_masking { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x5, x5, [sp, #-0x10]! ; mov x5, #1 ; lsl x5, x5, x1 ; eor x5, x5, #255 ; orr x1, x0, x5 ; ldp x5, x5, [sp], #0x10 );}; } macro_rules! tbnz_masking { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x5, x5, [sp, #-0x10]! ; mov x5, #1 ; lsl x5, x5, x1 ; orr x1, x0, x5 ; ldp x5, x5, [sp], #0x10 );}; } let mut ops_handle_tbz_masking = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); tbz_masking!(ops_handle_tbz_masking); let mut ops_handle_tbnz_masking = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); tbnz_masking!(ops_handle_tbnz_masking); let mut ops_save_register_and_blr_to_populate = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); blr_to_populate!(ops_save_register_and_blr_to_populate); self.ops_handle_tbz_masking = Some( ops_handle_tbz_masking .finalize() .unwrap() .into_boxed_slice(), ); self.ops_handle_tbnz_masking = Some( ops_handle_tbnz_masking .finalize() .unwrap() .into_boxed_slice(), ); self.ops_save_register_and_blr_to_populate = Some( ops_save_register_and_blr_to_populate .finalize() .unwrap() .into_boxed_slice(), ); } pub fn init(&mut self) { self.generate_instrumentation_blobs(); } #[inline] #[must_use] pub fn ops_save_register_and_blr_to_populate(&self) -> &[u8] { self.ops_save_register_and_blr_to_populate.as_ref().unwrap() } #[inline] #[must_use] pub fn ops_handle_tbz_masking(&self) -> &[u8] { self.ops_handle_tbz_masking.as_ref().unwrap() } #[inline] #[must_use] pub fn ops_handle_tbnz_masking(&self) -> &[u8] { self.ops_handle_tbnz_masking.as_ref().unwrap() } } impl Default for CmpLogRuntime { fn default() -> Self { Self::new() } }
use dynasmrt::{dynasm, DynasmApi, DynasmLabelApi}; use libafl_targets::CMPLOG_MAP_W; use std::ffi::c_void; extern crate libafl_targets; extern "C" { pub fn __libafl_targets_cmplog_instructions(k: u64, shape: u8, arg1: u64, arg2: u64); } pub struct CmpLogRuntime { ops_save_register_and_blr_to_populate: Option<Box<[u8]>>, ops_handle_tbz_masking: Option<Box<[u8]>>, ops_handle_tbnz_masking: Option<Box<[u8]>>, } impl CmpLogRuntime { #[must_use] pub fn new() -> CmpLogRuntime { Self { ops_save_register_and_blr_to_populate: None, ops_handle_tbz_masking: None, ops_handle_tbnz_masking: None, } } #[allow(clippy::unused_self)] extern "C" fn populate_lists(&mut self, op1: u64, op2: u64, retaddr: u64) { let mut k = (retaddr >> 4) ^ (retaddr << 8); k &= (CMPLOG_MAP_W as u64) - 1; unsafe { __libafl_targets_cmplog_instructions(k, 8, op1, op2); } } #[allow(clippy::similar_names)] fn generate_instrumentation_blobs(&mut self) { macro_rules! blr_to_populate { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x2, x3, [sp, #-0x10]! ; stp x4, x5, [sp, #-0x10]! ; stp x6, x7, [sp, #-0x10]! ; stp x8, x9, [sp, #-0x10]! ; stp x10, x11, [sp, #-0x10]! ; stp x12, x13, [sp, #-0x10]! ; stp x14, x15, [sp, #-0x10]! ; stp x16, x17, [sp, #-0x10]! ; stp x18, x19, [sp, #-0x10]! ; stp x20, x21, [sp, #-0x10]! ; stp x22, x23, [sp, #-0x10]! ; stp x24, x25, [sp, #-0x10]! ; stp x26, x27, [sp, #-0x10]! ; stp x28, x29, [sp, #-0x10]! ; stp x30, xzr, [sp, #-0x10]! ; .dword 0xd53b4218u32 as i32 ; mov x2, x0 ; adr x3, >done ; ldr x4, >populate_lists ; ldr x0, >self_addr ; blr x4 ; .dword 0xd51b4218u32 as i32 ; ldp x30, xzr, [sp], #0x10 ; ldp x28, x29, [sp], #0x10 ; ldp x26, x27, [sp], #0x10 ; ldp x24, x25, [sp], #0x10 ; ldp x22, x23, [sp], #0x10 ; ldp x20, x21, [sp], #0x10 ; ldp x18, x19, [sp], #0x10 ; ldp x16, x17, [sp], #0x10 ; ldp x14, x15, [sp], #0x10 ; ldp x12, x13, [sp], #0x10 ; ldp x10, x11, [sp], #0x10 ; ldp x8, x9, [sp], #0x10 ; ldp x6, x7, [sp], #0x10 ; ldp x4, x5, [sp], #0x10 ; ldp x2, x3, [sp], #0x10 ; b >done ; self_addr: ; .qword self as *mut _ as *mut c_void as i64 ; populate_lists: ; .qword CmpLogRuntime::populate_lists as *mut c_void as i64 ; done: );}; } macro_rules! tbz_masking { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x5, x5, [sp, #-0x10]! ; mov x5, #1 ; lsl x5, x5, x1 ; eor x5, x5, #255 ; orr x1, x0, x5 ; ldp x5, x5, [sp], #0x10 );}; } macro_rules! tbnz_masking { ($ops:ident) => {dynasm!($ops ; .arch aarch64 ; stp x5, x5, [sp, #-0x10]! ; mov x5, #1 ; lsl x5, x5, x1 ; orr x1, x0, x5 ; ldp x5, x5, [sp], #0x10 );}; } let mut ops_handle_tbz_masking = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); tbz_masking!(ops_handle_tbz_masking); let mut ops_handle_tbnz_masking = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); tbnz_masking!(ops_handle_tbnz_masking); let mut ops_save_register_and_blr_to_populate = dynasmrt::VecAssembler::<dynasmrt::aarch64::Aarch64Relocation>::new(0); blr_to_populate!(ops_save_register_and_blr_to_populate); self.ops_handle_tbz_masking = Some( ops_handle_tbz_masking .finalize() .unwrap() .into_boxed_slice(), ); self.ops_handle_tbnz_masking =
; self.ops_save_register_and_blr_to_populate = Some( ops_save_register_and_blr_to_populate .finalize() .unwrap() .into_boxed_slice(), ); } pub fn init(&mut self) { self.generate_instrumentation_blobs(); } #[inline] #[must_use] pub fn ops_save_register_and_blr_to_populate(&self) -> &[u8] { self.ops_save_register_and_blr_to_populate.as_ref().unwrap() } #[inline] #[must_use] pub fn ops_handle_tbz_masking(&self) -> &[u8] { self.ops_handle_tbz_masking.as_ref().unwrap() } #[inline] #[must_use] pub fn ops_handle_tbnz_masking(&self) -> &[u8] { self.ops_handle_tbnz_masking.as_ref().unwrap() } } impl Default for CmpLogRuntime { fn default() -> Self { Self::new() } }
Some( ops_handle_tbnz_masking .finalize() .unwrap() .into_boxed_slice(), )
call_expression
[ { "content": "pub fn set_exec_cmp1_hook(hook: extern \"C\" fn(id: u64, v0: u8, v1: u8)) {\n\n unsafe {\n\n libafl_exec_cmp_hook1 = hook;\n\n }\n\n}\n\n\n", "file_path": "libafl_qemu/src/emu.rs", "rank": 0, "score": 394177.4333775672 }, { "content": "pub fn set_hook(addr: u64, ca...
Rust
12_exceptions_part1_groundwork/src/_arch/aarch64/exception.rs
tantara/rust-raspberrypi-OS-tutorials
6eafd7c81e41cdfcac131eaaf722e274c8b1bcff
use core::{cell::UnsafeCell, fmt}; use cortex_a::{asm, barrier, regs::*}; use register::InMemoryRegister; global_asm!(include_str!("exception.S")); #[repr(transparent)] struct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>); #[repr(C)] struct ExceptionContext { gpr: [u64; 30], lr: u64, elr_el1: u64, spsr_el1: SpsrEL1, } struct EsrEL1; fn default_exception_handler(e: &ExceptionContext) { panic!( "\n\nCPU Exception!\n\ FAR_EL1: {:#018x}\n\ {}\n\ {}", FAR_EL1.get(), EsrEL1 {}, e ); } #[no_mangle] unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { let far_el1 = FAR_EL1.get(); if far_el1 == 8 * 1024 * 1024 * 1024 { e.elr_el1 += 4; asm::eret() } default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[rustfmt::skip] impl fmt::Display for EsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let esr_el1 = ESR_EL1.extract(); writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", _ => "N/A", }; writeln!(f, " - {}", ec_translation)?; write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; Ok(()) } } #[rustfmt::skip] impl fmt::Display for SpsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; let to_flag_str = |x| -> _ { if x { "Set" } else { "Not set" } }; writeln!(f, " Flags:")?; writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; writeln!(f, " Exception handling state:")?; writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; write!(f, " Illegal Execution State (IL): {}", to_flag_str(self.0.is_set(SPSR_EL1::IL)) )?; Ok(()) } } impl fmt::Display for ExceptionContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; writeln!(f, "{}", self.spsr_el1)?; writeln!(f)?; writeln!(f, "General purpose register:")?; #[rustfmt::skip] let alternating = |x| -> _ { if x % 2 == 0 { " " } else { "\n" } }; for (i, reg) in self.gpr.iter().enumerate() { write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; } write!(f, " lr : {:#018x}", self.lr)?; Ok(()) } } use crate::exception::PrivilegeLevel; pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } pub unsafe fn handling_init() { extern "Rust" { static __exception_vector_start: UnsafeCell<()>; } VBAR_EL1.set(__exception_vector_start.get() as u64); barrier::isb(barrier::SY); }
use core::{cell::UnsafeCell, fmt}; use cortex_a::{asm, barrier, regs::*}; use register::InMemoryRegister; global_asm!(include_str!("exception.S")); #[repr(transparent)] struct SpsrEL1(InMemoryRegister<u64, SPSR_EL1::Register>); #[repr(C)] struct ExceptionContext { gpr: [u64; 30], lr: u64, elr_el1: u64, spsr_el1: SpsrEL1, } struct EsrEL1; fn default_exception_handler(e: &ExceptionContext) { panic!( "\n\nCPU Exception!\n\ FAR_EL1: {:#018x}\n\ {}\n\ {}", FAR_EL1.get(), EsrEL1 {}, e ); } #[no_mangle] unsafe extern "C" fn current_el0_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_el0_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_el0_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_synchronous(e: &mut ExceptionContext) { let far_el1 = FAR_EL1.get(); if far_el1 == 8 * 1024 * 1024 * 1024 { e.elr_el1 += 4; asm::eret() } default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn current_elx_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch64_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_synchronous(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_irq(e: &mut ExceptionContext) { default_exception_handler(e); } #[no_mangle] unsafe extern "C" fn lower_aarch32_serror(e: &mut ExceptionContext) { default_exception_handler(e); } #[rustfmt::skip] impl fmt::Display for EsrEL1 {
} #[rustfmt::skip] impl fmt::Display for SpsrEL1 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "SPSR_EL1: {:#010x}", self.0.get())?; let to_flag_str = |x| -> _ { if x { "Set" } else { "Not set" } }; writeln!(f, " Flags:")?; writeln!(f, " Negative (N): {}", to_flag_str(self.0.is_set(SPSR_EL1::N)))?; writeln!(f, " Zero (Z): {}", to_flag_str(self.0.is_set(SPSR_EL1::Z)))?; writeln!(f, " Carry (C): {}", to_flag_str(self.0.is_set(SPSR_EL1::C)))?; writeln!(f, " Overflow (V): {}", to_flag_str(self.0.is_set(SPSR_EL1::V)))?; let to_mask_str = |x| -> _ { if x { "Masked" } else { "Unmasked" } }; writeln!(f, " Exception handling state:")?; writeln!(f, " Debug (D): {}", to_mask_str(self.0.is_set(SPSR_EL1::D)))?; writeln!(f, " SError (A): {}", to_mask_str(self.0.is_set(SPSR_EL1::A)))?; writeln!(f, " IRQ (I): {}", to_mask_str(self.0.is_set(SPSR_EL1::I)))?; writeln!(f, " FIQ (F): {}", to_mask_str(self.0.is_set(SPSR_EL1::F)))?; write!(f, " Illegal Execution State (IL): {}", to_flag_str(self.0.is_set(SPSR_EL1::IL)) )?; Ok(()) } } impl fmt::Display for ExceptionContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "ELR_EL1: {:#018x}", self.elr_el1)?; writeln!(f, "{}", self.spsr_el1)?; writeln!(f)?; writeln!(f, "General purpose register:")?; #[rustfmt::skip] let alternating = |x| -> _ { if x % 2 == 0 { " " } else { "\n" } }; for (i, reg) in self.gpr.iter().enumerate() { write!(f, " x{: <2}: {: >#018x}{}", i, reg, alternating(i))?; } write!(f, " lr : {:#018x}", self.lr)?; Ok(()) } } use crate::exception::PrivilegeLevel; pub fn current_privilege_level() -> (PrivilegeLevel, &'static str) { let el = CurrentEL.read_as_enum(CurrentEL::EL); match el { Some(CurrentEL::EL::Value::EL2) => (PrivilegeLevel::Hypervisor, "EL2"), Some(CurrentEL::EL::Value::EL1) => (PrivilegeLevel::Kernel, "EL1"), Some(CurrentEL::EL::Value::EL0) => (PrivilegeLevel::User, "EL0"), _ => (PrivilegeLevel::Unknown, "Unknown"), } } pub unsafe fn handling_init() { extern "Rust" { static __exception_vector_start: UnsafeCell<()>; } VBAR_EL1.set(__exception_vector_start.get() as u64); barrier::isb(barrier::SY); }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let esr_el1 = ESR_EL1.extract(); writeln!(f, "ESR_EL1: {:#010x}", esr_el1.get())?; write!(f, " Exception Class (EC) : {:#x}", esr_el1.read(ESR_EL1::EC))?; let ec_translation = match esr_el1.read_as_enum(ESR_EL1::EC) { Some(ESR_EL1::EC::Value::DataAbortCurrentEL) => "Data Abort, current EL", _ => "N/A", }; writeln!(f, " - {}", ec_translation)?; write!(f, " Instr Specific Syndrome (ISS): {:#x}", esr_el1.read(ESR_EL1::ISS))?; Ok(()) }
function_block-full_function
[ { "content": "/// Return the inclusive range spanning the .bss section.\n\n///\n\n/// # Safety\n\n///\n\n/// - Values are provided by the linker script and must be trusted as-is.\n\n/// - The linker-provided addresses must be u64 aligned.\n\npub fn bss_range_inclusive() -> RangeInclusive<*mut u64> {\n\n let ...
Rust
src/errno.rs
allisonrandal/vmm-sys-util
26e085b93c0e6342447d82ef21ddb3846c4edad4
use std::fmt::{Display, Formatter}; use std::io; use std::result; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Error(i32); pub type Result<T> = result::Result<T, Error>; impl Error { pub fn new(errno: i32) -> Error { Error(errno) } pub fn last() -> Error { Error(io::Error::last_os_error().raw_os_error().unwrap()) } pub fn errno(self) -> i32 { self.0 } } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { io::Error::from_raw_os_error(self.0).fmt(f) } } impl std::error::Error for Error {} impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::new(e.raw_os_error().unwrap_or_default()) } } impl Into<io::Error> for Error { fn into(self) -> io::Error { io::Error::from_raw_os_error(self.0) } } pub fn errno_result<T>() -> Result<T> { Err(Error::last()) } #[cfg(test)] mod tests { use super::*; use libc; use std::env::temp_dir; use std::error::Error as _; use std::fs::OpenOptions; use std::io::{self, Read}; #[test] pub fn test_errno() { #[cfg(unix)] let expected_errno = libc::EBADF; #[cfg(not(unix))] let expected_errno = libc::EIO; let mut path = temp_dir(); path.push("test"); let mut file = OpenOptions::new() .read(false) .write(true) .create(true) .truncate(true) .open(path) .unwrap(); let mut buf: Vec<u8> = Vec::new(); assert!(file.read_to_end(&mut buf).is_err()); let last_err = errno_result::<i32>().unwrap_err(); assert_eq!(last_err, Error::new(expected_errno)); assert_eq!(last_err.errno(), expected_errno); assert!(last_err.source().is_none()); assert_eq!(last_err, Error::from(io::Error::last_os_error())); assert_eq!(last_err, Error::last()); let last_err: io::Error = last_err.into(); assert_eq!(io::Error::last_os_error().kind(), last_err.kind()); } #[test] pub fn test_display() { #[cfg(unix)] assert_eq!( format!("{}", Error::new(libc::EBADF)), "Bad file descriptor (os error 9)" ); #[cfg(not(unix))] assert_eq!( format!("{}", Error::new(libc::EIO)), "Access is denied. (os error 5)" ); } }
use std::fmt::{Display, Formatter}; use std::io; use std::result; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Error(i32); pub type Result<T> = result::Result<T, Error>; impl Error { pub fn new(errno: i32) -> Error { Error(errno) } pub fn last() -> Error { Error(io::Error::last_os_error().raw_os_error().unwrap()) } pub fn errno(self) -> i32 { self.0 } } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { io::Error::from_raw_os_error(self.0).fmt(f) } } impl std::error::Error for Error {} impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::new(e.raw_os_error().unwrap_or_default()) } } impl Into<io::Error> for Error { fn into(self) -> io::Error { io::Error::from_raw_os_error(self.0) } } pub fn errno_result<T>() -> Result<T> { Err(Error::last()) } #[cfg(test)] mod tests { use super::*; use libc; use std::env::temp_dir; use std::error::Error as _; use std::fs::OpenOptions; use std::io::{self, Read}; #[test] pub fn test_errno() { #[cfg(unix)] let expected_errno = libc::EBADF; #[cfg(not(unix))] let expected_errno = libc::EIO; let mut path = temp_dir(); path.push("test");
let mut buf: Vec<u8> = Vec::new(); assert!(file.read_to_end(&mut buf).is_err()); let last_err = errno_result::<i32>().unwrap_err(); assert_eq!(last_err, Error::new(expected_errno)); assert_eq!(last_err.errno(), expected_errno); assert!(last_err.source().is_none()); assert_eq!(last_err, Error::from(io::Error::last_os_error())); assert_eq!(last_err, Error::last()); let last_err: io::Error = last_err.into(); assert_eq!(io::Error::last_os_error().kind(), last_err.kind()); } #[test] pub fn test_display() { #[cfg(unix)] assert_eq!( format!("{}", Error::new(libc::EBADF)), "Bad file descriptor (os error 9)" ); #[cfg(not(unix))] assert_eq!( format!("{}", Error::new(libc::EIO)), "Access is denied. (os error 5)" ); } }
let mut file = OpenOptions::new() .read(false) .write(true) .create(true) .truncate(true) .open(path) .unwrap();
assignment_statement
[ { "content": "fn modify_mode<F: FnOnce(&mut termios)>(fd: RawFd, f: F) -> Result<()> {\n\n // Safe because we check the return value of isatty.\n\n if unsafe { isatty(fd) } != 1 {\n\n return Ok(());\n\n }\n\n\n\n // The following pair are safe because termios gets totally overwritten by tcget...
Rust
crates/ra_ide/src/references/search_scope.rs
iTZAvishay/rust-analyzer
074474fe00a08d394cbdcac2a136bca825d93377
use std::mem; use hir::{DefWithBody, HasSource, ModuleSource}; use ra_db::{FileId, SourceDatabaseExt}; use ra_prof::profile; use ra_syntax::{AstNode, TextRange}; use rustc_hash::FxHashMap; use ra_ide_db::RootDatabase; use super::Definition; pub struct SearchScope { entries: FxHashMap<FileId, Option<TextRange>>, } impl SearchScope { fn empty() -> SearchScope { SearchScope { entries: FxHashMap::default() } } pub(crate) fn for_def(def: &Definition, db: &RootDatabase) -> SearchScope { let _p = profile("search_scope"); let module = match def.module(db) { Some(it) => it, None => return SearchScope::empty(), }; let module_src = module.definition_source(db); let file_id = module_src.file_id.original_file(db); if let Definition::Local(var) = def { let range = match var.parent(db) { DefWithBody::Function(f) => f.source(db).value.syntax().text_range(), DefWithBody::Const(c) => c.source(db).value.syntax().text_range(), DefWithBody::Static(s) => s.source(db).value.syntax().text_range(), }; let mut res = FxHashMap::default(); res.insert(file_id, Some(range)); return SearchScope::new(res); } let vis = def.visibility(db).as_ref().map(|v| v.syntax().to_string()).unwrap_or_default(); if vis.as_str() == "pub(super)" { if let Some(parent_module) = module.parent(db) { let mut res = FxHashMap::default(); let parent_src = parent_module.definition_source(db); let file_id = parent_src.file_id.original_file(db); match parent_src.value { ModuleSource::Module(m) => { let range = Some(m.syntax().text_range()); res.insert(file_id, range); } ModuleSource::SourceFile(_) => { res.insert(file_id, None); res.extend(parent_module.children(db).map(|m| { let src = m.definition_source(db); (src.file_id.original_file(db), None) })); } } return SearchScope::new(res); } } if vis.as_str() != "" { let source_root_id = db.file_source_root(file_id); let source_root = db.source_root(source_root_id); let mut res = source_root.walk().map(|id| (id, None)).collect::<FxHashMap<_, _>>(); if vis.as_str() == "pub(crate)" { return SearchScope::new(res); } if vis.as_str() == "pub" { let krate = module.krate(); for rev_dep in krate.reverse_dependencies(db) { let root_file = rev_dep.root_file(db); let source_root_id = db.file_source_root(root_file); let source_root = db.source_root(source_root_id); res.extend(source_root.walk().map(|id| (id, None))); } return SearchScope::new(res); } } let mut res = FxHashMap::default(); let range = match module_src.value { ModuleSource::Module(m) => Some(m.syntax().text_range()), ModuleSource::SourceFile(_) => None, }; res.insert(file_id, range); SearchScope::new(res) } fn new(entries: FxHashMap<FileId, Option<TextRange>>) -> SearchScope { SearchScope { entries } } pub fn single_file(file: FileId) -> SearchScope { SearchScope::new(std::iter::once((file, None)).collect()) } pub(crate) fn intersection(&self, other: &SearchScope) -> SearchScope { let (mut small, mut large) = (&self.entries, &other.entries); if small.len() > large.len() { mem::swap(&mut small, &mut large) } let res = small .iter() .filter_map(|(file_id, r1)| { let r2 = large.get(file_id)?; let r = intersect_ranges(*r1, *r2)?; Some((*file_id, r)) }) .collect(); return SearchScope::new(res); fn intersect_ranges( r1: Option<TextRange>, r2: Option<TextRange>, ) -> Option<Option<TextRange>> { match (r1, r2) { (None, r) | (r, None) => Some(r), (Some(r1), Some(r2)) => { let r = r1.intersection(&r2)?; Some(Some(r)) } } } } } impl IntoIterator for SearchScope { type Item = (FileId, Option<TextRange>); type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>; fn into_iter(self) -> Self::IntoIter { self.entries.into_iter() } }
use std::mem; use hir::{DefWithBody, HasSource, ModuleSource}; use ra_db::{FileId, SourceDatabaseExt}; use ra_prof::profile; use ra_syntax::{AstNode, TextRange}; use rustc_hash::FxHashMap; use ra_ide_db::RootDatabase; use super::Definition; pub struct SearchScope { entries: FxHashMap<FileId, Option<TextRange>>, } impl SearchScope { fn empty() -> SearchScope { SearchScope { entries: FxHashMap::default() } } pub(crate) fn for_def(def: &Definition, db: &RootDatabase) -> SearchScope { let _p = profile("search_scope"); let module = match def.module(db) { Some(it) => it, None => return SearchScope::empty(), }; let module_src = module.definition_source(db); let file_id = module_src.file_id.original_file(db); if let Definition::Local(var) = def { let range = match var.parent(db) { DefWithBody::Function(f) => f.source
parent_module.definition_source(db); let file_id = parent_src.file_id.original_file(db); match parent_src.value { ModuleSource::Module(m) => { let range = Some(m.syntax().text_range()); res.insert(file_id, range); } ModuleSource::SourceFile(_) => { res.insert(file_id, None); res.extend(parent_module.children(db).map(|m| { let src = m.definition_source(db); (src.file_id.original_file(db), None) })); } } return SearchScope::new(res); } } if vis.as_str() != "" { let source_root_id = db.file_source_root(file_id); let source_root = db.source_root(source_root_id); let mut res = source_root.walk().map(|id| (id, None)).collect::<FxHashMap<_, _>>(); if vis.as_str() == "pub(crate)" { return SearchScope::new(res); } if vis.as_str() == "pub" { let krate = module.krate(); for rev_dep in krate.reverse_dependencies(db) { let root_file = rev_dep.root_file(db); let source_root_id = db.file_source_root(root_file); let source_root = db.source_root(source_root_id); res.extend(source_root.walk().map(|id| (id, None))); } return SearchScope::new(res); } } let mut res = FxHashMap::default(); let range = match module_src.value { ModuleSource::Module(m) => Some(m.syntax().text_range()), ModuleSource::SourceFile(_) => None, }; res.insert(file_id, range); SearchScope::new(res) } fn new(entries: FxHashMap<FileId, Option<TextRange>>) -> SearchScope { SearchScope { entries } } pub fn single_file(file: FileId) -> SearchScope { SearchScope::new(std::iter::once((file, None)).collect()) } pub(crate) fn intersection(&self, other: &SearchScope) -> SearchScope { let (mut small, mut large) = (&self.entries, &other.entries); if small.len() > large.len() { mem::swap(&mut small, &mut large) } let res = small .iter() .filter_map(|(file_id, r1)| { let r2 = large.get(file_id)?; let r = intersect_ranges(*r1, *r2)?; Some((*file_id, r)) }) .collect(); return SearchScope::new(res); fn intersect_ranges( r1: Option<TextRange>, r2: Option<TextRange>, ) -> Option<Option<TextRange>> { match (r1, r2) { (None, r) | (r, None) => Some(r), (Some(r1), Some(r2)) => { let r = r1.intersection(&r2)?; Some(Some(r)) } } } } } impl IntoIterator for SearchScope { type Item = (FileId, Option<TextRange>); type IntoIter = std::collections::hash_map::IntoIter<FileId, Option<TextRange>>; fn into_iter(self) -> Self::IntoIter { self.entries.into_iter() } }
(db).value.syntax().text_range(), DefWithBody::Const(c) => c.source(db).value.syntax().text_range(), DefWithBody::Static(s) => s.source(db).value.syntax().text_range(), }; let mut res = FxHashMap::default(); res.insert(file_id, Some(range)); return SearchScope::new(res); } let vis = def.visibility(db).as_ref().map(|v| v.syntax().to_string()).unwrap_or_default(); if vis.as_str() == "pub(super)" { if let Some(parent_module) = module.parent(db) { let mut res = FxHashMap::default(); let parent_src =
random
[ { "content": "/// Build the signature of a callable item (function, struct or enum variant).\n\npub fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> PolyFnSig {\n\n match def {\n\n CallableDef::FunctionId(f) => fn_sig_for_fn(db, f),\n\n CallableDef::StructId(s) => fn_sig_for_str...
Rust
src/developer/ffx/lib/doctor_utils/src/recorder.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { anyhow::{anyhow, Result}, chrono::prelude::*, std::{ collections::HashMap, fs::File, io::{copy, Seek, SeekFrom, Write}, path::PathBuf, }, zip::{ write::{FileOptions, ZipWriter}, CompressionMethod, }, }; const FILE_MAX_BYTES: i64 = 4_000_000; pub trait Recorder { fn add_sources(&mut self, source_files: Vec<PathBuf>); fn add_content(&mut self, file_name: &str, content: String); fn generate(&self, output_dir: PathBuf) -> Result<PathBuf>; } pub struct DoctorRecorder { resource: HashMap<String, String>, source_files: Vec<PathBuf>, } impl DoctorRecorder { pub fn new() -> Self { Self { resource: HashMap::new(), source_files: vec![] } } fn copy_file(&self, source: &PathBuf, zip: &mut ZipWriter<File>) -> Result<()> { let mut f = File::open(source)?; let source_name = source.file_name().unwrap().to_string_lossy(); zip.start_file( source_name, FileOptions::default().compression_method(CompressionMethod::Stored), )?; if let Ok(meta) = f.metadata() { if meta.len() > FILE_MAX_BYTES as u64 { f.seek(SeekFrom::End(-FILE_MAX_BYTES))?; zip.write(b"<doctor: truncated for size>")?; } } copy(&mut f, zip).map(|_| {}).map_err(|e| anyhow!(e)) } } impl Recorder for DoctorRecorder { fn add_sources(&mut self, source_files: Vec<PathBuf>) { self.source_files.extend(source_files.into_iter()); } fn add_content(&mut self, file_name: &str, content: String) { let _ = self .resource .entry(file_name.to_string()) .and_modify(|e| e.push_str(&content)) .or_insert(content); } fn generate(&self, output_dir: PathBuf) -> Result<PathBuf> { let fname = format!("ffx-record-{}.zip", Local::now().format("%Y%m%d-%H%M%S")); let mut output_path = output_dir.clone(); output_path.push(fname); let file = File::create(output_path.clone())?; let mut zip = ZipWriter::new(file); for source in self.source_files.iter() { match self.copy_file(&source, &mut zip) { Ok(()) => {} Err(e) => { log::warn!( "unable to add '{}' to report zip: {:?}", source.file_name().and_then(std::ffi::OsStr::to_str).unwrap(), e ); continue; } } } for (file_name, resource) in self.resource.iter() { zip.start_file( file_name, FileOptions::default().compression_method(CompressionMethod::Stored), )?; zip.write(resource.as_bytes()).map_err(|e| anyhow!(e))?; } zip.finish().map_err(|e| anyhow!(e))?; Ok(output_path) } } #[cfg(test)] mod test { use { super::*, fuchsia_async as fasync, std::{ collections::HashSet, fs::File, io::{Read, Write}, }, tempfile::tempdir, zip::read::ZipArchive, }; const FAKE_OUTPUT: &str = "doctor doctor"; const DOCTOR_OUTPUT_NAME: &str = "doctor_output.txt"; const FILE_CONTENTS: &[u8] = b"fake log file"; const FILE_NAME: &str = "log.txt"; const NON_EXISTENT_FILE_NAME: &str = "does_not_exist.txt"; #[fasync::run_singlethreaded(test)] async fn test() -> Result<()> { let temp = tempdir()?; let root = temp.path().to_path_buf(); let mut f1path = root.clone(); f1path.push(FILE_NAME); let mut f1 = File::create(f1path.clone())?; f1.write_all(FILE_CONTENTS)?; let mut f2path = root.clone(); f2path.push(NON_EXISTENT_FILE_NAME); let mut rec = DoctorRecorder::new(); rec.add_sources(vec![f1path, f2path]); rec.add_content(DOCTOR_OUTPUT_NAME, FAKE_OUTPUT.to_string()); let path = rec.generate(root)?; let mut zip = ZipArchive::new(File::open(path)?)?; let actual_names: HashSet<_> = zip.file_names().collect(); let expected_names: HashSet<_> = vec![DOCTOR_OUTPUT_NAME, FILE_NAME].into_iter().collect(); assert_eq!(actual_names, expected_names); { let mut f1 = zip.by_name(FILE_NAME)?; let mut buf = String::new(); f1.read_to_string(&mut buf)?; assert_eq!(buf.into_bytes(), FILE_CONTENTS); } let mut output = zip.by_name(DOCTOR_OUTPUT_NAME)?; let mut buf = String::new(); output.read_to_string(&mut buf)?; assert_eq!(buf, FAKE_OUTPUT.to_string()); Ok(()) } }
use { anyhow::{anyhow, Result}, chrono::prelude::*, std::{ collections::HashMap, fs::File, io::{copy, Seek, SeekFrom, Write}, path::PathBuf, }, zip::{ write::{FileOptions, ZipWriter}, CompressionMethod, }, }; const FILE_MAX_BYTES: i64 = 4_000_000; pub trait Recorder { fn add_sources(&mut self, source_files: Vec<PathBuf>); fn add_content(&mut self, file_name: &str, content: String); fn generate(&self, output_dir: PathBuf) -> Result<PathBuf>; } pub struct DoctorRecorder { resource: HashMap<String, String>, source_files: Vec<PathBuf>, } impl DoctorRecorder { pub fn new() -> Self { Self { resource: HashMap::new(), source_files: vec![] } } fn copy_file(&self, source: &PathBuf, zip: &mut ZipWriter<File>) -> Result<()> { let mut f = File::open(source)?; let source_name = source.file_name().unwrap().to_string_lossy(); zip.start_file( source_name, FileOptions::default().compression_method(CompressionMethod::Stored), )?; if let Ok(meta) = f.metadata() { if meta.len() > FILE_MAX_BYTES as u64 { f.seek(SeekFrom::End(-FILE_MAX_BYTES))?; zip.write(b"<doctor: truncated for size>")?; } } copy(&mut f, zip).map(|_| {}).map_err(|e| anyhow!(e)) } } impl Recorder for DoctorRecorder { fn add_sources(&mut self, source_files: Vec<PathBuf>) { self.source_files.extend(source_files.into_iter()); } fn add_content(&mut self, file_name: &str, content: String) { let _ = self .resource .entry(file_name.to_string()) .and_modify(|e| e.push_str(&content)) .or_insert(content); }
} #[cfg(test)] mod test { use { super::*, fuchsia_async as fasync, std::{ collections::HashSet, fs::File, io::{Read, Write}, }, tempfile::tempdir, zip::read::ZipArchive, }; const FAKE_OUTPUT: &str = "doctor doctor"; const DOCTOR_OUTPUT_NAME: &str = "doctor_output.txt"; const FILE_CONTENTS: &[u8] = b"fake log file"; const FILE_NAME: &str = "log.txt"; const NON_EXISTENT_FILE_NAME: &str = "does_not_exist.txt"; #[fasync::run_singlethreaded(test)] async fn test() -> Result<()> { let temp = tempdir()?; let root = temp.path().to_path_buf(); let mut f1path = root.clone(); f1path.push(FILE_NAME); let mut f1 = File::create(f1path.clone())?; f1.write_all(FILE_CONTENTS)?; let mut f2path = root.clone(); f2path.push(NON_EXISTENT_FILE_NAME); let mut rec = DoctorRecorder::new(); rec.add_sources(vec![f1path, f2path]); rec.add_content(DOCTOR_OUTPUT_NAME, FAKE_OUTPUT.to_string()); let path = rec.generate(root)?; let mut zip = ZipArchive::new(File::open(path)?)?; let actual_names: HashSet<_> = zip.file_names().collect(); let expected_names: HashSet<_> = vec![DOCTOR_OUTPUT_NAME, FILE_NAME].into_iter().collect(); assert_eq!(actual_names, expected_names); { let mut f1 = zip.by_name(FILE_NAME)?; let mut buf = String::new(); f1.read_to_string(&mut buf)?; assert_eq!(buf.into_bytes(), FILE_CONTENTS); } let mut output = zip.by_name(DOCTOR_OUTPUT_NAME)?; let mut buf = String::new(); output.read_to_string(&mut buf)?; assert_eq!(buf, FAKE_OUTPUT.to_string()); Ok(()) } }
fn generate(&self, output_dir: PathBuf) -> Result<PathBuf> { let fname = format!("ffx-record-{}.zip", Local::now().format("%Y%m%d-%H%M%S")); let mut output_path = output_dir.clone(); output_path.push(fname); let file = File::create(output_path.clone())?; let mut zip = ZipWriter::new(file); for source in self.source_files.iter() { match self.copy_file(&source, &mut zip) { Ok(()) => {} Err(e) => { log::warn!( "unable to add '{}' to report zip: {:?}", source.file_name().and_then(std::ffi::OsStr::to_str).unwrap(), e ); continue; } } } for (file_name, resource) in self.resource.iter() { zip.start_file( file_name, FileOptions::default().compression_method(CompressionMethod::Stored), )?; zip.write(resource.as_bytes()).map_err(|e| anyhow!(e))?; } zip.finish().map_err(|e| anyhow!(e))?; Ok(output_path) }
function_block-full_function
[]
Rust
src/tools/clippy/clippy_lints/src/needless_for_each.rs
stevepentland/rust
57d8747cca741de84918800dca13da0c821e33e0
use rustc_errors::Applicability; use rustc_hir::{ intravisit::{walk_expr, NestedVisitorMap, Visitor}, Expr, ExprKind, Stmt, StmtKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{source_map::Span, sym, Symbol}; use if_chain::if_chain; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_trait_method; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::has_iter_method; declare_clippy_lint! { pub NEEDLESS_FOR_EACH, pedantic, "using `for_each` where a `for` loop would be simpler" } declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]); impl LateLintPass<'_> for NeedlessForEach { fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { let expr = match stmt.kind { StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr, _ => return, }; if_chain! { if let ExprKind::MethodCall(method_name, _, [for_each_recv, for_each_arg], _) = expr.kind; if method_name.ident.name == Symbol::intern("for_each"); if is_trait_method(cx, expr, sym::Iterator); if let ExprKind::MethodCall(_, _, [iter_recv], _) = for_each_recv.kind; if matches!( iter_recv.kind, ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..) ); if has_iter_method(cx, cx.typeck_results().expr_ty(iter_recv)).is_some(); if let ExprKind::Closure(_, _, body_id, ..) = for_each_arg.kind; let body = cx.tcx.hir().body(body_id); if let ExprKind::Block(..) = body.value.kind; then { let mut ret_collector = RetCollector::default(); ret_collector.visit_expr(&body.value); if ret_collector.ret_in_loop { return; } let (mut applicability, ret_suggs) = if ret_collector.spans.is_empty() { (Applicability::MachineApplicable, None) } else { ( Applicability::MaybeIncorrect, Some( ret_collector .spans .into_iter() .map(|span| (span, "continue".to_string())) .collect(), ), ) }; let sugg = format!( "for {} in {} {}", snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability), snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability), snippet_with_applicability(cx, body.value.span, "..", &mut applicability), ); span_lint_and_then(cx, NEEDLESS_FOR_EACH, stmt.span, "needless use of `for_each`", |diag| { diag.span_suggestion(stmt.span, "try", sugg, applicability); if let Some(ret_suggs) = ret_suggs { diag.multipart_suggestion("...and replace `return` with `continue`", ret_suggs, applicability); } }) } } } } #[derive(Default)] struct RetCollector { spans: Vec<Span>, ret_in_loop: bool, loop_depth: u16, } impl<'tcx> Visitor<'tcx> for RetCollector { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &Expr<'_>) { match expr.kind { ExprKind::Ret(..) => { if self.loop_depth > 0 && !self.ret_in_loop { self.ret_in_loop = true; } self.spans.push(expr.span); }, ExprKind::Loop(..) => { self.loop_depth += 1; walk_expr(self, expr); self.loop_depth -= 1; return; }, _ => {}, } walk_expr(self, expr); } fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::None } }
use rustc_errors::Applicability; use rustc_hir::{ intravisit::{walk_expr, NestedVisitorMap, Visitor}, Expr, ExprKind, Stmt, StmtKind, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{source_map::Span, sym, Symbol}; use if_chain::if_chain; use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::is_trait_method; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::has_iter_method; declare_clippy_lint! { pub NEEDLESS_FOR_EACH, pedantic, "using `for_each` where a `for` loop would be simpler" } declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]); impl LateLintPass<'_> for NeedlessForEach {
} #[derive(Default)] struct RetCollector { spans: Vec<Span>, ret_in_loop: bool, loop_depth: u16, } impl<'tcx> Visitor<'tcx> for RetCollector { type Map = Map<'tcx>; fn visit_expr(&mut self, expr: &Expr<'_>) { match expr.kind { ExprKind::Ret(..) => { if self.loop_depth > 0 && !self.ret_in_loop { self.ret_in_loop = true; } self.spans.push(expr.span); }, ExprKind::Loop(..) => { self.loop_depth += 1; walk_expr(self, expr); self.loop_depth -= 1; return; }, _ => {}, } walk_expr(self, expr); } fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { NestedVisitorMap::None } }
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) { let expr = match stmt.kind { StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr, _ => return, }; if_chain! { if let ExprKind::MethodCall(method_name, _, [for_each_recv, for_each_arg], _) = expr.kind; if method_name.ident.name == Symbol::intern("for_each"); if is_trait_method(cx, expr, sym::Iterator); if let ExprKind::MethodCall(_, _, [iter_recv], _) = for_each_recv.kind; if matches!( iter_recv.kind, ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..) ); if has_iter_method(cx, cx.typeck_results().expr_ty(iter_recv)).is_some(); if let ExprKind::Closure(_, _, body_id, ..) = for_each_arg.kind; let body = cx.tcx.hir().body(body_id); if let ExprKind::Block(..) = body.value.kind; then { let mut ret_collector = RetCollector::default(); ret_collector.visit_expr(&body.value); if ret_collector.ret_in_loop { return; } let (mut applicability, ret_suggs) = if ret_collector.spans.is_empty() { (Applicability::MachineApplicable, None) } else { ( Applicability::MaybeIncorrect, Some( ret_collector .spans .into_iter() .map(|span| (span, "continue".to_string())) .collect(), ), ) }; let sugg = format!( "for {} in {} {}", snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability), snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability), snippet_with_applicability(cx, body.value.span, "..", &mut applicability), ); span_lint_and_then(cx, NEEDLESS_FOR_EACH, stmt.span, "needless use of `for_each`", |diag| { diag.span_suggestion(stmt.span, "try", sugg, applicability); if let Some(ret_suggs) = ret_suggs { diag.multipart_suggestion("...and replace `return` with `continue`", ret_suggs, applicability); } }) } } }
function_block-full_function
[]
Rust
src/binding_layout_tests.rs
nervosnetwork/blake2b-rs
1ecc3d2986977ea2ac8fb04fd0566332465d349a
use crate::binding::*; #[test] fn bindgen_test_layout_max_align_t() { assert_eq!( ::core::mem::size_of::<max_align_t>(), 32usize, concat!("Size of: ", stringify!(max_align_t)) ); assert_eq!( ::core::mem::align_of::<max_align_t>(), 16usize, concat!("Alignment of ", stringify!(max_align_t)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<max_align_t>())).__clang_max_align_nonce1 as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(max_align_t), "::", stringify!(__clang_max_align_nonce1) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<max_align_t>())).__clang_max_align_nonce2 as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(max_align_t), "::", stringify!(__clang_max_align_nonce2) ) ); } #[test] fn bindgen_test_layout___fsid_t() { assert_eq!( ::core::mem::size_of::<__fsid_t>(), 8usize, concat!("Size of: ", stringify!(__fsid_t)) ); assert_eq!( ::core::mem::align_of::<__fsid_t>(), 4usize, concat!("Alignment of ", stringify!(__fsid_t)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<__fsid_t>())).__val as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(__fsid_t), "::", stringify!(__val) ) ); } #[test] fn bindgen_test_layout_blake2b_state__() { assert_eq!( ::core::mem::size_of::<blake2b_state__>(), 248usize, concat!("Size of: ", stringify!(blake2b_state__)) ); assert_eq!( ::core::mem::align_of::<blake2b_state__>(), 8usize, concat!("Alignment of ", stringify!(blake2b_state__)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).h as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(h) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).t as *const _ as usize }, 64usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(t) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).f as *const _ as usize }, 80usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(f) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).buf as *const _ as usize }, 96usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(buf) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).buflen as *const _ as usize }, 224usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(buflen) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).outlen as *const _ as usize }, 232usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(outlen) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).last_node as *const _ as usize }, 240usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(last_node) ) ); } #[test] fn bindgen_test_layout_blake2b_param__() { assert_eq!( ::core::mem::size_of::<blake2b_param__>(), 64usize, concat!("Size of: ", stringify!(blake2b_param__)) ); assert_eq!( ::core::mem::align_of::<blake2b_param__>(), 1usize, concat!("Alignment of ", stringify!(blake2b_param__)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).digest_length as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(digest_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).key_length as *const _ as usize }, 1usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(key_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).fanout as *const _ as usize }, 2usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(fanout) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).depth as *const _ as usize }, 3usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(depth) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).leaf_length as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(leaf_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).node_offset as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(node_offset) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).xof_length as *const _ as usize }, 12usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(xof_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).node_depth as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(node_depth) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).inner_length as *const _ as usize }, 17usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(inner_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).reserved as *const _ as usize }, 18usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(reserved) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).salt as *const _ as usize }, 32usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(salt) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).personal as *const _ as usize }, 48usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(personal) ) ); }
use crate::binding::*; #[test] fn bindgen_test_layout_max_align_t() { assert_eq!( ::core::mem::size_of::<max_align_t>(), 32usize, concat!("Size of: ", stringify!(max_align_t)) ); assert_eq!( ::core::mem::align_of::<max_align_t>(), 16usize, concat!("Alignment of ", stringify!(max_align_t)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<max_align_t>())).__clang_max_align_nonce1 as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(max_align_t), "::", stringify!(__clang_max_align_nonce1) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<max_align_t>())).__clang_max_align_nonce2 as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(max_align_t), "::", stringify!(__clang_max_align_nonce2) ) ); } #[test]
#[test] fn bindgen_test_layout_blake2b_state__() { assert_eq!( ::core::mem::size_of::<blake2b_state__>(), 248usize, concat!("Size of: ", stringify!(blake2b_state__)) ); assert_eq!( ::core::mem::align_of::<blake2b_state__>(), 8usize, concat!("Alignment of ", stringify!(blake2b_state__)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).h as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(h) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).t as *const _ as usize }, 64usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(t) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).f as *const _ as usize }, 80usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(f) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).buf as *const _ as usize }, 96usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(buf) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).buflen as *const _ as usize }, 224usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(buflen) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).outlen as *const _ as usize }, 232usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(outlen) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_state__>())).last_node as *const _ as usize }, 240usize, concat!( "Offset of field: ", stringify!(blake2b_state__), "::", stringify!(last_node) ) ); } #[test] fn bindgen_test_layout_blake2b_param__() { assert_eq!( ::core::mem::size_of::<blake2b_param__>(), 64usize, concat!("Size of: ", stringify!(blake2b_param__)) ); assert_eq!( ::core::mem::align_of::<blake2b_param__>(), 1usize, concat!("Alignment of ", stringify!(blake2b_param__)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).digest_length as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(digest_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).key_length as *const _ as usize }, 1usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(key_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).fanout as *const _ as usize }, 2usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(fanout) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).depth as *const _ as usize }, 3usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(depth) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).leaf_length as *const _ as usize }, 4usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(leaf_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).node_offset as *const _ as usize }, 8usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(node_offset) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).xof_length as *const _ as usize }, 12usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(xof_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).node_depth as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(node_depth) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).inner_length as *const _ as usize }, 17usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(inner_length) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).reserved as *const _ as usize }, 18usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(reserved) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).salt as *const _ as usize }, 32usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(salt) ) ); assert_eq!( unsafe { &(*(::core::ptr::null::<blake2b_param__>())).personal as *const _ as usize }, 48usize, concat!( "Offset of field: ", stringify!(blake2b_param__), "::", stringify!(personal) ) ); }
fn bindgen_test_layout___fsid_t() { assert_eq!( ::core::mem::size_of::<__fsid_t>(), 8usize, concat!("Size of: ", stringify!(__fsid_t)) ); assert_eq!( ::core::mem::align_of::<__fsid_t>(), 4usize, concat!("Alignment of ", stringify!(__fsid_t)) ); assert_eq!( unsafe { &(*(::core::ptr::null::<__fsid_t>())).__val as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(__fsid_t), "::", stringify!(__val) ) ); }
function_block-full_function
[ { "content": "fn main() {\n\n // Some target(e.g. wasm32-unknown-unknown) won't have this flag\n\n // defined since it has not features.\n\n let features = std::env::var(\"CARGO_CFG_TARGET_FEATURE\").unwrap_or_default();\n\n if features.contains(\"sse4.1\") || features.contains(\"sse2\") {\n\n ...
Rust
src/rules/no_regex_spaces.rs
hugo-paul/deno_lint
d46a89fe4569f8ab0596996bb0a98a70b4a34b05
use super::Context; use super::LintRule; use crate::scopes::{ScopeManager, ScopeVisitor}; use swc_ecma_ast::{CallExpr, Expr, ExprOrSuper, Lit, NewExpr, Regex}; use swc_ecma_visit::Node; use swc_ecma_visit::Visit; pub struct NoRegexSpaces; impl LintRule for NoRegexSpaces { fn new() -> Box<Self> { Box::new(NoRegexSpaces) } fn code(&self) -> &'static str { "no-regex-spaces" } fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) { let mut scope_visitor = ScopeVisitor::new(); scope_visitor.visit_module(&module, &module); let scope_manager = scope_visitor.consume(); let mut visitor = NoRegexSpacesVisitor::new(context, scope_manager); visitor.visit_module(&module, &module); } } pub struct NoRegexSpacesVisitor { context: Context, scope_manager: ScopeManager, } impl NoRegexSpacesVisitor { pub fn new(context: Context, scope_manager: ScopeManager) -> Self { Self { context, scope_manager, } } fn check_regex(&self, regex: &str) -> bool { lazy_static! { static ref DOUBLE_SPACE: regex::Regex = regex::Regex::new(r"(?u) {2}").unwrap(); static ref BRACKETS: regex::Regex = regex::Regex::new(r"\[.*?[^\\]\]").unwrap(); static ref SPACES: regex::Regex = regex::Regex::new(r#"(?u)( {2,})(?: [+*{?]|[^+*{?]|$)"#).unwrap(); } if !DOUBLE_SPACE.is_match(regex) { return false; } let mut character_classes = vec![]; for mtch in BRACKETS.find_iter(regex) { character_classes.push((mtch.start(), mtch.end())); } for mtch in SPACES.find_iter(regex) { let not_in_classes = &character_classes .iter() .all(|ref v| mtch.start() < v.0 || v.1 <= mtch.start()); if *not_in_classes { return true; } } false } } impl Visit for NoRegexSpacesVisitor { fn visit_regex(&mut self, regex: &Regex, _parent: &dyn Node) { if self.check_regex(regex.exp.to_string().as_ref()) { self.context.add_diagnostic( regex.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } fn visit_new_expr(&mut self, new_expr: &NewExpr, _parent: &dyn Node) { if let Expr::Ident(ident) = &*new_expr.callee { let name = ident.sym.to_string(); if name != "RegExp" { return; } let scope = self.scope_manager.get_scope_for_span(new_expr.span); if self.scope_manager.get_binding(scope, &ident.sym).is_some() { return; } if let Some(args) = &new_expr.args { if let Some(first_arg) = args.get(0) { let regex_literal = if let Expr::Lit(Lit::Str(literal)) = &*first_arg.expr { &literal.value } else if let Expr::Lit(Lit::Regex(regex)) = &*first_arg.expr { &regex.exp } else { return; }; if self.check_regex(regex_literal.as_ref()) { self.context.add_diagnostic( new_expr.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } } } } fn visit_call_expr(&mut self, call_expr: &CallExpr, _parent: &dyn Node) { if let ExprOrSuper::Expr(expr) = &call_expr.callee { if let Expr::Ident(ident) = expr.as_ref() { let name = ident.sym.to_string(); if name != "RegExp" { return; } let scope = self.scope_manager.get_scope_for_span(call_expr.span); if self.scope_manager.get_binding(scope, &ident.sym).is_some() { return; } if !call_expr.args.is_empty() { if let Some(first_arg) = call_expr.args.get(0) { let regex_literal = if let Expr::Lit(Lit::Str(literal)) = &*first_arg.expr { &literal.value } else if let Expr::Lit(Lit::Regex(regex)) = &*first_arg.expr { &regex.exp } else { return; }; if self.check_regex(regex_literal.as_ref()) { self.context.add_diagnostic( call_expr.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } }; } } } } #[cfg(test)] mod tests { use super::*; use crate::test_util::*; #[test] fn no_regex_spaces_valid() { assert_lint_ok_n::<NoRegexSpaces>(vec![ "var foo = /foo/;", "var foo = RegExp('foo')", "var foo = / /;", "var foo = RegExp(' ')", "var foo = / a b c d /;", "var foo = /bar {3}baz/g;", "var foo = RegExp('bar {3}baz', 'g')", "var foo = new RegExp('bar {3}baz')", "var foo = /bar\t\t\tbaz/;", "var foo = RegExp('bar\t\t\tbaz');", "var foo = new RegExp('bar\t\t\tbaz');", "var foo = / +/;", "var foo = / ?/;", "var foo = / */;", "var foo = / {2}/;", "var RegExp = function() {}; var foo = new RegExp('bar baz');", "var RegExp = function() {}; var foo = RegExp('bar baz');", r"var foo = /bar \\ baz/;", r"var foo = /bar\\ \\ baz/;", r"var foo = /bar \\u0020 baz/;", r"var foo = /bar\\u0020\\u0020baz/;", r"var foo = new RegExp('bar \\ baz')", r"var foo = new RegExp('bar\\ \\ baz')", r"var foo = new RegExp('bar \\\\ baz')", r"var foo = new RegExp('bar \\u0020 baz')", r"var foo = new RegExp('bar\\u0020\\u0020baz')", r"var foo = new RegExp('bar \\\\u0020 baz')", "var foo = /[ ]/;", "var foo = /[ ]/;", "var foo = / [ ] /;", "var foo = / [ ] [ ] /;", "var foo = new RegExp('[ ]');", "var foo = new RegExp('[ ]');", "var foo = new RegExp(' [ ] ');", "var foo = RegExp(' [ ] [ ] ');", "var foo = new RegExp(' \\[ \\] ');", ]); } #[test] fn no_regex_spaces_invalid() { assert_lint_err::<NoRegexSpaces>("let foo = /bar baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = / a b c d /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp(' a b c d ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('bar baz');", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('bar baz');", 10); assert_lint_err::<NoRegexSpaces>( "{ let RegExp = function() {}; } var foo = RegExp('bar baz');", 42, ); assert_lint_err::<NoRegexSpaces>("let foo = /bar {3}baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar ?baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('bar +baz')", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('bar ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar\\ baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /[ ] /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = / [ ] /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('[ ] ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp(' [ ]');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\[ /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\[ \\]/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /(?: )/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('^foo(?= )');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\ /", 10); assert_lint_err::<NoRegexSpaces>("let foo = / \\ /", 10); assert_lint_err::<NoRegexSpaces>("let foo = / foo /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('\\\\d ')", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('\\u0041 ')", 10); assert_lint_err::<NoRegexSpaces>( "let foo = new RegExp('\\\\[ \\\\]');", 10, ); } }
use super::Context; use super::LintRule; use crate::scopes::{ScopeManager, ScopeVisitor}; use swc_ecma_ast::{CallExpr, Expr, ExprOrSuper, Lit, NewExpr, Regex}; use swc_ecma_visit::Node; use swc_ecma_visit::Visit; pub struct NoRegexSpaces; impl LintRule for NoRegexSpaces { fn new() -> Box<Self> { Box::new(NoRegexSpaces) } fn code(&self) -> &'static str { "no-regex-spaces" }
} pub struct NoRegexSpacesVisitor { context: Context, scope_manager: ScopeManager, } impl NoRegexSpacesVisitor { pub fn new(context: Context, scope_manager: ScopeManager) -> Self { Self { context, scope_manager, } } fn check_regex(&self, regex: &str) -> bool { lazy_static! { static ref DOUBLE_SPACE: regex::Regex = regex::Regex::new(r"(?u) {2}").unwrap(); static ref BRACKETS: regex::Regex = regex::Regex::new(r"\[.*?[^\\]\]").unwrap(); static ref SPACES: regex::Regex = regex::Regex::new(r#"(?u)( {2,})(?: [+*{?]|[^+*{?]|$)"#).unwrap(); } if !DOUBLE_SPACE.is_match(regex) { return false; } let mut character_classes = vec![]; for mtch in BRACKETS.find_iter(regex) { character_classes.push((mtch.start(), mtch.end())); } for mtch in SPACES.find_iter(regex) { let not_in_classes = &character_classes .iter() .all(|ref v| mtch.start() < v.0 || v.1 <= mtch.start()); if *not_in_classes { return true; } } false } } impl Visit for NoRegexSpacesVisitor { fn visit_regex(&mut self, regex: &Regex, _parent: &dyn Node) { if self.check_regex(regex.exp.to_string().as_ref()) { self.context.add_diagnostic( regex.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } fn visit_new_expr(&mut self, new_expr: &NewExpr, _parent: &dyn Node) { if let Expr::Ident(ident) = &*new_expr.callee { let name = ident.sym.to_string(); if name != "RegExp" { return; } let scope = self.scope_manager.get_scope_for_span(new_expr.span); if self.scope_manager.get_binding(scope, &ident.sym).is_some() { return; } if let Some(args) = &new_expr.args { if let Some(first_arg) = args.get(0) { let regex_literal = if let Expr::Lit(Lit::Str(literal)) = &*first_arg.expr { &literal.value } else if let Expr::Lit(Lit::Regex(regex)) = &*first_arg.expr { &regex.exp } else { return; }; if self.check_regex(regex_literal.as_ref()) { self.context.add_diagnostic( new_expr.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } } } } fn visit_call_expr(&mut self, call_expr: &CallExpr, _parent: &dyn Node) { if let ExprOrSuper::Expr(expr) = &call_expr.callee { if let Expr::Ident(ident) = expr.as_ref() { let name = ident.sym.to_string(); if name != "RegExp" { return; } let scope = self.scope_manager.get_scope_for_span(call_expr.span); if self.scope_manager.get_binding(scope, &ident.sym).is_some() { return; } if !call_expr.args.is_empty() { if let Some(first_arg) = call_expr.args.get(0) { let regex_literal = if let Expr::Lit(Lit::Str(literal)) = &*first_arg.expr { &literal.value } else if let Expr::Lit(Lit::Regex(regex)) = &*first_arg.expr { &regex.exp } else { return; }; if self.check_regex(regex_literal.as_ref()) { self.context.add_diagnostic( call_expr.span, "no-regex-spaces", "more than one consecutive spaces in RegExp is not allowed", ); } } }; } } } } #[cfg(test)] mod tests { use super::*; use crate::test_util::*; #[test] fn no_regex_spaces_valid() { assert_lint_ok_n::<NoRegexSpaces>(vec![ "var foo = /foo/;", "var foo = RegExp('foo')", "var foo = / /;", "var foo = RegExp(' ')", "var foo = / a b c d /;", "var foo = /bar {3}baz/g;", "var foo = RegExp('bar {3}baz', 'g')", "var foo = new RegExp('bar {3}baz')", "var foo = /bar\t\t\tbaz/;", "var foo = RegExp('bar\t\t\tbaz');", "var foo = new RegExp('bar\t\t\tbaz');", "var foo = / +/;", "var foo = / ?/;", "var foo = / */;", "var foo = / {2}/;", "var RegExp = function() {}; var foo = new RegExp('bar baz');", "var RegExp = function() {}; var foo = RegExp('bar baz');", r"var foo = /bar \\ baz/;", r"var foo = /bar\\ \\ baz/;", r"var foo = /bar \\u0020 baz/;", r"var foo = /bar\\u0020\\u0020baz/;", r"var foo = new RegExp('bar \\ baz')", r"var foo = new RegExp('bar\\ \\ baz')", r"var foo = new RegExp('bar \\\\ baz')", r"var foo = new RegExp('bar \\u0020 baz')", r"var foo = new RegExp('bar\\u0020\\u0020baz')", r"var foo = new RegExp('bar \\\\u0020 baz')", "var foo = /[ ]/;", "var foo = /[ ]/;", "var foo = / [ ] /;", "var foo = / [ ] [ ] /;", "var foo = new RegExp('[ ]');", "var foo = new RegExp('[ ]');", "var foo = new RegExp(' [ ] ');", "var foo = RegExp(' [ ] [ ] ');", "var foo = new RegExp(' \\[ \\] ');", ]); } #[test] fn no_regex_spaces_invalid() { assert_lint_err::<NoRegexSpaces>("let foo = /bar baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = / a b c d /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp(' a b c d ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('bar baz');", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('bar baz');", 10); assert_lint_err::<NoRegexSpaces>( "{ let RegExp = function() {}; } var foo = RegExp('bar baz');", 42, ); assert_lint_err::<NoRegexSpaces>("let foo = /bar {3}baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar ?baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('bar +baz')", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('bar ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /bar\\ baz/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /[ ] /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = / [ ] /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('[ ] ');", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp(' [ ]');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\[ /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\[ \\]/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = /(?: )/;", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('^foo(?= )');", 10); assert_lint_err::<NoRegexSpaces>("let foo = /\\ /", 10); assert_lint_err::<NoRegexSpaces>("let foo = / \\ /", 10); assert_lint_err::<NoRegexSpaces>("let foo = / foo /;", 10); assert_lint_err::<NoRegexSpaces>("let foo = new RegExp('\\\\d ')", 10); assert_lint_err::<NoRegexSpaces>("let foo = RegExp('\\u0041 ')", 10); assert_lint_err::<NoRegexSpaces>( "let foo = new RegExp('\\\\[ \\\\]');", 10, ); } }
fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) { let mut scope_visitor = ScopeVisitor::new(); scope_visitor.visit_module(&module, &module); let scope_manager = scope_visitor.consume(); let mut visitor = NoRegexSpacesVisitor::new(context, scope_manager); visitor.visit_module(&module, &module); }
function_block-full_function
[ { "content": "pub fn assert_lint_ok<T: LintRule + 'static>(source: &str) {\n\n let rule = T::new();\n\n let diagnostics = lint(rule, source);\n\n if !diagnostics.is_empty() {\n\n panic!(\"Unexpected diagnostics: {:#?}\", diagnostics);\n\n }\n\n}\n\n\n", "file_path": "src/test_util.rs", "rank": 0,...
Rust
src/prolog/heap_iter.rs
GavinMendelGleason/scryer-prolog
9e54b1406c9982258f43234401ea29c8b45f44eb
use crate::prolog::machine::machine_indices::*; use crate::prolog::machine::machine_state::*; use indexmap::IndexSet; use std::cmp::Ordering; use std::ops::Deref; use std::vec::Vec; pub struct HCPreOrderIterator<'a> { pub machine_st: &'a MachineState, pub state_stack: Vec<Addr>, } impl<'a> HCPreOrderIterator<'a> { pub fn new(machine_st: &'a MachineState, a: Addr) -> Self { HCPreOrderIterator { machine_st, state_stack: vec![a], } } #[inline] pub fn machine_st(&self) -> &MachineState { &self.machine_st } fn follow_heap(&mut self, h: usize) -> Addr { match &self.machine_st.heap[h] { &HeapCellValue::NamedStr(arity, _, _) => { for idx in (1 .. arity + 1).rev() { self.state_stack.push(Addr::HeapCell(h + idx)); } Addr::Str(h) } &HeapCellValue::Addr(a) => { self.follow(a) } HeapCellValue::PartialString(..) => { self.follow(Addr::PStrLocation(h, 0)) } HeapCellValue::Atom(..) | HeapCellValue::DBRef(_) | HeapCellValue::Integer(_) | HeapCellValue::Rational(_) => { Addr::Con(h) } HeapCellValue::Stream(_) => { Addr::Stream(h) } } } fn follow(&mut self, addr: Addr) -> Addr { let da = self.machine_st.store(self.machine_st.deref(addr)); match da { Addr::Lis(a) => { self.state_stack.push(Addr::HeapCell(a + 1)); self.state_stack.push(Addr::HeapCell(a)); da } Addr::PStrLocation(h, n) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.machine_st.heap[h] { if let Some(c) = pstr.range_from(n ..).next() { if !pstr.at_end(n + c.len_utf8()) { self.state_stack.push(Addr::PStrLocation(h, n + c.len_utf8())); } else if has_tail { self.state_stack.push(Addr::HeapCell(h + 1)); } else { self.state_stack.push(Addr::EmptyList); } self.state_stack.push(Addr::Char(c)); } else if has_tail { return self.follow(Addr::HeapCell(h + 1)); } } else { unreachable!() } Addr::PStrLocation(h, n) } Addr::Str(s) => { self.follow_heap(s) } Addr::Con(h) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.machine_st.heap[h] { if !self.machine_st.flags.double_quotes.is_atom() { return if let Some(c) = pstr.range_from(0 ..).next() { self.state_stack.push(Addr::PStrLocation(h, c.len_utf8())); self.state_stack.push(Addr::Char(c)); Addr::PStrLocation(h, 0) } else if has_tail { self.follow(Addr::HeapCell(h + 1)) } else { Addr::EmptyList }; } } Addr::Con(h) } da => { da } } } } impl<'a> Iterator for HCPreOrderIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { self.state_stack.pop().map(|a| self.follow(a)) } } pub trait MutStackHCIterator where Self: Iterator<Item = Addr> { fn stack(&mut self) -> &mut Vec<Addr>; } pub struct HCPostOrderIterator<'a> { base_iter: HCPreOrderIterator<'a>, parent_stack: Vec<(usize, Addr)>, } impl<'a> Deref for HCPostOrderIterator<'a> { type Target = HCPreOrderIterator<'a>; fn deref(&self) -> &Self::Target { &self.base_iter } } impl<'a> HCPostOrderIterator<'a> { pub fn new(base_iter: HCPreOrderIterator<'a>) -> Self { HCPostOrderIterator { base_iter, parent_stack: vec![], } } } impl<'a> Iterator for HCPostOrderIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { loop { if let Some((child_count, node)) = self.parent_stack.pop() { if child_count == 0 { return Some(node); } self.parent_stack.push((child_count - 1, node)); } if let Some(item) = self.base_iter.next() { match self.base_iter.machine_st.heap.index_addr(&item).as_ref() { &HeapCellValue::NamedStr(arity, ..) => { self.parent_stack.push((arity, item)); } &HeapCellValue::Addr(Addr::Lis(a)) => { self.parent_stack.push((2, Addr::Lis(a))); } &HeapCellValue::Addr(Addr::PStrLocation(h, n)) => { match &self.machine_st.heap[h] { &HeapCellValue::PartialString(ref pstr, _) => { let c = pstr.range_from(n ..).next().unwrap(); let next_n = n + c.len_utf8(); if !pstr.at_end(next_n) { self.parent_stack.push((2, Addr::PStrLocation(h, next_n))); } } _ => { unreachable!() } } } _ => { return Some(item); } } } else { return None; } } } } impl MachineState { pub fn pre_order_iter<'a>(&'a self, a: Addr) -> HCPreOrderIterator<'a> { HCPreOrderIterator::new(self, a) } pub fn post_order_iter<'a>(&'a self, a: Addr) -> HCPostOrderIterator<'a> { HCPostOrderIterator::new(HCPreOrderIterator::new(self, a)) } pub fn acyclic_pre_order_iter<'a>(&'a self, a: Addr,) -> HCAcyclicIterator<'a> { HCAcyclicIterator::new(HCPreOrderIterator::new(self, a)) } pub fn zipped_acyclic_pre_order_iter<'a>( &'a self, a1: Addr, a2: Addr, ) -> HCZippedAcyclicIterator<'a> { HCZippedAcyclicIterator::new( HCPreOrderIterator::new(self, a1), HCPreOrderIterator::new(self, a2), ) } } impl<'a> MutStackHCIterator for HCPreOrderIterator<'a> { fn stack(&mut self) -> &mut Vec<Addr> { &mut self.state_stack } } pub struct HCAcyclicIterator<'a> { iter: HCPreOrderIterator<'a>, seen: IndexSet<Addr>, } impl<'a> HCAcyclicIterator<'a> { pub fn new(iter: HCPreOrderIterator<'a>) -> Self { HCAcyclicIterator { iter, seen: IndexSet::new(), } } } impl<'a> Deref for HCAcyclicIterator<'a> { type Target = HCPreOrderIterator<'a>; fn deref(&self) -> &Self::Target { &self.iter } } impl<'a> Iterator for HCAcyclicIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { while let Some(addr) = self.iter.stack().pop() { if !self.seen.contains(&addr) { self.iter.stack().push(addr.clone()); self.seen.insert(addr); break; } } self.iter.next() } } pub struct HCZippedAcyclicIterator<'a> { i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>, seen: IndexSet<(Addr, Addr)>, pub first_to_expire: Ordering, } impl<'a> HCZippedAcyclicIterator<'a> { pub fn new(i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>) -> Self { HCZippedAcyclicIterator { i1, i2, seen: IndexSet::new(), first_to_expire: Ordering::Equal, } } } impl<'a> Iterator for HCZippedAcyclicIterator<'a> { type Item = (Addr, Addr); fn next(&mut self) -> Option<Self::Item> { while let (Some(a1), Some(a2)) = (self.i1.stack().pop(), self.i2.stack().pop()) { if !self.seen.contains(&(a1.clone(), a2.clone())) { self.i1.stack().push(a1.clone()); self.i2.stack().push(a2.clone()); self.seen.insert((a1, a2)); break; } } match (self.i1.next(), self.i2.next()) { (Some(v1), Some(v2)) => Some((v1, v2)), (Some(_), None) => { self.first_to_expire = Ordering::Greater; None } (None, Some(_)) => { self.first_to_expire = Ordering::Less; None } _ => { None } } } }
use crate::prolog::machine::machine_indices::*; use crate::prolog::machine::machine_state::*; use indexmap::IndexSet; use std::cmp::Ordering; use std::ops::Deref; use std::vec::Vec; pub struct HCPreOrderIterator<'a> { pub machine_st: &'a MachineState, pub state_stack: Vec<Addr>, } impl<'a> HCPreOrderIterator<'a> { pub fn new(machine_st: &'a MachineState, a: Addr) -> Self { HCPreOrderIterator { machine_st, state_stack: vec![a], } } #[inline] pub fn machine_st(&self) -> &MachineState { &self.machine_st } fn follow_heap(&mut self, h: usize) -> Addr { match &self.machine_st.heap[h] { &HeapCellValue::NamedStr(arity, _, _) => { for idx in (1 .. arity + 1).rev() { self.state_stack.push(Addr::HeapCell(h + idx)); } Addr::Str(h) } &HeapCellValue::Addr(a) => { self.follow(a) } HeapCellValue::PartialString(..) => { self.follow(Addr::PStrLocation(h, 0)) } HeapCellValue::Atom(..) | HeapCellValue::DBRef(_) | HeapCellValue::Integer(_) | HeapCellValue::Rational(_) => { Addr::Con(h) } HeapCellValue::Stream(_) => { Addr::Stream(h) } } } fn follow(&mut self, addr: Addr) -> Addr { let da = self.machine_st.store(self.machine_st.deref(addr)); match da { Addr::Lis(a) => { self.state_stack.push(Addr::HeapCell(a + 1)); self.state_stack.push(Addr::HeapCell(a)); da } Addr::PStrLocation(h, n) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.machine_st.heap[h] { if let Some(c) = pstr.range_from(n ..).next() { if !pstr.at_end(n + c.len_utf8()) { self.state_stack.push(Addr::PStrLocation(h, n + c.len_utf8())); } else if has_tail { self.state_stack.push(Addr::HeapCell(h + 1)); } else { self.state_stack.push(Addr::EmptyList); } self.state_stack.push(Addr::Char(c)); } else if has_tail { return self.follow(Addr::HeapCell(h + 1)); } } else { unreachable!() } Addr::PStrLocation(h, n) } Addr::Str(s) => { self.follow_heap(s) } Addr::Con(h) => { if let &HeapCellValue::PartialString(ref pstr, has_tail) = &self.machine_st.heap[h] { if !self.machine_st.flags.double_quotes.is_atom() { return if let Some(c) = pstr.range_from(0 ..).next() { self.state_stack.push(Addr::PStrLocation(h, c.len_utf8())); self.state_stack.push(Addr::Char(c)); Addr::PStrLocation(h, 0) } else
; } } Addr::Con(h) } da => { da } } } } impl<'a> Iterator for HCPreOrderIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { self.state_stack.pop().map(|a| self.follow(a)) } } pub trait MutStackHCIterator where Self: Iterator<Item = Addr> { fn stack(&mut self) -> &mut Vec<Addr>; } pub struct HCPostOrderIterator<'a> { base_iter: HCPreOrderIterator<'a>, parent_stack: Vec<(usize, Addr)>, } impl<'a> Deref for HCPostOrderIterator<'a> { type Target = HCPreOrderIterator<'a>; fn deref(&self) -> &Self::Target { &self.base_iter } } impl<'a> HCPostOrderIterator<'a> { pub fn new(base_iter: HCPreOrderIterator<'a>) -> Self { HCPostOrderIterator { base_iter, parent_stack: vec![], } } } impl<'a> Iterator for HCPostOrderIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { loop { if let Some((child_count, node)) = self.parent_stack.pop() { if child_count == 0 { return Some(node); } self.parent_stack.push((child_count - 1, node)); } if let Some(item) = self.base_iter.next() { match self.base_iter.machine_st.heap.index_addr(&item).as_ref() { &HeapCellValue::NamedStr(arity, ..) => { self.parent_stack.push((arity, item)); } &HeapCellValue::Addr(Addr::Lis(a)) => { self.parent_stack.push((2, Addr::Lis(a))); } &HeapCellValue::Addr(Addr::PStrLocation(h, n)) => { match &self.machine_st.heap[h] { &HeapCellValue::PartialString(ref pstr, _) => { let c = pstr.range_from(n ..).next().unwrap(); let next_n = n + c.len_utf8(); if !pstr.at_end(next_n) { self.parent_stack.push((2, Addr::PStrLocation(h, next_n))); } } _ => { unreachable!() } } } _ => { return Some(item); } } } else { return None; } } } } impl MachineState { pub fn pre_order_iter<'a>(&'a self, a: Addr) -> HCPreOrderIterator<'a> { HCPreOrderIterator::new(self, a) } pub fn post_order_iter<'a>(&'a self, a: Addr) -> HCPostOrderIterator<'a> { HCPostOrderIterator::new(HCPreOrderIterator::new(self, a)) } pub fn acyclic_pre_order_iter<'a>(&'a self, a: Addr,) -> HCAcyclicIterator<'a> { HCAcyclicIterator::new(HCPreOrderIterator::new(self, a)) } pub fn zipped_acyclic_pre_order_iter<'a>( &'a self, a1: Addr, a2: Addr, ) -> HCZippedAcyclicIterator<'a> { HCZippedAcyclicIterator::new( HCPreOrderIterator::new(self, a1), HCPreOrderIterator::new(self, a2), ) } } impl<'a> MutStackHCIterator for HCPreOrderIterator<'a> { fn stack(&mut self) -> &mut Vec<Addr> { &mut self.state_stack } } pub struct HCAcyclicIterator<'a> { iter: HCPreOrderIterator<'a>, seen: IndexSet<Addr>, } impl<'a> HCAcyclicIterator<'a> { pub fn new(iter: HCPreOrderIterator<'a>) -> Self { HCAcyclicIterator { iter, seen: IndexSet::new(), } } } impl<'a> Deref for HCAcyclicIterator<'a> { type Target = HCPreOrderIterator<'a>; fn deref(&self) -> &Self::Target { &self.iter } } impl<'a> Iterator for HCAcyclicIterator<'a> { type Item = Addr; fn next(&mut self) -> Option<Self::Item> { while let Some(addr) = self.iter.stack().pop() { if !self.seen.contains(&addr) { self.iter.stack().push(addr.clone()); self.seen.insert(addr); break; } } self.iter.next() } } pub struct HCZippedAcyclicIterator<'a> { i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>, seen: IndexSet<(Addr, Addr)>, pub first_to_expire: Ordering, } impl<'a> HCZippedAcyclicIterator<'a> { pub fn new(i1: HCPreOrderIterator<'a>, i2: HCPreOrderIterator<'a>) -> Self { HCZippedAcyclicIterator { i1, i2, seen: IndexSet::new(), first_to_expire: Ordering::Equal, } } } impl<'a> Iterator for HCZippedAcyclicIterator<'a> { type Item = (Addr, Addr); fn next(&mut self) -> Option<Self::Item> { while let (Some(a1), Some(a2)) = (self.i1.stack().pop(), self.i2.stack().pop()) { if !self.seen.contains(&(a1.clone(), a2.clone())) { self.i1.stack().push(a1.clone()); self.i2.stack().push(a2.clone()); self.seen.insert((a1, a2)); break; } } match (self.i1.next(), self.i2.next()) { (Some(v1), Some(v2)) => Some((v1, v2)), (Some(_), None) => { self.first_to_expire = Ordering::Greater; None } (None, Some(_)) => { self.first_to_expire = Ordering::Less; None } _ => { None } } } }
if has_tail { self.follow(Addr::HeapCell(h + 1)) } else { Addr::EmptyList }
if_condition
[ { "content": "#[inline]\n\nfn functor_location(addr: &Addr) -> Option<usize> {\n\n Some(match addr {\n\n &Addr::Lis(l) => l,\n\n &Addr::Str(s) => s,\n\n &Addr::PStrLocation(h, _) => h,\n\n _ => {\n\n return None;\n\n }\n\n })\n\n}\n\n\n\nimpl<'a, Outputter: HC...
Rust
winapi-perf-wrapper/src/lib.rs
zaphar/win-utils
8215fc3b56cd083c7f4575e663f0469d51eb9e2d
use winapi::shared::minwindef::{DWORD, FALSE, TRUE}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::pdh::{ PDH_FMT_COUNTERVALUE_u, PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhEnumObjectItemsW, PdhEnumObjectsW, PdhExpandCounterPathW, PdhGetFormattedCounterValue, PdhOpenQueryW, PdhRemoveCounter, PdhValidatePathW, PDH_FMT_COUNTERVALUE, PDH_HCOUNTER as HCounter, PDH_HQUERY as HQuery, PERF_DETAIL_STANDARD, }; use std::ptr::null_mut; use std::time::Duration; pub mod constants; pub use constants::PDHStatus; use constants::*; fn null_separated_to_vec(mut buf: Vec<u16>) -> Vec<Vec<u16>> { buf.pop(); buf.pop(); let mut v = Vec::new(); for item in buf.split(|el| *el == 0) { v.push(item.to_owned()); } return v; } fn str_to_utf16(s: &str) -> Vec<u16> { let mut v = s.encode_utf16().collect::<Vec<u16>>(); v.push(0); v } fn zeroed_buffer(sz: usize) -> Vec<u16> { let mut v = Vec::with_capacity(sz); v.resize(sz, Default::default()); return v; } pub struct PDH { machine_name: Option<Vec<u16>>, } impl PDH { pub fn new() -> Self { Self { machine_name: None } } pub fn with_machine_name(mut self, machine_name: Vec<u16>) -> Self { self.machine_name = Some(machine_name); self } pub fn enumerate_objects_string(&mut self) -> Result<Vec<String>, PDHStatus> { self.enumerate_objects_utf16().map(|mut v| { v.drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect() }) } pub fn enumerate_objects_utf16(&mut self) -> Result<Vec<Vec<u16>>, PDHStatus> { let data_source = null_mut(); let machine_name = if let Some(ref mut machine_name) = self.machine_name { machine_name.as_mut_ptr() } else { null_mut() }; let mut buffer_length: DWORD = 0; let mut status = unsafe { PdhEnumObjectsW( data_source, machine_name, null_mut(), &mut buffer_length, PERF_DETAIL_STANDARD, TRUE, ) } as u32; if status == constants::PDH_MORE_DATA { let mut object_list = Vec::<u16>::with_capacity(buffer_length as usize); object_list.resize(buffer_length as usize, 0); status = unsafe { PdhEnumObjectsW( data_source, machine_name, object_list.as_mut_ptr(), &mut buffer_length, PERF_DETAIL_STANDARD, FALSE, ) } as u32; if status == ERROR_SUCCESS { return Ok(null_separated_to_vec(object_list)); } else { return Err(status); } } else { return Err(status); } } pub fn enumerate_items_string<S: Into<String>>( &self, obj: S, ) -> Result<(Vec<String>, Vec<String>), PDHStatus> { self.enumerate_items_utf16(&str_to_utf16(&obj.into())) .map(|(mut cs, mut insts)| { ( cs.drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect(), insts .drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect(), ) }) } pub fn enumerate_items_utf16( &self, obj: &Vec<u16>, ) -> Result<(Vec<Vec<u16>>, Vec<Vec<u16>>), PDHStatus> { let mut object_name = obj.clone(); let mut counter_list_len: DWORD = 0; let mut instance_list_len: DWORD = 0; let mut status = unsafe { PdhEnumObjectItemsW( null_mut(), null_mut(), object_name.as_mut_ptr(), null_mut(), &mut counter_list_len, null_mut(), &mut instance_list_len, PERF_DETAIL_STANDARD, 0, ) } as PDHStatus; if status == constants::PDH_MORE_DATA { let mut counter_list = zeroed_buffer(counter_list_len as usize); let mut instance_list = zeroed_buffer(instance_list_len as usize); status = unsafe { PdhEnumObjectItemsW( null_mut(), null_mut(), object_name.as_mut_ptr(), counter_list.as_mut_ptr(), &mut counter_list_len, instance_list.as_mut_ptr(), &mut instance_list_len, PERF_DETAIL_STANDARD, 0, ) } as PDHStatus; if status != ERROR_SUCCESS { return Err(status); } return Ok(( null_separated_to_vec(counter_list), null_separated_to_vec(instance_list), )); } else { return Err(status); } } pub fn open_query(&self) -> Result<PdhQuery, PDHStatus> { let mut query = PdhQuery(null_mut()); let status = unsafe { PdhOpenQueryW(null_mut(), 0, query.query()) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(query); } pub fn enumerate_counters(&mut self) -> Result<Vec<String>, PDHStatus> { let mut counter_path_vec = Vec::new(); let path_prefix = if let Some(ref machine_name) = self.machine_name { format!("\\\\{}", String::from_utf16_lossy(machine_name.as_slice())) } else { String::new() }; for obj in self.enumerate_objects_utf16()? { let (counters, instances) = match self.enumerate_items_utf16(&obj) { Ok(t) => t, Err(PDH_CSTATUS_NO_OBJECT) => { continue; } Err(s) => return Err(s), }; let obj = String::from_utf16_lossy(obj.as_slice()); for i in &instances { let i = if i.is_empty() { String::new() } else { format!("({})", String::from_utf16_lossy(i)) }; for c in &counters { counter_path_vec.push(format!( "{}\\{}{}\\{}", path_prefix, obj, i, String::from_utf16_lossy(c) )); } } } return Ok(counter_path_vec); } pub fn expand_counter_path_utf16(&self, path: &Vec<u16>) -> Result<Vec<Vec<u16>>, PDHStatus> { let mut counter_list_len: DWORD = 0; let mut status = unsafe { PdhExpandCounterPathW(path.as_ptr(), null_mut(), &mut counter_list_len) } as PDHStatus; if status != constants::PDH_MORE_DATA { return Err(status); } let mut unparsed_list = zeroed_buffer(counter_list_len as usize); status = unsafe { PdhExpandCounterPathW( path.as_ptr(), unparsed_list.as_mut_ptr(), &mut counter_list_len, ) } as PDHStatus; if status != ERROR_SUCCESS { return Err(status); } Ok(null_separated_to_vec(unparsed_list)) } pub fn expand_counter_path_string<S: Into<String>>( &self, path: S, ) -> Result<Vec<String>, PDHStatus> { self.expand_counter_path_utf16(&str_to_utf16(&path.into())) .map(|mut ps| { ps.drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect() }) } } pub struct PdhQuery(HQuery); impl PdhQuery { pub fn query(&mut self) -> &mut HQuery { &mut self.0 } pub fn add_counter_utf16(&self, wide_path: Vec<u16>) -> Result<PdhCounter, PDHStatus> { let mut status = unsafe { PdhValidatePathW(wide_path.as_ptr()) } as u32; if status != ERROR_SUCCESS { return Err(status); } let mut counter_handle: HCounter = null_mut(); status = unsafe { PdhAddCounterW(self.0, wide_path.as_ptr(), 0, &mut counter_handle) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(PdhCounter(counter_handle)); } pub fn add_counter_string<S: Into<String>>(&self, path: S) -> Result<PdhCounter, PDHStatus> { self.add_counter_utf16(str_to_utf16(&path.into())) } #[allow(unused_variables)] pub fn remove_counter(&self, counter_handle: PdhCounter) { } fn collect_data( &self, counter: &PdhCounter, format: u32, ) -> Result<PDH_FMT_COUNTERVALUE, PDHStatus> { let mut status = unsafe { PdhCollectQueryData(self.0) } as u32; if status != ERROR_SUCCESS { return Err(status); } let mut fmt_counter_value = unsafe { PDH_FMT_COUNTERVALUE { CStatus: 0, u: std::mem::zeroed::<PDH_FMT_COUNTERVALUE_u>(), } }; let mut counter_type: u32 = 0; status = unsafe { PdhGetFormattedCounterValue( counter.0, format, &mut counter_type, &mut fmt_counter_value, ) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(fmt_counter_value); } pub fn get_value_stream_from_path<S: Into<String>, ValueType>( &self, counter_path: S, ) -> Result<CounterStream<ValueType>, PDHStatus> { let counter_handle = self.add_counter_string(counter_path)?; Ok(self.get_value_stream_from_handle(counter_handle)) } pub fn get_value_stream_from_handle<ValueType>( &self, counter: PdhCounter, ) -> CounterStream<ValueType> { CounterStream::new(self, counter) } pub fn collect_long_data(&self, counter: &PdhCounter) -> Result<i32, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_LONG)?; return Ok(unsafe { *fmt_counter_value.u.longValue() }); } pub fn collect_large_data(&self, counter: &PdhCounter) -> Result<i64, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_LARGE)?; return Ok(unsafe { *fmt_counter_value.u.largeValue() }); } pub fn collect_double_data(&self, counter: &PdhCounter) -> Result<f64, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_DOUBLE)?; return Ok(unsafe { *fmt_counter_value.u.doubleValue() }); } } pub trait ValueStream<ValueType> { fn next(&self) -> Result<ValueType, PDHStatus>; } pub struct CounterStream<'a, ValueType> { query_handle: &'a PdhQuery, counter_handle: PdhCounter, collect_delay: Option<Duration>, phantom: std::marker::PhantomData<ValueType>, } impl<'a, ValueType> CounterStream<'a, ValueType> { pub fn new<'b: 'a>(query_handle: &'b PdhQuery, counter_handle: PdhCounter) -> Self { Self { query_handle: query_handle, counter_handle: counter_handle, phantom: std::marker::PhantomData, collect_delay: None, } } pub fn with_delay<D: Into<Duration>>(mut self, delay: D) -> Self { self.collect_delay = Some(delay.into()); return self; } } impl<'a> ValueStream<i32> for CounterStream<'a, i32> { fn next(&self) -> Result<i32, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_long_data(&self.counter_handle) } } impl<'a> ValueStream<i64> for CounterStream<'a, i64> { fn next(&self) -> Result<i64, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_large_data(&self.counter_handle) } } impl<'a> ValueStream<f64> for CounterStream<'a, f64> { fn next(&self) -> Result<f64, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_double_data(&self.counter_handle) } } impl Drop for PdhQuery { fn drop(&mut self) { unsafe { PdhCloseQuery(self.0); } } } pub struct PdhCounter(HCounter); impl Drop for PdhCounter { fn drop(&mut self) { unsafe { PdhRemoveCounter(self.0); } } }
use winapi::shared::minwindef::{DWORD, FALSE, TRUE}; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::pdh::{ PDH_FMT_COUNTERVALUE_u, PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhEnumObjectItemsW, PdhEnumObjectsW, PdhExpandCounterPathW, PdhGetFormattedCounterValue, PdhOpenQueryW, PdhRemoveCounter, PdhValidatePathW, PDH_FMT_COUNTERVALUE, PDH_HCOUNTER as HCounter, PDH_HQUERY as HQuery, PERF_DETAIL_STANDARD, }; use std::ptr::null_mut; use std::time::Duration; pub mod constants; pub use constants::PDHStatus; use constants::*; fn null_separated_to_vec(mut buf: Vec<u16>) -> Vec<Vec<u16>> { buf.pop(); buf.pop(); let mut v = Vec::new(); for item in buf.split(|el| *el == 0) { v.push(item.to_owned()); } return v; } fn str_to_utf16(s: &str) -> Vec<u16> { let mut v = s.encode_utf16().collect::<Vec<u16>>(); v.push(0); v } fn zeroed_buffer(sz: usize) -> Vec<u16> { let mut v = Vec::with_capacity(sz); v.resize(sz, Default::default()); return v; } pub struct PDH { machine_name: Option<Vec<u16>>, } impl PDH { pub fn new() -> Self { Self { machine_name: None } } pub fn with_machine_name(mut self, machine_name: Vec<u16>) -> Self { self.machine_name = Some(machine_name); self } pub fn enumerate_objects_string(&mut self) -> Result<Vec<String>, PDHStatus> { self.enumerate_objects_utf16().map(|mut v| { v.drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect() }) } pub fn enumerate_objects_utf16(&mut self) -> Result<Vec<Vec<u16>>, PDHStatus> { let data_source = null_mut(); let machine_name = if let Some(ref mut machine_name) = self.machine_name { machine_name.as_mut_ptr() } else { null_mut() }; let mut buffer_length: DWORD = 0; let mut status = unsafe { PdhEnumObjectsW( data_source, machine_name, null_mut(), &mut buffer_length, PERF_DETAIL_STANDARD, TRUE, ) } as u32; if status == constants::PDH_MORE_DATA { let mut object_list = Vec::<u16>::with_capacity(buffer_length as usize); object_list.resize(buffer_length as usize, 0); status = unsafe { PdhEnumObjectsW( data_source, machine_name, object_list.as_mut_ptr(), &mut buffer_length, PERF_DETAIL_STANDARD, FALSE, ) } as u32; if status == ERROR_SUCCESS { return Ok(null_separated_to_vec(object_list)); } else { return Err(status); } } else { return Err(status); } } pub fn enumerate_items_string<S: Into<String>>( &self, obj: S, ) -> Result<(Vec<String>, Vec<String>), PDHStatus> { self.enumerate_items_utf16(&str_to_utf16(&obj.into())) .map(|(mut cs, mut insts)| { ( cs.drain(0..) .map(|v| String::from_
unters(&mut self) -> Result<Vec<String>, PDHStatus> { let mut counter_path_vec = Vec::new(); let path_prefix = if let Some(ref machine_name) = self.machine_name { format!("\\\\{}", String::from_utf16_lossy(machine_name.as_slice())) } else { String::new() }; for obj in self.enumerate_objects_utf16()? { let (counters, instances) = match self.enumerate_items_utf16(&obj) { Ok(t) => t, Err(PDH_CSTATUS_NO_OBJECT) => { continue; } Err(s) => return Err(s), }; let obj = String::from_utf16_lossy(obj.as_slice()); for i in &instances { let i = if i.is_empty() { String::new() } else { format!("({})", String::from_utf16_lossy(i)) }; for c in &counters { counter_path_vec.push(format!( "{}\\{}{}\\{}", path_prefix, obj, i, String::from_utf16_lossy(c) )); } } } return Ok(counter_path_vec); } pub fn expand_counter_path_utf16(&self, path: &Vec<u16>) -> Result<Vec<Vec<u16>>, PDHStatus> { let mut counter_list_len: DWORD = 0; let mut status = unsafe { PdhExpandCounterPathW(path.as_ptr(), null_mut(), &mut counter_list_len) } as PDHStatus; if status != constants::PDH_MORE_DATA { return Err(status); } let mut unparsed_list = zeroed_buffer(counter_list_len as usize); status = unsafe { PdhExpandCounterPathW( path.as_ptr(), unparsed_list.as_mut_ptr(), &mut counter_list_len, ) } as PDHStatus; if status != ERROR_SUCCESS { return Err(status); } Ok(null_separated_to_vec(unparsed_list)) } pub fn expand_counter_path_string<S: Into<String>>( &self, path: S, ) -> Result<Vec<String>, PDHStatus> { self.expand_counter_path_utf16(&str_to_utf16(&path.into())) .map(|mut ps| { ps.drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect() }) } } pub struct PdhQuery(HQuery); impl PdhQuery { pub fn query(&mut self) -> &mut HQuery { &mut self.0 } pub fn add_counter_utf16(&self, wide_path: Vec<u16>) -> Result<PdhCounter, PDHStatus> { let mut status = unsafe { PdhValidatePathW(wide_path.as_ptr()) } as u32; if status != ERROR_SUCCESS { return Err(status); } let mut counter_handle: HCounter = null_mut(); status = unsafe { PdhAddCounterW(self.0, wide_path.as_ptr(), 0, &mut counter_handle) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(PdhCounter(counter_handle)); } pub fn add_counter_string<S: Into<String>>(&self, path: S) -> Result<PdhCounter, PDHStatus> { self.add_counter_utf16(str_to_utf16(&path.into())) } #[allow(unused_variables)] pub fn remove_counter(&self, counter_handle: PdhCounter) { } fn collect_data( &self, counter: &PdhCounter, format: u32, ) -> Result<PDH_FMT_COUNTERVALUE, PDHStatus> { let mut status = unsafe { PdhCollectQueryData(self.0) } as u32; if status != ERROR_SUCCESS { return Err(status); } let mut fmt_counter_value = unsafe { PDH_FMT_COUNTERVALUE { CStatus: 0, u: std::mem::zeroed::<PDH_FMT_COUNTERVALUE_u>(), } }; let mut counter_type: u32 = 0; status = unsafe { PdhGetFormattedCounterValue( counter.0, format, &mut counter_type, &mut fmt_counter_value, ) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(fmt_counter_value); } pub fn get_value_stream_from_path<S: Into<String>, ValueType>( &self, counter_path: S, ) -> Result<CounterStream<ValueType>, PDHStatus> { let counter_handle = self.add_counter_string(counter_path)?; Ok(self.get_value_stream_from_handle(counter_handle)) } pub fn get_value_stream_from_handle<ValueType>( &self, counter: PdhCounter, ) -> CounterStream<ValueType> { CounterStream::new(self, counter) } pub fn collect_long_data(&self, counter: &PdhCounter) -> Result<i32, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_LONG)?; return Ok(unsafe { *fmt_counter_value.u.longValue() }); } pub fn collect_large_data(&self, counter: &PdhCounter) -> Result<i64, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_LARGE)?; return Ok(unsafe { *fmt_counter_value.u.largeValue() }); } pub fn collect_double_data(&self, counter: &PdhCounter) -> Result<f64, PDHStatus> { let fmt_counter_value = self.collect_data(counter, PDH_FMT_DOUBLE)?; return Ok(unsafe { *fmt_counter_value.u.doubleValue() }); } } pub trait ValueStream<ValueType> { fn next(&self) -> Result<ValueType, PDHStatus>; } pub struct CounterStream<'a, ValueType> { query_handle: &'a PdhQuery, counter_handle: PdhCounter, collect_delay: Option<Duration>, phantom: std::marker::PhantomData<ValueType>, } impl<'a, ValueType> CounterStream<'a, ValueType> { pub fn new<'b: 'a>(query_handle: &'b PdhQuery, counter_handle: PdhCounter) -> Self { Self { query_handle: query_handle, counter_handle: counter_handle, phantom: std::marker::PhantomData, collect_delay: None, } } pub fn with_delay<D: Into<Duration>>(mut self, delay: D) -> Self { self.collect_delay = Some(delay.into()); return self; } } impl<'a> ValueStream<i32> for CounterStream<'a, i32> { fn next(&self) -> Result<i32, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_long_data(&self.counter_handle) } } impl<'a> ValueStream<i64> for CounterStream<'a, i64> { fn next(&self) -> Result<i64, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_large_data(&self.counter_handle) } } impl<'a> ValueStream<f64> for CounterStream<'a, f64> { fn next(&self) -> Result<f64, PDHStatus> { if let Some(d) = self.collect_delay { std::thread::sleep(d); } self.query_handle.collect_double_data(&self.counter_handle) } } impl Drop for PdhQuery { fn drop(&mut self) { unsafe { PdhCloseQuery(self.0); } } } pub struct PdhCounter(HCounter); impl Drop for PdhCounter { fn drop(&mut self) { unsafe { PdhRemoveCounter(self.0); } } }
utf16_lossy(v.as_slice())) .collect(), insts .drain(0..) .map(|v| String::from_utf16_lossy(v.as_slice())) .collect(), ) }) } pub fn enumerate_items_utf16( &self, obj: &Vec<u16>, ) -> Result<(Vec<Vec<u16>>, Vec<Vec<u16>>), PDHStatus> { let mut object_name = obj.clone(); let mut counter_list_len: DWORD = 0; let mut instance_list_len: DWORD = 0; let mut status = unsafe { PdhEnumObjectItemsW( null_mut(), null_mut(), object_name.as_mut_ptr(), null_mut(), &mut counter_list_len, null_mut(), &mut instance_list_len, PERF_DETAIL_STANDARD, 0, ) } as PDHStatus; if status == constants::PDH_MORE_DATA { let mut counter_list = zeroed_buffer(counter_list_len as usize); let mut instance_list = zeroed_buffer(instance_list_len as usize); status = unsafe { PdhEnumObjectItemsW( null_mut(), null_mut(), object_name.as_mut_ptr(), counter_list.as_mut_ptr(), &mut counter_list_len, instance_list.as_mut_ptr(), &mut instance_list_len, PERF_DETAIL_STANDARD, 0, ) } as PDHStatus; if status != ERROR_SUCCESS { return Err(status); } return Ok(( null_separated_to_vec(counter_list), null_separated_to_vec(instance_list), )); } else { return Err(status); } } pub fn open_query(&self) -> Result<PdhQuery, PDHStatus> { let mut query = PdhQuery(null_mut()); let status = unsafe { PdhOpenQueryW(null_mut(), 0, query.query()) } as u32; if status != ERROR_SUCCESS { return Err(status); } return Ok(query); } pub fn enumerate_co
random
[ { "content": "pub fn print_object_counters(pdh: &mut PDH, obj: &str) -> anyhow::Result<()> {\n\n println!(\"Counters for {}:\", obj);\n\n let (counters, instances) = pdh\n\n .enumerate_items_string(obj)\n\n .map_err(|s| constants::pdh_status_friendly_name(s))\n\n .unwrap();\n\n for...
Rust
a_2sat/src/lib.rs
Ninjani/rosalind
e22ecf2c9f0935d970b137684029957c0850d63f
use std::collections::{btree_map::BTreeMap, HashMap, HashSet}; use failure::Error; use utility; pub fn rosalind_2sat(filename: &str) -> Result<Vec<Option<Vec<isize>>>, Error> { let input = utility::io::input_from_file(filename)?; let mut lines = input .split('\n') .filter(|s| !s.trim().is_empty()) .map(|s| s.to_owned()); let num_sections = lines.next().unwrap().parse::<usize>()?; let mut output = Vec::with_capacity(num_sections); for _ in 0..num_sections { match get_assignment(&mut lines)? { Some(true_variables) => { println!( "1 {}", true_variables .iter() .map(|v| v.to_string()) .collect::<Vec<_>>() .join(" ") ); output.push(Some(true_variables)); } None => { println!("0"); output.push(None); } } } Ok(output) } pub trait From2sat: Sized { fn from_2sat_adjacency_list( lines: &mut dyn Iterator<Item=String>, run_dfs: bool, ) -> Result<Self, Error>; } impl From2sat for utility::graph::IntegerGraph { fn from_2sat_adjacency_list( lines: &mut dyn Iterator<Item=String>, run_dfs: bool, ) -> Result<Self, Error> { let length_input = lines .next() .unwrap() .split(' ') .map(str::parse) .collect::<Result<Vec<usize>, _>>()?; let (num_variables, num_clauses) = (length_input[0], length_input[1]); let mut adjacency_list = BTreeMap::new(); let mut line; for _ in 0..num_clauses { line = lines.next().unwrap(); let parts = line .split(' ') .map(str::parse) .collect::<Result<Vec<isize>, _>>()?; { let edge_list_1 = adjacency_list .entry(get_node(-parts[0])) .or_insert_with(Vec::new); edge_list_1.push(get_node(parts[1])); let edge_list_1 = adjacency_list .entry(get_node(-parts[1])) .or_insert_with(Vec::new); edge_list_1.push(get_node(parts[0])); } } Ok(Self::new( adjacency_list, (1..=num_variables * 2).collect(), run_dfs, )) } } fn get_node(variable: isize) -> usize { if variable < 0 { 2 * (variable.abs() as usize) - 1 } else { 2 * variable as usize } } fn get_variable(node: usize) -> isize { if node % 2 == 0 { (node / 2) as isize } else { -(((node + 1) / 2) as isize) } } fn get_negated_node(node: usize) -> usize { let variable = get_variable(node); if variable < 0 { node + 1 } else { node - 1 } } fn get_assignment(lines: &mut dyn Iterator<Item=String>) -> Result<Option<Vec<isize>>, Error> { let mut graph = utility::graph::IntegerGraph::from_2sat_adjacency_list(lines, false)?; let graph_reverse = graph.get_reverse_graph(true); let mut node_order = graph_reverse .postvisit .into_iter() .enumerate() .collect::<Vec<_>>(); node_order.sort_by(|a, b| b.1.cmp(&a.1)); let node_order: Vec<usize> = node_order.iter().map(|(i, _)| *i).collect(); graph.run_dfs_given_node_order(&node_order); let mut satisfiable = true; for node in (0..graph.num_nodes - 1).step_by(2) { if graph.connected_components[node] == graph.connected_components[node + 1] { satisfiable = false; break; } } if satisfiable { let mut component_to_nodes = HashMap::new(); for (i, component) in graph.connected_components.iter().enumerate() { component_to_nodes .entry(component) .or_insert_with(Vec::new) .push(graph.nodes[i]); } let mut seen = HashSet::with_capacity(graph.num_nodes); let mut assignment = (0..graph.num_nodes).map(|_| false).collect::<Vec<_>>(); let mut n_node; for node_index in node_order { if !seen.contains(&graph.nodes[node_index]) { for c_node in &component_to_nodes[&graph.connected_components[node_index]] { if !seen.contains(c_node) { n_node = get_negated_node(*c_node); seen.insert(*c_node); seen.insert(n_node); assignment[graph.node_to_index[c_node]] = true; assignment[graph.node_to_index[&n_node]] = false; } } } } Ok(Some( assignment .into_iter() .enumerate() .filter(|(_, s)| *s) .map(|(i, _)| get_variable(graph.nodes[i])) .collect(), )) } else { Ok(None) } } #[cfg(test)] mod tests { use utility::io::Parseable; use super::*; #[test] fn _2sat() -> Result<(), Error> { let (input_file, output_file) = utility::testing::get_input_output_file("rosalind_2sat")?; let result = rosalind_2sat(&input_file)?; for (input_assignment, output_assignment) in result.into_iter().zip( utility::io::input_from_file(&output_file)? .split('\n') .filter(|line| !line.trim().is_empty()), ) { if let Ok(0) = output_assignment.trim().parse::<usize>() { assert!(input_assignment.is_none()) } else { assert!(input_assignment.is_some()); assert_eq!( input_assignment.unwrap()[..], isize::parse_line(output_assignment.trim())?[1..] ); } } Ok(()) } }
use std::collections::{btree_map::BTreeMap, HashMap, HashSet}; use failure::Error; use utility; pub fn rosalind_2sat(filename: &str) -> Result<Vec<Option<Vec<isize>>>, Error> { let input = utility::io::input_from_file(filename)?; let mut lines = input .split('\n') .filter(|s| !s.trim().is_empty()) .map(|s| s.to_owned()); let num_sections = lines.next().unwrap().parse::<usize>()?; let mut output = Vec::with_capacity(num_sections); for _ in 0..num_sections { match get_assignment(&mut lines)? { Some(true_variables) => { println!( "1 {}", true_variables .iter() .map(|v| v.to_string()) .collect::<Vec<_>>() .join(" ") ); output.push(Some(true_variables)); } None => { println!("0"); output.push(None); } } } Ok(output) } pub trait From2sat: Sized { fn from_2sat_adjacency_list( lines: &mut dyn Iterator<Item=String>, run_dfs: bool, ) -> Result<Self, Error>; } impl From2sat for utility::graph::IntegerGraph { fn from_2sat_adjacency_list( lines: &mut dyn Iterator<Item=String>, run_dfs: bool, ) -> Result<Self, Error> { let length_input = lines .next() .unwrap() .split(' ') .map(str::parse) .collect::<Result<Vec<usize>, _>>()?; let (num_variables, num_clauses) = (length_input[0], length_input[1]); let mut adjacency_list = BTreeMap::new(); let mut line; for _ in 0..num_clauses { line = lines.next().unwrap(); let parts = line .split(' ') .map(str::parse) .collect::<Result<Vec<isize>, _>>()?; { let edge_list_1 = adjacency_list .entry(get_node(-parts[0])) .or_insert_with(Vec::new); edge_list_1.push(get_node(parts[1])); let edge_list_1 = adjacency_list .entry(get_node(-parts[1])) .or_insert_with(Vec::new); edge_list_1.push(get_node(parts[0])); } } Ok(Self::new( adjacency_list, (1..=num_variables * 2).collect(), run_dfs, )) } } fn get_node(variable: isize) -> usize { if variable < 0 { 2 * (variable.abs() as usize) - 1 } else { 2 * variable as usize } } fn get_variable(node: usize) -> isize { if node % 2 == 0 { (node / 2) as isize } else { -(((node + 1) / 2) as isize) } } fn get_negated_node(node: usize) -> usize { let variable = get_variable(node); if variable < 0 { node + 1 } else { node - 1 } } fn get_assignment(lines: &mut dyn Iterator<Item=String>) -> Result<Option<Vec<isize>>, Error> { let mut graph = utility::graph::IntegerGraph::from_2sat_adjacency_list(lines, false)?; let graph_reverse = graph.get_reverse_graph(true); let mut node_order = graph_reverse .postvisit .into_iter() .enumerate() .collect::<Vec<_>>(); node_order.sort_by(|a, b| b.1.cmp(&a.1)); let node_order: Vec<usize> = node_order.iter().map(|(i, _)| *i).collect(); graph.run_dfs_given_node_order(&node_order); let mut satisfiable = true; for node in (0..graph.num_nodes - 1).step_by(2) { if graph.connected_components[node] == graph.connected_components[node + 1] { satisfiable = false; break; } } if satisfiable { let mut component_to_nodes = HashMap::new(); for (i, component) in graph.con
for node_index in node_order { if !seen.contains(&graph.nodes[node_index]) { for c_node in &component_to_nodes[&graph.connected_components[node_index]] { if !seen.contains(c_node) { n_node = get_negated_node(*c_node); seen.insert(*c_node); seen.insert(n_node); assignment[graph.node_to_index[c_node]] = true; assignment[graph.node_to_index[&n_node]] = false; } } } } Ok(Some( assignment .into_iter() .enumerate() .filter(|(_, s)| *s) .map(|(i, _)| get_variable(graph.nodes[i])) .collect(), )) } else { Ok(None) } } #[cfg(test)] mod tests { use utility::io::Parseable; use super::*; #[test] fn _2sat() -> Result<(), Error> { let (input_file, output_file) = utility::testing::get_input_output_file("rosalind_2sat")?; let result = rosalind_2sat(&input_file)?; for (input_assignment, output_assignment) in result.into_iter().zip( utility::io::input_from_file(&output_file)? .split('\n') .filter(|line| !line.trim().is_empty()), ) { if let Ok(0) = output_assignment.trim().parse::<usize>() { assert!(input_assignment.is_none()) } else { assert!(input_assignment.is_some()); assert_eq!( input_assignment.unwrap()[..], isize::parse_line(output_assignment.trim())?[1..] ); } } Ok(()) } }
nected_components.iter().enumerate() { component_to_nodes .entry(component) .or_insert_with(Vec::new) .push(graph.nodes[i]); } let mut seen = HashSet::with_capacity(graph.num_nodes); let mut assignment = (0..graph.num_nodes).map(|_| false).collect::<Vec<_>>(); let mut n_node;
random
[ { "content": "/// Read set of form:\n\n/// {n1, n2, n3, ... }\n\npub fn read_set(line: &str) -> Result<HashSet<usize>, Error> {\n\n let chars: Vec<_> = line.chars().collect();\n\n let line: String = chars[1..(line.len() - 1)].iter().collect();\n\n Ok(HashSet::from_iter(\n\n line.split(\", \")\n\...
Rust
src/font/hbwrap.rs
TimeToogo/wezterm
d36afd90ceb5c17e425f94e7a4d893df33a0cb62
#![allow(dead_code)] #[cfg(target_os = "macos")] use core_text::font::{CTFont, CTFontRef}; use freetype; pub use harfbuzz::*; use anyhow::{ensure, Error}; use std::mem; use std::ptr; use std::slice; extern "C" { fn hb_ft_font_set_load_flags(font: *mut hb_font_t, load_flags: i32); } #[cfg(windows)] extern "C" { fn hb_directwrite_face_create(face: *mut winapi::um::dwrite::IDWriteFontFace) -> *mut hb_font_t; } #[cfg(target_os = "macos")] extern "C" { fn hb_coretext_font_create(ct_font: CTFontRef) -> *mut hb_font_t; /* HB_EXTERN hb_face_t * hb_coretext_face_create (CGFontRef cg_font); HB_EXTERN hb_font_t * hb_coretext_font_create (CTFontRef ct_font); HB_EXTERN CGFontRef hb_coretext_face_get_cg_font (hb_face_t *face); HB_EXTERN CTFontRef hb_coretext_font_get_ct_font (hb_font_t *font); */ } pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> { unsafe { let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32); ensure!(!lang.is_null(), "failed to convert {} to language"); Ok(lang) } } pub fn feature_from_string(s: &str) -> Result<hb_feature_t, Error> { unsafe { let mut feature = mem::zeroed(); ensure!( hb_feature_from_string( s.as_ptr() as *const i8, s.len() as i32, &mut feature as *mut _, ) != 0, "failed to create feature from {}", s ); Ok(feature) } } pub struct Font { font: *mut hb_font_t, } impl Drop for Font { fn drop(&mut self) { unsafe { hb_font_destroy(self.font); } } } struct Blob { blob: *mut hb_blob_t, } impl Drop for Blob { fn drop(&mut self) { unsafe { hb_blob_destroy(self.blob); } } } impl Blob { fn from_slice(data: &[u8]) -> Result<Self, Error> { let blob = unsafe { hb_blob_create( data.as_ptr() as *const i8, data.len() as u32, hb_memory_mode_t::HB_MEMORY_MODE_READONLY, ptr::null_mut(), None, ) }; ensure!(!blob.is_null(), "failed to create harfbuzz blob for slice"); Ok(Self { blob }) } } struct Face { face: *mut hb_face_t, } impl Drop for Face { fn drop(&mut self) { unsafe { hb_face_destroy(self.face); } } } impl Face { fn from_blob(blob: &Blob, idx: u32) -> Result<Face, Error> { let face = unsafe { hb_face_create(blob.blob, idx) }; ensure!( !face.is_null(), "failed to create face from blob data at idx {}", idx ); Ok(Self { face }) } } impl Font { pub fn new(face: freetype::FT_Face) -> Font { Font { font: unsafe { hb_ft_font_create_referenced(face as _) }, } } #[cfg(target_os = "macos")] pub fn new_coretext(ct_font: &CTFont) -> Font { use core_foundation::base::TCFType; Font { font: unsafe { hb_coretext_font_create(ct_font.as_concrete_TypeRef()) }, } } #[cfg(windows)] pub fn new_directwrite(face: &dwrote::FontFace) -> Font { Font { font: unsafe { hb_directwrite_face_create(face.as_ptr()) }, } } #[cfg(windows)] pub fn new_from_fontkit(font: &font_kit::font::Font) -> Font { Self::new_directwrite(&font.native_font().dwrite_font_face) } #[cfg(target_os = "macos")] pub fn new_from_fontkit(font: &font_kit::font::Font) -> Font { Self::new_coretext(&font.native_font()) } pub fn new_from_slice(data: &[u8], idx: u32) -> Result<Font, Error> { let blob = Blob::from_slice(data)?; let face = Face::from_blob(&blob, idx)?; let font = unsafe { hb_font_create(face.face) }; ensure!(!font.is_null(), "failed to convert face to font"); Ok(Self { font }) } pub fn set_load_flags(&mut self, load_flags: freetype::FT_Int32) { unsafe { hb_ft_font_set_load_flags(self.font, load_flags); } } pub fn shape(&mut self, buf: &mut Buffer, features: Option<&[hb_feature_t]>) { unsafe { if let Some(features) = features { hb_shape(self.font, buf.buf, features.as_ptr(), features.len() as u32) } else { hb_shape(self.font, buf.buf, ptr::null(), 0) } } } } pub struct Buffer { buf: *mut hb_buffer_t, } impl Drop for Buffer { fn drop(&mut self) { unsafe { hb_buffer_destroy(self.buf); } } } impl Buffer { pub fn new() -> Result<Buffer, Error> { let buf = unsafe { hb_buffer_create() }; ensure!( unsafe { hb_buffer_allocation_successful(buf) } != 0, "hb_buffer_create failed" ); Ok(Buffer { buf }) } #[allow(dead_code)] pub fn reset(&mut self) { unsafe { hb_buffer_reset(self.buf); } } pub fn set_direction(&mut self, direction: hb_direction_t) { unsafe { hb_buffer_set_direction(self.buf, direction); } } pub fn set_script(&mut self, script: hb_script_t) { unsafe { hb_buffer_set_script(self.buf, script); } } pub fn set_language(&mut self, lang: hb_language_t) { unsafe { hb_buffer_set_language(self.buf, lang); } } #[allow(dead_code)] pub fn add(&mut self, codepoint: hb_codepoint_t, cluster: u32) { unsafe { hb_buffer_add(self.buf, codepoint, cluster); } } pub fn add_utf8(&mut self, buf: &[u8]) { unsafe { hb_buffer_add_utf8( self.buf, buf.as_ptr() as *const i8, buf.len() as i32, 0, buf.len() as i32, ); } } pub fn add_str(&mut self, s: &str) { self.add_utf8(s.as_bytes()) } pub fn glyph_infos(&self) -> &[hb_glyph_info_t] { unsafe { let mut len: u32 = 0; let info = hb_buffer_get_glyph_infos(self.buf, &mut len as *mut _); slice::from_raw_parts(info, len as usize) } } pub fn glyph_positions(&self) -> &[hb_glyph_position_t] { unsafe { let mut len: u32 = 0; let pos = hb_buffer_get_glyph_positions(self.buf, &mut len as *mut _); slice::from_raw_parts(pos, len as usize) } } }
#![allow(dead_code)] #[cfg(target_os = "macos")] use core_text::font::{CTFont, CTFontRef}; use freetype; pub use harfbuzz::*; use anyhow::{ensure, Error}; use std::mem; use std::ptr; use std::slice; extern "C" { fn hb_ft_font_set_load_flags(font: *mut hb_font_t, load_flags: i32); } #[cfg(windows)] extern "C" { fn hb_directwrite_face_create(face: *mut winapi::um::dwrite::IDWriteFontFace) -> *mut hb_font_t; } #[cfg(target_os = "macos")] extern "C" { fn hb_coretext_font_create(ct_font: CTFontRef) -> *mut hb_font_t; /* HB_EXTERN hb_face_t * hb_coretext_face_create (CGFontRef cg_font); HB_EXTERN hb_font_t * hb_coretext_font_create (CTFontRef ct_font); HB_EXTERN CGFontRef hb_coretext_face_get_cg_font (hb_face_t *face); HB_EXTERN CTFontRef hb_coretext_font_get_ct_font (hb_font_t *font); */ } pub fn language_from_string(s: &str) -> Result<hb_language_t, Error> { unsafe { let lang = hb_language_from_string(s.as_ptr() as *const i8, s.len() as i32); ensure!(!lang.is_null(), "failed to convert {} to language"); Ok(lang) } } pub fn feature_from_string(s: &str) -> Result<hb_feature_t, Error> { unsafe { let mut feature = mem::zeroed(); ensure!( hb_feature_from_string( s.as_ptr() as *const i8, s.len() as i32, &mut feature as *mut _, ) != 0, "failed to create feature from {}", s ); Ok(feature) } } pub struct Font { font: *mut hb_font_t, } impl Drop for Font { fn drop(&mut self) { unsafe { hb_font_destroy(self.font); } } } struct Blob { blob: *mut hb_blob_t, } impl Drop for Blob { fn drop(&mut self) { unsafe { hb_blob_destroy(self.blob); } } } impl Blob { fn from_slice(data: &[u8]) -> Result<Self, Error> { let blob = unsafe { hb_blob_create( data.as_ptr() as *const i8, data.len() as u32, hb_memory_mode_t::HB_MEMORY_MODE_READONLY, ptr::null_mut(), None, ) }; ensure!(!blob.is_null(), "failed to create harfbuzz blob for slice"); Ok(Self { blob }) } } struct Face { face: *mut hb_face_t, } impl Drop for Face { fn drop(&mut self) { unsafe { hb_face_destroy(self.face); } } } impl Face { fn from_blob(blob: &Blob, idx: u32) -> Result<Face, Error> { let face = unsafe { hb_face_create(blob.blob, idx) }; ensure!( !face.is_null(), "failed to create face from blob data at idx {}", idx ); Ok(Self { face }) } } impl Font { pub fn new(face: freetype::FT_Face) -> Font { Font { font: unsafe { hb_ft_font_create_referenced(face as _) }, } } #[cfg(target_os = "macos")] pub fn new_coretext(ct_font: &CTFont) -> Font { use core_foundation::base::TCFType; Font { font: unsafe { hb_coretext_font_create(ct_font.as_concrete_TypeRef()) }, } } #[cfg(windows)] pub fn new_directwrite(face: &dwrote::FontFace) -> Font { Font { font: unsafe { hb_directwrite_face_create(face.as_ptr()) }, } } #[cfg(windows)] pub fn new_from_fontkit(font: &font_kit::font::Font) -> Font { Self::new_directwrite(&font.native_font().dwrite_font_face) } #[cfg(target_os = "macos")] pub fn new_from_fontkit(font: &font_kit::font::Font) -> Font { Self::new_coretext(&font.native_font()) } pub fn new_from_slice(data: &[u8], idx: u32) -> Result<Font, Error> { let blob = Blob::from_slice(data)?; let face = Face::from_blob(&blob, idx)?; let font = unsafe { hb_font_create(face.face) }; ensure!(!font.is_null(), "failed to convert face to font"); Ok(Self { font }) } pub fn set_load_flags(&mut self, load_flags: freetype::FT_Int32) { unsafe { hb_ft_font_set_load_flags(self.font, load_flags); } } pub fn shape(&mut self, buf: &mut Buffer, features: Option<&[hb_feature_t]>) { unsafe { if let Some(features) = features { hb_shape(self.font, buf.buf, features.as_ptr(), features.len() as u32) } else { hb_shape(self.font, buf.buf, ptr::null(), 0) } } } } pub struct Buffer { buf: *mut hb_buffer_t, } impl Drop for Buffer { fn drop(&mut self) { unsafe { hb_buffer_destroy(self.buf); } } } impl Buffer { pub fn new() -> Result<Buffer, Error> { let buf = unsafe { hb_buffer_create() }; ensure!( unsafe { hb_buffer_allocation_successful(buf) } != 0, "hb_buffer_create failed" ); Ok(Buffer { buf }) } #[allow(dead_code)] pub fn reset(&mut self) { unsafe { hb_buffer_reset(self.buf); } } pub fn set_direction(&mut self, direction: hb_direction_t) { unsafe { hb_buffer_set_direction(self.buf, direction); } } pub fn set_script(&mut self, script: hb_script_t) { unsafe { hb_buffer_set_script(self.buf, script); } } pub fn set_language(&mut self, lang: hb_language_t) { unsafe { hb_buffer_set_language(self.buf, lang); } } #[allow(dead_code)] pub fn add(&mut self, codepoint: hb_codepoint_t, cluster: u32) { unsafe { hb_buffer_add(self.buf, codepoint, cluster); } } pub fn add_utf8(&mut self, buf: &[u8]) { unsafe { hb_buffer_add_utf8( self.buf, buf.as_ptr() as *const i8, buf.len() as i32, 0, buf.len() as i32, ); } } pub fn add_str(&mut self, s: &str) { self.add_utf8(s.as_bytes()) } pub fn glyph_infos(&self) -> &[hb_glyph_info_t] { unsafe { let mut len: u32 = 0; let info = hb_buffer_get_glyph_infos(self.buf, &mut len as *mut _); slice::from_raw_parts(info, len as usize) } }
}
pub fn glyph_positions(&self) -> &[hb_glyph_position_t] { unsafe { let mut len: u32 = 0; let pos = hb_buffer_get_glyph_positions(self.buf, &mut len as *mut _); slice::from_raw_parts(pos, len as usize) } }
function_block-full_function
[ { "content": "/// A convenience function that wraps Base91Decoder; it decodes a slice of data\n\n/// and returns a vector holding the unencoded binary data.\n\npub fn decode(buf: &[u8]) -> Vec<u8> {\n\n let mut result = Vec::with_capacity(buf.len());\n\n {\n\n let mut writer = Base91Decoder::new(&m...
Rust
crates/swc_ecma_transforms_optimization/src/simplify/const_propgation.rs
maxxcs/swc
a2a0b63c6297de039a5703a549eae62ae20b48c8
use swc_common::{collections::AHashMap, util::take::Take}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn constant_propagation() -> impl 'static + Fold + VisitMut { as_folder(ConstPropagation::default()) } #[derive(Default)] struct ConstPropagation<'a> { scope: Scope<'a>, } #[derive(Default)] struct Scope<'a> { parent: Option<&'a Scope<'a>>, vars: AHashMap<Id, Box<Expr>>, } impl<'a> Scope<'a> { fn new(parent: &'a Scope<'a>) -> Self { Self { parent: Some(parent), vars: Default::default(), } } fn find_var(&self, id: &Id) -> Option<&Box<Expr>> { if let Some(v) = self.vars.get(id) { return Some(v); } self.parent.and_then(|parent| parent.find_var(id)) } } impl VisitMut for ConstPropagation<'_> { noop_visit_mut_type!(); fn visit_mut_function(&mut self, n: &mut Function) { let scope = Scope::new(&self.scope); let mut v = ConstPropagation { scope }; n.visit_mut_children_with(&mut v); } fn visit_mut_var_decl(&mut self, var: &mut VarDecl) { var.decls.visit_mut_with(self); if let VarDeclKind::Const = var.kind { for decl in &var.decls { match &decl.name { Pat::Ident(name) => match &decl.init { Some(init) => match &**init { Expr::Lit(Lit::Bool(..)) | Expr::Lit(Lit::Num(..)) | Expr::Lit(Lit::Null(..)) => { self.scope.vars.insert(name.to_id(), init.clone()); } Expr::Ident(init) if name.id.span.is_dummy() || var.span.is_dummy() || init.span.is_dummy() => { if let Some(value) = self.scope.vars.get(&init.to_id()).cloned() { self.scope.vars.insert(name.to_id(), value); } else { self.scope .vars .insert(name.to_id(), Box::new(Expr::Ident(init.clone()))); } } _ => {} }, None => {} }, _ => {} } } } } fn visit_mut_prop(&mut self, p: &mut Prop) { p.visit_mut_children_with(self); match p { Prop::Shorthand(i) => { if let Some(expr) = self.scope.find_var(&i.to_id()) { *p = Prop::KeyValue(KeyValueProp { key: PropName::Ident(i.take()), value: expr.clone(), }); return; } } _ => {} } } fn visit_mut_assign_expr(&mut self, _: &mut AssignExpr) {} fn visit_mut_expr(&mut self, e: &mut Expr) { match e { Expr::Ident(i) => { if let Some(expr) = self.scope.find_var(&i.to_id()) { *e = *expr.clone(); return; } } _ => {} } e.visit_mut_children_with(self); } fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) { e.obj.visit_mut_with(self); if e.computed { e.prop.visit_mut_with(self); } } fn visit_mut_export_named_specifier(&mut self, n: &mut ExportNamedSpecifier) { if let Some(expr) = self.scope.find_var(&n.orig.to_id()) { match &**expr { Expr::Ident(v) => { let orig = n.orig.clone(); n.orig = v.clone(); if n.exported.is_none() { n.exported = Some(orig); } } _ => {} } } match &n.exported { Some(exported) => { if exported.sym == n.orig.sym && exported.span.ctxt == n.orig.span.ctxt { n.exported = None; } } None => {} } } }
use swc_common::{collections::AHashMap, util::take::Take}; use swc_ecma_ast::*; use swc_ecma_utils::{ident::IdentLike, Id}; use swc_ecma_visit::{as_folder, noop_visit_mut_type, Fold, VisitMut, VisitMutWith}; pub fn constant_propagation() -> impl 'static + Fold + VisitMut { as_folder(ConstPropagation::default()) } #[derive(Default)] struct ConstPropagation<'a> { scope: Scope<'a>, } #[derive(Default)] struct Scope<'a> { parent: Option<&'a Scope<'a>>, vars: AHashMap<Id, Box<Expr>>, } impl<'a> Scope<'a> { fn new(parent: &'a Scope<'a>) -> Self { Self { parent: Some(parent), vars: Default::default(), } } fn find_var(&
} impl VisitMut for ConstPropagation<'_> { noop_visit_mut_type!(); fn visit_mut_function(&mut self, n: &mut Function) { let scope = Scope::new(&self.scope); let mut v = ConstPropagation { scope }; n.visit_mut_children_with(&mut v); } fn visit_mut_var_decl(&mut self, var: &mut VarDecl) { var.decls.visit_mut_with(self); if let VarDeclKind::Const = var.kind { for decl in &var.decls { match &decl.name { Pat::Ident(name) => match &decl.init { Some(init) => match &**init { Expr::Lit(Lit::Bool(..)) | Expr::Lit(Lit::Num(..)) | Expr::Lit(Lit::Null(..)) => { self.scope.vars.insert(name.to_id(), init.clone()); } Expr::Ident(init) if name.id.span.is_dummy() || var.span.is_dummy() || init.span.is_dummy() => { if let Some(value) = self.scope.vars.get(&init.to_id()).cloned() { self.scope.vars.insert(name.to_id(), value); } else { self.scope .vars .insert(name.to_id(), Box::new(Expr::Ident(init.clone()))); } } _ => {} }, None => {} }, _ => {} } } } } fn visit_mut_prop(&mut self, p: &mut Prop) { p.visit_mut_children_with(self); match p { Prop::Shorthand(i) => { if let Some(expr) = self.scope.find_var(&i.to_id()) { *p = Prop::KeyValue(KeyValueProp { key: PropName::Ident(i.take()), value: expr.clone(), }); return; } } _ => {} } } fn visit_mut_assign_expr(&mut self, _: &mut AssignExpr) {} fn visit_mut_expr(&mut self, e: &mut Expr) { match e { Expr::Ident(i) => { if let Some(expr) = self.scope.find_var(&i.to_id()) { *e = *expr.clone(); return; } } _ => {} } e.visit_mut_children_with(self); } fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) { e.obj.visit_mut_with(self); if e.computed { e.prop.visit_mut_with(self); } } fn visit_mut_export_named_specifier(&mut self, n: &mut ExportNamedSpecifier) { if let Some(expr) = self.scope.find_var(&n.orig.to_id()) { match &**expr { Expr::Ident(v) => { let orig = n.orig.clone(); n.orig = v.clone(); if n.exported.is_none() { n.exported = Some(orig); } } _ => {} } } match &n.exported { Some(exported) => { if exported.sym == n.orig.sym && exported.span.ctxt == n.orig.span.ctxt { n.exported = None; } } None => {} } } }
self, id: &Id) -> Option<&Box<Expr>> { if let Some(v) = self.vars.get(id) { return Some(v); } self.parent.and_then(|parent| parent.find_var(id)) }
function_block-function_prefixed
[]
Rust
mayastor/tests/yaml_config.rs
whoan/Mayastor
a541eebfd021d937d374b41f2b297224014ffe3b
use std::{fs::metadata, sync::Mutex, time::Duration}; use common::ms_exec::run_test; use mayastor::{subsys, subsys::Config}; pub mod common; #[test] fn yaml_default() { let args = vec!["-s".into(), "128".into()]; run_test(Box::from(args), |ms| { let out = ms .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); }); } #[test] fn yaml_not_exist() { let args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/test.yaml".into(), ]; common::delete_file(&["/tmp/test.yaml".into()]); run_test(Box::from(args), |ms| { let out = ms .rpc_call("mayastor_config_export", serde_json::json!(null)) .unwrap(); assert_eq!(out, serde_json::Value::Null); assert_eq!(metadata("/tmp/test.yaml").unwrap().is_file(), true); }); } #[test] fn yaml_load_from_existing() { let mut cfg = Config::default(); common::truncate_file("/tmp/disk1.img", 1024 * 64); let bdev = subsys::BaseBdev { uri: "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c".to_string(), }; cfg.source = Some("/tmp/loadme.yaml".into()); cfg.base_bdevs = Some(vec![bdev]); cfg.write("/tmp/loadme.yaml").unwrap(); assert_eq!( std::fs::metadata("/tmp/loadme.yaml").unwrap().is_file(), true ); let args = vec![ "-s".to_string(), "128".to_string(), "-y".to_string(), "/tmp/loadme.yaml".to_string(), ]; run_test(Box::from(args), |ms| { let out = ms .rpc_call( "framework_get_config", serde_json::json!({"name": "MayastorConfig"}), ) .unwrap(); let base_bdevs = out .as_object() .unwrap() .get("base_bdevs") .unwrap() .as_array() .unwrap(); assert_eq!( base_bdevs[0]["uri"].as_str().unwrap(), "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c" ); let bdev = ms.rpc_call( "bdev_get_bdevs", serde_json::json!({"name": "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c"}), ).unwrap(); assert_ne!(bdev.as_array().unwrap().len(), 0); }); common::delete_file(&["/tmp/disk1.img".into()]); } #[test] fn yaml_pool_tests() { let mut cfg = Config::default(); common::delete_file(&["/tmp/disk1.img".into()]); common::truncate_file("/tmp/disk1.img", 1024 * 64); let pool = subsys::Pool { name: "tpool".to_string(), disks: vec!["/tmp/disk1.img".into()], blk_size: 512, io_if: 1, }; let uuid: Mutex<String> = Mutex::new("".into()); cfg.source = Some("/tmp/pool.yaml".into()); cfg.pools = Some(vec![pool]); cfg.nexus_opts.nvmf_enable = false; cfg.write("/tmp/pool.yaml").unwrap(); let args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/pool.yaml".to_string(), ]; run_test(Box::from(args.clone()), |ms| { let lvs_list = common::retry(10, Duration::from_millis(500), || { let lvs_list = ms .rpc_call("bdev_lvol_get_lvstores", serde_json::json!(null)) .unwrap(); if lvs_list.is_array() { Ok(lvs_list) } else { Err(()) } }); let lvs = lvs_list.as_array().unwrap()[0].as_object().unwrap(); assert_eq!(lvs.get("name").unwrap(), "tpool"); *uuid.lock().unwrap() = lvs.get("uuid").unwrap().to_string(); common::delete_file(&["/tmp/pool.yaml".into()]); let out = ms .rpc_call("mayastor_config_export", serde_json::json!(null)) .unwrap(); assert_eq!(out, serde_json::Value::Null); assert_eq!(metadata("/tmp/pool.yaml").unwrap().is_file(), true); }); run_test(Box::from(args), |ms| { let lvols = common::retry(10, Duration::from_millis(500), || { let vols = ms .rpc_call("bdev_lvol_get_lvstores", serde_json::json!(null)) .unwrap(); if vols.as_array().unwrap().is_empty() { Err(()) } else { Ok(vols) } }); assert_eq!( *uuid.lock().unwrap(), lvols.as_array().unwrap()[0] .as_object() .unwrap() .get("uuid") .unwrap() .to_string() ); }); common::delete_file(&["/tmp/disk1.img".into()]); } #[test] fn yaml_multi_maya() { common::delete_file(&[ "/tmp/first.yaml".to_string(), "/tmp/second.yaml".into(), ]); let mut first = Config::default(); let second = Config::default(); first.nexus_opts.iscsi_enable = false; first.nexus_opts.nvmf_enable = false; first.write("/tmp/first.yaml").unwrap(); second.write("/tmp/second.yaml").unwrap(); let first_args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/first.yaml".into(), ]; let second_args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/second.yaml".into(), ]; run_test(Box::from(first_args), |ms1| { let out = ms1 .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); run_test(Box::from(second_args), |ms2| { let out = ms2 .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); }); }); common::delete_file(&[ "/tmp/first.yaml".to_string(), "/tmp/second.yaml".into(), ]) }
use std::{fs::metadata, sync::Mutex, time::Duration}; use common::ms_exec::run_test; use mayastor::{subsys, subsys::Config}; pub mod common; #[test] fn yaml_default() { let args = vec!["-s".into(), "128".into()]; run_test(Box::from(args), |ms| { let out = ms .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); }); } #[test]
#[test] fn yaml_load_from_existing() { let mut cfg = Config::default(); common::truncate_file("/tmp/disk1.img", 1024 * 64); let bdev = subsys::BaseBdev { uri: "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c".to_string(), }; cfg.source = Some("/tmp/loadme.yaml".into()); cfg.base_bdevs = Some(vec![bdev]); cfg.write("/tmp/loadme.yaml").unwrap(); assert_eq!( std::fs::metadata("/tmp/loadme.yaml").unwrap().is_file(), true ); let args = vec![ "-s".to_string(), "128".to_string(), "-y".to_string(), "/tmp/loadme.yaml".to_string(), ]; run_test(Box::from(args), |ms| { let out = ms .rpc_call( "framework_get_config", serde_json::json!({"name": "MayastorConfig"}), ) .unwrap(); let base_bdevs = out .as_object() .unwrap() .get("base_bdevs") .unwrap() .as_array() .unwrap(); assert_eq!( base_bdevs[0]["uri"].as_str().unwrap(), "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c" ); let bdev = ms.rpc_call( "bdev_get_bdevs", serde_json::json!({"name": "aio:///tmp/disk1.img?blk_size=512&uuid=3dbbaeb0-ec02-4962-99c5-4e8f67c6b80c"}), ).unwrap(); assert_ne!(bdev.as_array().unwrap().len(), 0); }); common::delete_file(&["/tmp/disk1.img".into()]); } #[test] fn yaml_pool_tests() { let mut cfg = Config::default(); common::delete_file(&["/tmp/disk1.img".into()]); common::truncate_file("/tmp/disk1.img", 1024 * 64); let pool = subsys::Pool { name: "tpool".to_string(), disks: vec!["/tmp/disk1.img".into()], blk_size: 512, io_if: 1, }; let uuid: Mutex<String> = Mutex::new("".into()); cfg.source = Some("/tmp/pool.yaml".into()); cfg.pools = Some(vec![pool]); cfg.nexus_opts.nvmf_enable = false; cfg.write("/tmp/pool.yaml").unwrap(); let args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/pool.yaml".to_string(), ]; run_test(Box::from(args.clone()), |ms| { let lvs_list = common::retry(10, Duration::from_millis(500), || { let lvs_list = ms .rpc_call("bdev_lvol_get_lvstores", serde_json::json!(null)) .unwrap(); if lvs_list.is_array() { Ok(lvs_list) } else { Err(()) } }); let lvs = lvs_list.as_array().unwrap()[0].as_object().unwrap(); assert_eq!(lvs.get("name").unwrap(), "tpool"); *uuid.lock().unwrap() = lvs.get("uuid").unwrap().to_string(); common::delete_file(&["/tmp/pool.yaml".into()]); let out = ms .rpc_call("mayastor_config_export", serde_json::json!(null)) .unwrap(); assert_eq!(out, serde_json::Value::Null); assert_eq!(metadata("/tmp/pool.yaml").unwrap().is_file(), true); }); run_test(Box::from(args), |ms| { let lvols = common::retry(10, Duration::from_millis(500), || { let vols = ms .rpc_call("bdev_lvol_get_lvstores", serde_json::json!(null)) .unwrap(); if vols.as_array().unwrap().is_empty() { Err(()) } else { Ok(vols) } }); assert_eq!( *uuid.lock().unwrap(), lvols.as_array().unwrap()[0] .as_object() .unwrap() .get("uuid") .unwrap() .to_string() ); }); common::delete_file(&["/tmp/disk1.img".into()]); } #[test] fn yaml_multi_maya() { common::delete_file(&[ "/tmp/first.yaml".to_string(), "/tmp/second.yaml".into(), ]); let mut first = Config::default(); let second = Config::default(); first.nexus_opts.iscsi_enable = false; first.nexus_opts.nvmf_enable = false; first.write("/tmp/first.yaml").unwrap(); second.write("/tmp/second.yaml").unwrap(); let first_args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/first.yaml".into(), ]; let second_args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/second.yaml".into(), ]; run_test(Box::from(first_args), |ms1| { let out = ms1 .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); run_test(Box::from(second_args), |ms2| { let out = ms2 .rpc_call("rpc_get_methods", serde_json::json!(null)) .unwrap(); assert_ne!(out.as_array().unwrap().len(), 0); }); }); common::delete_file(&[ "/tmp/first.yaml".to_string(), "/tmp/second.yaml".into(), ]) }
fn yaml_not_exist() { let args = vec![ "-s".to_string(), "128".into(), "-y".into(), "/tmp/test.yaml".into(), ]; common::delete_file(&["/tmp/test.yaml".into()]); run_test(Box::from(args), |ms| { let out = ms .rpc_call("mayastor_config_export", serde_json::json!(null)) .unwrap(); assert_eq!(out, serde_json::Value::Null); assert_eq!(metadata("/tmp/test.yaml").unwrap().is_file(), true); }); }
function_block-full_function
[ { "content": "/// start mayastor as a separate process and run the closure. By wrapping the\n\n/// test closure, we can catch errors but still kill mayastor to avoid dangling\n\n/// process.\n\npub fn run_test<T>(args: Box<[String]>, test: T)\n\nwhere\n\n T: FnOnce(&MayastorProcess) + panic::UnwindSafe,\n\n{...
Rust
tests/integration_test.rs
Baawa/chiselstore
b1ab1dba568ab4aafe9f3e199a94f3f562560ed3
use chiselstore::rpc::proto::rpc_server::RpcServer; use chiselstore::{ rpc::{RpcService, RpcTransport}, StoreServer, }; use std::sync::Arc; use tonic::transport::Server; extern crate futures; use crate::futures::FutureExt; pub mod proto { tonic::include_proto!("proto"); } use proto::rpc_client::RpcClient; use proto::{Query}; use tokio::sync::oneshot; use slog::info; use sloggers::Build; use sloggers::terminal::{TerminalLoggerBuilder, Destination}; use sloggers::types::Severity; fn log(s: String) { let mut builder = TerminalLoggerBuilder::new(); builder.level(Severity::Debug); builder.destination(Destination::Stderr); let logger = builder.build().unwrap(); info!(logger, "{}", s); } fn node_authority(id: u64) -> (&'static str, u16) { let host = "127.0.0.1"; let port = 50000 + (id as u16); (host, port) } fn node_rpc_addr(id: u64) -> String { let (host, port) = node_authority(id); format!("http://{}:{}", host, port) } struct Replica { store_server: std::sync::Arc<StoreServer<RpcTransport>>, store_message_handle: tokio::task::JoinHandle<()>, store_ble_handle: tokio::task::JoinHandle<()>, rpc_handle: tokio::task::JoinHandle<Result<(), tonic::transport::Error>>, halt_sender: tokio::sync::oneshot::Sender<()>, shutdown_sender: tokio::sync::oneshot::Sender<()>, } impl Replica { pub async fn shutdown(self) { self.shutdown_sender.send(()); self.rpc_handle.await.unwrap(); self.halt_sender.send(()); self.store_message_handle.await.unwrap(); self.store_ble_handle.await.unwrap(); } pub fn is_leader(&self) -> bool { self.store_server.get_current_leader() == self.store_server.get_id() } pub fn get_id(&self) -> u64 { self.store_server.get_id() } pub fn get_current_leader(&self) -> u64 { self.store_server.get_current_leader() } pub fn reconfigure(&self, new_cluster: Vec<u64>) { self.store_server.reconfigure(new_cluster); } } async fn start_replica(id: u64, peers: Vec<u64>) -> Replica { let (host, port) = node_authority(id); let rpc_listen_addr = format!("{}:{}", host, port).parse().unwrap(); let transport = RpcTransport::new(Box::new(node_rpc_addr)); let server = StoreServer::start(id, peers, transport).unwrap(); let server = Arc::new(server); let (halt_sender, halt_receiver) = oneshot::channel::<()>(); let store_handles = { let server_receiver = server.clone(); let server_message_loop = server.clone(); let server_ble_loop = server.clone(); tokio::task::spawn(async move { match halt_receiver.await { Ok(_) => server_receiver.set_halt(true), Err(_) => println!("Received error in halt_receiver"), }; }); let ble_loop = tokio::task::spawn(async move { log(format!("BLE loop starting for pid: {}", id).to_string()); server_ble_loop.run_ble_loop().await; log("BLE loop shutting down".to_string()); }); let message_loop = tokio::task::spawn(async move { log(format!("Message loop starting for pid: {}", id).to_string()); server_message_loop.run_message_loop().await; log("Message loop shutting down".to_string()); }); (message_loop, ble_loop) }; let (shutdown_sender, shutdown_receiver) = oneshot::channel::<()>(); let rpc_handle = { let server = server.clone(); let rpc = RpcService::new(server); tokio::task::spawn(async move { log(format!("RPC listening to {} ...", rpc_listen_addr).to_string()); let ret = Server::builder() .add_service(RpcServer::new(rpc)) .serve_with_shutdown(rpc_listen_addr, shutdown_receiver.map(drop)) .await; log("RPC Server shutting down...".to_string()); ret }) }; return Replica { store_server: server.clone(), store_message_handle: store_handles.0, store_ble_handle: store_handles.1, rpc_handle, halt_sender, shutdown_sender, } } async fn setup_replicas(num_replicas: u64) -> Vec<Replica> { let mut replicas: Vec<Replica> = Vec::new(); for id in 1..(num_replicas+1) { let mut peers: Vec<u64> = (1..num_replicas+1).collect(); peers.remove((id - 1) as usize); log(format!("setup pid: {} peers: {:?}", id, peers).to_string()); replicas.push(start_replica(id, peers).await); } return replicas } async fn shutdown_replicas(mut replicas: Vec<Replica>) { while let Some(r) = replicas.pop() { r.shutdown().await; } } use std::error::Error; async fn query(replica_id: u64, sql: String) -> Result<String, Box<dyn Error>> { let addr = node_rpc_addr(replica_id); let mut client = RpcClient::connect(addr).await.unwrap(); let query = tonic::Request::new(Query { sql: sql, }); let response = client.execute(query).await.unwrap(); let response = response.into_inner(); if response.rows.len() == 0 || response.rows[0].values.len() == 0 { return Ok(String::from("")); } let res = response.rows[0].values[0].clone(); Ok(res) } #[tokio::test(flavor = "multi_thread")] async fn connect_to_cluster() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { let res = query(1, String::from("SELECT 1+1;")).await.unwrap(); assert!(res == "2"); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn write_read() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test (id integer PRIMARY KEY)")).await.unwrap(); query(1, String::from("INSERT INTO test VALUES(1)")).await.unwrap(); let res = query(1, String::from("SELECT id FROM test WHERE id = 1")).await.unwrap(); assert!(res == "1"); log(format!("query res: {}", res).to_string()); let res = query(2, String::from("SELECT id FROM test WHERE id = 1")).await.unwrap(); assert!(res == "1"); log(format!("query res: {}", res).to_string()); query(1, String::from("DROP TABLE test")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn synchronous_writes() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_synchronous (id integer PRIMARY KEY, value integer NOT NULL)")).await.unwrap(); }).await.unwrap(); let write_a = tokio::task::spawn(async { println!("write_a"); query(1, String::from("INSERT OR REPLACE INTO test_synchronous VALUES(1,1)")).await.unwrap(); }); let write_b = tokio::task::spawn(async { println!("write_b"); query(2, String::from("INSERT OR REPLACE INTO test_synchronous VALUES(1,2)")).await.unwrap(); }); write_a.await.unwrap(); write_b.await.unwrap(); let x = query(1, String::from("SELECT value FROM test_synchronous WHERE id = 1")).await.unwrap(); let y = query(2, String::from("SELECT value FROM test_synchronous WHERE id = 1")).await.unwrap(); assert!(x == y); query(1, String::from("DROP TABLE test_synchronous")).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn leader_crashes() { let mut replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_leader_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut leader_idx = 0; for (i, r) in replicas.iter().enumerate() { if r.is_leader() { leader_idx = i; break } } let leader = replicas.remove(leader_idx); leader.shutdown().await; log(format!("Leader with idx {} dead", leader_idx).to_string()); tokio::time::sleep(tokio::time::Duration::from_millis(5000)).await; let mut new_leader_idx = 0; let mut new_cluster: Vec<u64> = Vec::new(); for (i, r) in replicas.iter().enumerate() { if r.is_leader() { new_leader_idx = i; } new_cluster.push(r.get_id()); } replicas[new_leader_idx].reconfigure(new_cluster); log(format!("Leader with idx {} reconfigure", new_leader_idx).to_string()); tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; let living_replica_id = replicas[new_leader_idx].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("INSERT INTO test_leader_drop VALUES(1)")).await.unwrap(); }).await.unwrap(); let living_replica_id = replicas[new_leader_idx].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("DROP TABLE test_leader_drop")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn follower_crashes() { let mut replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_follower_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut follower_idx = 0; for (i, r) in replicas.iter().enumerate() { if !r.is_leader() { follower_idx = i; break } } let follower = replicas.remove(follower_idx); follower.shutdown().await; let living_replica_id = replicas[0].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("INSERT INTO test_follower_drop VALUES(1)")).await.unwrap(); }).await.unwrap(); tokio::task::spawn(async move { query(living_replica_id, String::from("DROP TABLE test_follower_drop")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; }
use chiselstore::rpc::proto::rpc_server::RpcServer; use chiselstore::{ rpc::{RpcService, RpcTransport}, StoreServer, }; use std::sync::Arc; use tonic::transport::Server; extern crate futures; use crate::futures::FutureExt; pub mod proto { tonic::include_proto!("proto"); } use proto::rpc_client::RpcClient; use proto::{Query}; use tokio::sync::oneshot; use slog::info; use sloggers::Build; use sloggers::terminal::{TerminalLoggerBuilder, Destination}; use sloggers::types::Severity; fn log(s: String) { let mut builder = TerminalLoggerBuilder::new(); builder.level(Severity::Debug); builder.destination(Destination::Stderr); let logger = builder.build().unwrap(); info!(logger, "{}", s); } fn node_authority(id: u64) -> (&'static str, u16) { let host = "127.0.0.1"; let port = 50000 + (id as u16); (host, port) } fn node_rpc_addr(id: u64) -> String { let (host, port) = node_authority(id); format!("http://{}:{}", host, port) } struct Replica { store_server: std::sync::Arc<StoreServer<RpcTransport>>, store_message_handle: tokio::task::JoinHandle<()>, store_ble_handle: tokio::task::JoinHandle<()>, rpc_handle: tokio::task::JoinHandle<Result<(), tonic::transport::Error>>, halt_sender: tokio::sync::oneshot::Sender<()>, shutdown_sender: tokio::sync::oneshot::Sender<()>, } impl Replica { pub async fn shutdown(self) { self.shutdown_sender.send(()); self.rpc_handle.await.unwrap(); self.halt_sender.send(()); self.store_message_handle.await.unwrap(); self.store_ble_handle.await.unwrap(); } pub fn is_leader(&self) -> bool { self.store_server.get_current_leader() == self.store_server.get_id() } pub fn get_id(&self) -> u64 { self.store_server.get_id() } pub fn get_current_leader(&self) -> u64 { self.store_server.get_current_leader() } pub fn reconfigure(&self, new_cluster: Vec<u64>) { self.store_server.reconfigure(new_cluster); } } async fn start_replica(id: u64, peers: Vec<u64>) -> Replica { let (host, port) = node_authority(id); let rpc_listen_addr = format!("{}:{}", host, port).parse().unwrap(); let transport = RpcTransport::new(Box::new(node_rpc_addr)); let server = StoreServer::start(id, peers, transport).unwrap(); let server = Arc::new(server); let (halt_sender, halt_receiver) = oneshot::channel::<()>(); let store_handles = { let server_receiver = server.clone(); let server_message_loop = server.clone(); let server_ble_loop = server.clone(); tokio::task::spawn(async move { match halt_receiver.await { Ok(_) => server_receiver.set_halt(true), Err(_) => println!("Received error in halt_receiver"), }; }); let ble_loop = tokio::task::spawn(async move { log(format!("BLE loop starting for pid: {}", id).to_string()); server_ble_loop.run_ble_loop().await; log("BLE loop shutting down".to_string()); }); let message_loop = tokio::task::spawn(async move { log(format!("Message loop starting for pid: {}", id).to_string()); server_message_loop.run_message_loop().await; log("Message loop shutting down".to_string()); }); (message_loop, ble_loop) }; let (shutdown_sender, shutdown_receiver) = oneshot::channel::<()>(); let rpc_handle = { let server = server.clone(); let rpc = RpcService::new(server); tokio::task::spawn(async move { log(format!("RPC listening to {} ...", rpc_listen_addr).to_string()); let ret = Server::builder() .add_service(RpcServer::new(rpc)) .serve_with_shutdown(rpc_listen_addr, shutdown_receiver.map(drop)) .await; log("RPC Server shutting down...".to_string()); ret }) }; return Replica { store_server: server.clone(), store_message_handle: store_handles.0, store_ble_handle: store_handles.1, rpc_handle, halt_sender, shutdown_sender, } } async fn setup_replicas(num_replicas: u64) -> Vec<Replica> { let mut replicas: Vec<Replica> = Vec::new(); for id in 1..(num_replicas+1) { let mut peers: Vec<u64> = (1..num_replicas+1).collect(); peers.remove((id - 1) as usize); log(format!("setup pid: {} peers: {:?}", id, peers).to_string()); replicas.push(start_replica(id, peers).await); } return replicas } async fn shutdown_replicas(mut replicas: Vec<Replica>) { while let Some(r) = replicas.pop() { r.shutdown().await; } } use std::error::Error; async fn query(replica_id: u64, sql: String) -> Result<String, Box<dyn Error>> { let addr = node_rpc_addr(replica_id); let mut client = RpcClient::connect(addr).await.unwrap(); let query = tonic::Request::new(Query { sql: sql, }); let response = client.execute(query).await.unwrap(); let response = response.into_inner(); if response.rows.len() == 0 || response.rows[0].values.len() == 0 { return Ok(String::from("")); } let res = response.rows[0].values[0].clone(); Ok(res) } #[tokio::test(flavor = "multi_thread")] async fn connect_to_cluster() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { let res = query(1, String::from("SELECT 1+1;")).await.unwrap(); assert!(res == "2"); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn write_read() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test (id integer PRIMARY KEY)")).await.unwrap(); query(1, String::from("INSERT INTO test VALUES(1)")).await.unwrap(); let res = query(1, String::from("SELECT id FROM test WHERE id = 1")).await.unwrap(); assert!(res == "1"); log(format!("query res: {}", res).to_string()); let res = query(2, String::from("SELECT id FROM test WHERE id = 1")).await.unwrap(); assert!(res == "1"); log(format!("query res: {}", res).to_string()); query(1, String::from("DROP TABLE test")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn synchronous_writes() { let mut replicas = setup_replicas(2).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_synchronous (id integer PRIMARY KEY, value integer NOT NULL)")).await.unwrap(); }).await.unwrap(); let write_a = tokio::task::spawn(async { println!("write_a"); query(1, String::from("INSERT OR REPLACE INTO test_synchronous VALUES(1,1)")).await.unwrap(); }); let write_b = tokio::task::spawn(async { println!("write_b"); query(2, String::from("INSERT OR REPLACE INTO test_synchronous VALUES(1,2)")).await.unwrap(); }); write_a.await.unwrap(); write_b.await.unwrap(); let x = query(1, String::from("SELECT value FROM test_synchronous WHERE id = 1")).await.unwrap(); let y = query(2, String::from("SELECT value FROM test_synchronous WHERE id = 1")).await.unwrap(); assert!(x == y); query(1, String::from("DROP TABLE test_synchronous")).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn leader_crashes() { let mut
let mut replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_follower_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut follower_idx = 0; for (i, r) in replicas.iter().enumerate() { if !r.is_leader() { follower_idx = i; break } } let follower = replicas.remove(follower_idx); follower.shutdown().await; let living_replica_id = replicas[0].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("INSERT INTO test_follower_drop VALUES(1)")).await.unwrap(); }).await.unwrap(); tokio::task::spawn(async move { query(living_replica_id, String::from("DROP TABLE test_follower_drop")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; }
replicas = setup_replicas(3).await; tokio::task::spawn(async { query(1, String::from("CREATE TABLE IF NOT EXISTS test_leader_drop (id integer PRIMARY KEY)")).await.unwrap(); }).await.unwrap(); let mut leader_idx = 0; for (i, r) in replicas.iter().enumerate() { if r.is_leader() { leader_idx = i; break } } let leader = replicas.remove(leader_idx); leader.shutdown().await; log(format!("Leader with idx {} dead", leader_idx).to_string()); tokio::time::sleep(tokio::time::Duration::from_millis(5000)).await; let mut new_leader_idx = 0; let mut new_cluster: Vec<u64> = Vec::new(); for (i, r) in replicas.iter().enumerate() { if r.is_leader() { new_leader_idx = i; } new_cluster.push(r.get_id()); } replicas[new_leader_idx].reconfigure(new_cluster); log(format!("Leader with idx {} reconfigure", new_leader_idx).to_string()); tokio::time::sleep(tokio::time::Duration::from_millis(2000)).await; let living_replica_id = replicas[new_leader_idx].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("INSERT INTO test_leader_drop VALUES(1)")).await.unwrap(); }).await.unwrap(); let living_replica_id = replicas[new_leader_idx].get_id(); tokio::task::spawn(async move { query(living_replica_id, String::from("DROP TABLE test_leader_drop")).await.unwrap(); }).await.unwrap(); shutdown_replicas(replicas).await; } #[tokio::test(flavor = "multi_thread")] async fn follower_crashes() {
random
[ { "content": "pub fn log(s: String) {\n\n let mut builder = TerminalLoggerBuilder::new();\n\n builder.level(Severity::Debug);\n\n builder.destination(Destination::Stderr);\n\n\n\n let logger = builder.build().unwrap();\n\n info!(logger, \"{}\", s);\n\n}\n", "file_path": "src/util/log.rs", ...
Rust
lib/tests/diff.rs
austinjones/texture-synthesis
52625c803523b659114d03ba0192bfb5c2905c07
use img_hash::{HashType, ImageHash}; use texture_synthesis as ts; use image::{imageops, DynamicImage, FilterType, GenericImageView, GrayImage, Pixel, RgbaImage}; use img_hash::HashImage; const FILTER_TYPE: FilterType = FilterType::Nearest; struct MyPrecious<T>(T); impl HashImage for MyPrecious<DynamicImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <DynamicImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(self.0.resize(width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { MyPrecious(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.raw_pixels() } fn channel_count() -> u8 { <<DynamicImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.pixels() { iter_fn(x, y, px.channels()); } } } impl HashImage for MyPrecious<GrayImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <GrayImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(imageops::resize(&self.0, width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { Self(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.into_raw() } fn channel_count() -> u8 { <<GrayImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.enumerate_pixels() { iter_fn(x, y, px.channels()); } } } impl HashImage for MyPrecious<RgbaImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <RgbaImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(imageops::resize(&self.0, width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { MyPrecious(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.into_raw() } fn channel_count() -> u8 { <<RgbaImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.enumerate_pixels() { iter_fn(x, y, px.channels()); } } } macro_rules! diff_hash { ($name:ident, $expected:expr, $gen:expr) => { #[test] fn $name() { let expected_hash = ImageHash::from_base64($expected).expect("loaded hash"); let generated = $gen .max_thread_count(1) .build() .unwrap() .run(None); let gen_img = generated.into_image(); let gen_hash = ImageHash::hash(&MyPrecious(gen_img), 8, HashType::DoubleGradient); if gen_hash != expected_hash { let distance = expected_hash.dist_ratio(&gen_hash); let txt_gen = gen_hash.to_base64(); assert_eq!($expected, txt_gen, "images hashes differed by {}", distance); } } }; } diff_hash!(single_example, "JKc2MqWo1iNWeJ856Ty6+a1M", { ts::Session::builder() .add_example(&"../imgs/1.jpg") .seed(120) .output_size(100, 100) }); diff_hash!(multi_example, "JFCWyK1a4vJ1eWNTQkPOmdy2", { ts::Session::builder() .add_examples(&[ &"../imgs/multiexample/1.jpg", &"../imgs/multiexample/2.jpg", &"../imgs/multiexample/3.jpg", &"../imgs/multiexample/4.jpg", ]) .resize_input(100, 100) .random_init(10) .seed(211) .output_size(100, 100) }); diff_hash!(guided, "JBQFEgoXm5KCiWZUfHHBhyYK", { ts::Session::builder() .add_example( ts::Example::builder(&"../imgs/2.jpg").with_guide(&"../imgs/masks/2_example.jpg"), ) .load_target_guide(&"../imgs/masks/2_target.jpg") .output_size(100, 100) }); diff_hash!(style_transfer, "JEMRDSUzJ4uhpHMes1Onenz0", { ts::Session::builder() .add_example(&"../imgs/multiexample/4.jpg") .load_target_guide(&"../imgs/tom.jpg") .output_size(100, 100) }); diff_hash!(inpaint, "JNG1tl5SaIkqauco1NEmtikk", { ts::Session::builder() .inpaint_example( &"../imgs/masks/3_inpaint.jpg", ts::Example::builder(&"../imgs/3.jpg") .set_sample_method(&"../imgs/masks/3_inpaint.jpg"), ) .resize_input(100, 100) .output_size(100, 100) }); diff_hash!(tiling, "JNSV0UiMaMzh2KotmlwojR2K", { ts::Session::builder() .inpaint_example( &"../imgs/masks/1_tile.jpg", ts::Example::new(&"../imgs/1.jpg"), ) .resize_input(100, 100) .output_size(100, 100) .tiling_mode(true) });
use img_hash::{HashType, ImageHash}; use texture_synthesis as ts; use image::{imageops, DynamicImage, FilterType, GenericImageView, GrayImage, Pixel, RgbaImage}; use img_hash::HashImage; const FILTER_TYPE: FilterType = FilterType::Nearest; struct MyPrecious<T>(T); impl HashImage for MyPrecious<DynamicImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <DynamicImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(self.0.resize(width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { MyPrecious(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.raw_pixels() } fn channel_count() -> u8 { <<DynamicImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.pixels() { iter_fn(x, y, px.channels()); } } } impl HashImage for MyPrecious<GrayImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <GrayImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(imageops::resize(&self.0, width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { Self(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.into_raw() } fn channel_count() -> u8 { <<GrayImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.enumerate_pixels() { iter_fn(x, y, px.channels()); } } } impl HashImage for MyPrecious<RgbaImage> { type Grayscale = MyPrecious<GrayImage>; fn dimensions(&self) -> (u32, u32) { <RgbaImage as GenericImageView>::dimensions(&self.0) } fn resize(&self, width: u32, height: u32) -> Self { Self(imageops::resize(&self.0, width, height, FILTER_TYPE)) } fn grayscale(&self) -> Self::Grayscale { MyPrecious(imageops::grayscale(&self.0)) } fn to_bytes(self) -> Vec<u8> { self.0.into_raw() } fn channel_count() -> u8 { <<RgbaImage as GenericImageView>::Pixel as Pixel>::CHANNEL_COUNT } fn foreach_pixel<F>(&self, mut iter_fn: F) where F: FnMut(u32, u32, &[u8]), { for (x, y, px) in self.0.enumerate_pixels() { iter_fn(x, y, px.channels()); } } } macro_rules! diff_hash { ($name:ident, $expected:expr, $gen:expr) => { #[test] fn $name() { let expected_hash = ImageHash::from_base64($expected).expect("loaded hash"); let generated = $gen .max_thread_count(1) .bui
.random_init(10) .seed(211) .output_size(100, 100) }); diff_hash!(guided, "JBQFEgoXm5KCiWZUfHHBhyYK", { ts::Session::builder() .add_example( ts::Example::builder(&"../imgs/2.jpg").with_guide(&"../imgs/masks/2_example.jpg"), ) .load_target_guide(&"../imgs/masks/2_target.jpg") .output_size(100, 100) }); diff_hash!(style_transfer, "JEMRDSUzJ4uhpHMes1Onenz0", { ts::Session::builder() .add_example(&"../imgs/multiexample/4.jpg") .load_target_guide(&"../imgs/tom.jpg") .output_size(100, 100) }); diff_hash!(inpaint, "JNG1tl5SaIkqauco1NEmtikk", { ts::Session::builder() .inpaint_example( &"../imgs/masks/3_inpaint.jpg", ts::Example::builder(&"../imgs/3.jpg") .set_sample_method(&"../imgs/masks/3_inpaint.jpg"), ) .resize_input(100, 100) .output_size(100, 100) }); diff_hash!(tiling, "JNSV0UiMaMzh2KotmlwojR2K", { ts::Session::builder() .inpaint_example( &"../imgs/masks/1_tile.jpg", ts::Example::new(&"../imgs/1.jpg"), ) .resize_input(100, 100) .output_size(100, 100) .tiling_mode(true) });
ld() .unwrap() .run(None); let gen_img = generated.into_image(); let gen_hash = ImageHash::hash(&MyPrecious(gen_img), 8, HashType::DoubleGradient); if gen_hash != expected_hash { let distance = expected_hash.dist_ratio(&gen_hash); let txt_gen = gen_hash.to_base64(); assert_eq!($expected, txt_gen, "images hashes differed by {}", distance); } } }; } diff_hash!(single_example, "JKc2MqWo1iNWeJ856Ty6+a1M", { ts::Session::builder() .add_example(&"../imgs/1.jpg") .seed(120) .output_size(100, 100) }); diff_hash!(multi_example, "JFCWyK1a4vJ1eWNTQkPOmdy2", { ts::Session::builder() .add_examples(&[ &"../imgs/multiexample/1.jpg", &"../imgs/multiexample/2.jpg", &"../imgs/multiexample/3.jpg", &"../imgs/multiexample/4.jpg", ]) .resize_input(100, 100)
random
[ { "content": "#[derive(Clone, Copy, Debug, Default)]\n\nstruct PatchId(u32);\n", "file_path": "lib/src/multires_stochastic_texture_synthesis.rs", "rank": 0, "score": 78339.35903847126 }, { "content": "#[derive(Clone, Copy, Debug)]\n\nstruct CoordFlat(u32);\n\n\n\nimpl CoordFlat {\n\n fn t...
Rust
xtask/src/docgen/extract.rs
zaida04/RSLint
05c9939d16aa45b24c3acd222e31917d49ad301a
use proc_macro2::TokenStream; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::*; use unindent::unindent; pub fn parse_group_mod(file: &str) -> Result<Group> { let file = parse_file(file)?; for item in file.items.iter() { if let Item::Macro(macro_call) = item { let call = macro_call.mac.clone(); if call .path .segments .last() .map_or(false, |x| x.ident == "group") { return parse2::<Group>(call.tokens); } } } Err(Error::new_spanned( file, "Expected a group! declaration in group mod file", )) } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Group { pub name: String, pub docstring: String, } impl Parse for Group { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(&input).unwrap_or_default(); let name = input.parse::<Ident>()?.to_string(); let _ = input.parse::<TokenStream>(); Ok(Self { name, docstring }) } } pub fn parse_rule_file(file: &str) -> Result<Option<RuleFile>> { let file = parse_file(file)?; let mut tests = None; let mut declaration = None; for item in file.items { if let Item::Macro(macro_call) = item { let call = macro_call.mac; if call .path .segments .last() .map_or(false, |x| x.ident == "declare_lint") { let res = parse2::<LintDeclaration>(call.tokens); declaration = Some(res?); } else if call .path .segments .last() .map_or(false, |x| x.ident == "rule_tests") && tests.is_none() { tests = Some(parse2::<RuleTests>(call.tokens)?); } } } if let Some(decl) = declaration { Ok(Some(RuleFile { lint_declaration: decl, tests, })) } else { Ok(None) } } #[derive(Clone)] pub struct RuleFile { pub lint_declaration: LintDeclaration, pub tests: Option<RuleTests>, } #[derive(Clone)] pub struct LintDeclaration { pub name: String, pub docstring: Option<String>, pub config_fields: Vec<ConfigField>, } #[derive(Clone)] pub struct ConfigField { pub docstring: Option<String>, pub field: Field, } impl Parse for LintDeclaration { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(input); input.parse::<Ident>()?; input.parse::<Token!(,)>()?; input.parse::<Ident>()?; input.parse::<Token!(,)>()?; let name = input.parse::<LitStr>()?.value(); let _ = input.parse::<Token!(,)>(); let config_fields = Punctuated::<ConfigField, Token![,]>::parse_terminated(input)? .into_iter() .filter(|field| matches!(field.field.vis, Visibility::Public(_))) .collect(); Ok(Self { name, docstring, config_fields, }) } } impl Parse for ConfigField { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(input); let field = input.call(Field::parse_named)?; Ok(Self { docstring, field }) } } fn parse_docstring(input: ParseStream) -> Option<String> { let mut res = String::new(); while input.peek(Token!(#)) { if let Ok(attr) = input.call(Attribute::parse_outer) { for attribute in attr { if attribute .path .get_ident() .map_or(false, |ident| ident == "doc") { let tokens = attribute.tokens.clone().into_iter().skip(1).collect(); let string = parse2::<LitStr>(tokens).expect("Invalid docstring").value(); res.push_str(&string); res.push('\n'); } } } } if res.is_empty() { None } else { Some(unindent(&res)) } } mod kw { syn::custom_keyword!(err); syn::custom_keyword!(ok); } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RuleTests { pub ok_examples: Vec<Example>, pub err_examples: Vec<Example>, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Example { pub source: String, pub docstring: Option<String>, } impl Parse for RuleTests { fn parse(input: ParseStream) -> Result<Self> { input.parse::<Expr>()?; input.parse::<Token!(,)>()?; input.parse::<kw::err>()?; input.parse::<Token!(:)>()?; let content; braced!(content in input); let mut err_examples: Vec<Example> = Punctuated::<Example, Token![,]>::parse_terminated(&content)? .into_iter() .collect(); err_examples = err_examples .into_iter() .filter(|elem| elem.docstring.as_ref().map(|x| x.trim()) != Some("ignore")) .collect(); err_examples.truncate(30); input.parse::<Token!(,)>()?; input.parse::<kw::ok>()?; input.parse::<Token!(:)>()?; let content; braced!(content in input); let mut ok_examples: Vec<Example> = Punctuated::<Example, Token![,]>::parse_terminated(&content)? .into_iter() .collect(); ok_examples = ok_examples .into_iter() .filter(|elem| elem.docstring.as_ref().map(|x| x.trim()) != Some("ignore")) .collect(); ok_examples.truncate(30); let _ = input.parse::<Token!(,)>(); Ok(Self { ok_examples, err_examples, }) } } impl Parse for Example { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(&input); let string = input.parse::<LitStr>()?.value(); let source = unindent(&string).trim().to_string(); Ok(Example { docstring, source }) } }
use proc_macro2::TokenStream; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::*; use unindent::unindent; pub fn parse_group_mod(file: &str) -> Result<Group> { let file = parse_file(file)?; for item in file.items.iter() { if let Item::Macro(macro_call) = item { let call = macro_call.mac.clone(); if call .path .segments .last() .map_or(false, |x| x.ident == "group") { return parse2::<Group>(call.tokens); } } } Err(Error::new_spanned( file, "Expected a group! declaration in group mod file", )) } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Group { pub name: String, pub docstring: String, } impl Parse for Group { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(&input).unwrap_or_default(); let name = input.parse::<Ident>()?.to_string(); let _ = input.parse::<TokenStream>(); Ok(Self { name, docstring }) } } pub fn parse_rule_file(file: &str) -> Result<Option<RuleFile>> { let file = parse_file(file)?; let mut tests = None; let mut declaration = None; for item in file.items { if let Item::Macro(macro_call) = item { let call = macro_call.mac; if call .path .segments .last() .map_or(false, |x| x.ident == "declare_lint") { let res = parse2::<LintDeclaration>(
ests: Option<RuleTests>, } #[derive(Clone)] pub struct LintDeclaration { pub name: String, pub docstring: Option<String>, pub config_fields: Vec<ConfigField>, } #[derive(Clone)] pub struct ConfigField { pub docstring: Option<String>, pub field: Field, } impl Parse for LintDeclaration { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(input); input.parse::<Ident>()?; input.parse::<Token!(,)>()?; input.parse::<Ident>()?; input.parse::<Token!(,)>()?; let name = input.parse::<LitStr>()?.value(); let _ = input.parse::<Token!(,)>(); let config_fields = Punctuated::<ConfigField, Token![,]>::parse_terminated(input)? .into_iter() .filter(|field| matches!(field.field.vis, Visibility::Public(_))) .collect(); Ok(Self { name, docstring, config_fields, }) } } impl Parse for ConfigField { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(input); let field = input.call(Field::parse_named)?; Ok(Self { docstring, field }) } } fn parse_docstring(input: ParseStream) -> Option<String> { let mut res = String::new(); while input.peek(Token!(#)) { if let Ok(attr) = input.call(Attribute::parse_outer) { for attribute in attr { if attribute .path .get_ident() .map_or(false, |ident| ident == "doc") { let tokens = attribute.tokens.clone().into_iter().skip(1).collect(); let string = parse2::<LitStr>(tokens).expect("Invalid docstring").value(); res.push_str(&string); res.push('\n'); } } } } if res.is_empty() { None } else { Some(unindent(&res)) } } mod kw { syn::custom_keyword!(err); syn::custom_keyword!(ok); } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RuleTests { pub ok_examples: Vec<Example>, pub err_examples: Vec<Example>, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Example { pub source: String, pub docstring: Option<String>, } impl Parse for RuleTests { fn parse(input: ParseStream) -> Result<Self> { input.parse::<Expr>()?; input.parse::<Token!(,)>()?; input.parse::<kw::err>()?; input.parse::<Token!(:)>()?; let content; braced!(content in input); let mut err_examples: Vec<Example> = Punctuated::<Example, Token![,]>::parse_terminated(&content)? .into_iter() .collect(); err_examples = err_examples .into_iter() .filter(|elem| elem.docstring.as_ref().map(|x| x.trim()) != Some("ignore")) .collect(); err_examples.truncate(30); input.parse::<Token!(,)>()?; input.parse::<kw::ok>()?; input.parse::<Token!(:)>()?; let content; braced!(content in input); let mut ok_examples: Vec<Example> = Punctuated::<Example, Token![,]>::parse_terminated(&content)? .into_iter() .collect(); ok_examples = ok_examples .into_iter() .filter(|elem| elem.docstring.as_ref().map(|x| x.trim()) != Some("ignore")) .collect(); ok_examples.truncate(30); let _ = input.parse::<Token!(,)>(); Ok(Self { ok_examples, err_examples, }) } } impl Parse for Example { fn parse(input: ParseStream) -> Result<Self> { let docstring = parse_docstring(&input); let string = input.parse::<LitStr>()?.value(); let source = unindent(&string).trim().to_string(); Ok(Example { docstring, source }) } }
call.tokens); declaration = Some(res?); } else if call .path .segments .last() .map_or(false, |x| x.ident == "rule_tests") && tests.is_none() { tests = Some(parse2::<RuleTests>(call.tokens)?); } } } if let Some(decl) = declaration { Ok(Some(RuleFile { lint_declaration: decl, tests, })) } else { Ok(None) } } #[derive(Clone)] pub struct RuleFile { pub lint_declaration: LintDeclaration, pub t
random
[]
Rust
cio/src/certs.rs
borisfaure/cio
b6eeb20b5b4bc8c3f3b7a3f6b679348c1a939481
use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::thread; use std::time; use acme_lib::create_p384_key; use acme_lib::persist::FilePersist; use acme_lib::{Directory, DirectoryUrl}; use async_trait::async_trait; use chrono::NaiveDate; use chrono::{DateTime, TimeZone, Utc}; use cloudflare::endpoints::{dns, zone}; use cloudflare::framework::{ async_api::{ApiClient, Client}, auth::Credentials, Environment, HttpApiClientConfig, }; use hubcaps::Github; use macros::db_struct; use openssl::x509::X509; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use tracing::instrument; use crate::airtable::{AIRTABLE_BASE_ID_MISC, AIRTABLE_CERTIFICATES_TABLE}; use crate::core::UpdateAirtableRecord; use crate::schema::certificates; use crate::utils::github_org; #[instrument] #[inline] pub async fn create_ssl_certificate(domain: &str) -> NewCertificate { let email = env::var("CLOUDFLARE_EMAIL").unwrap(); let cf_creds = Credentials::UserAuthKey { email: env::var("CLOUDFLARE_EMAIL").unwrap(), key: env::var("CLOUDFLARE_TOKEN").unwrap(), }; let api_client = Client::new(cf_creds, HttpApiClientConfig::default(), Environment::Production).unwrap(); let persist = FilePersist::new(env::temp_dir()); let dir = Directory::from_url(persist, DirectoryUrl::LetsEncrypt).unwrap(); let acc = dir.account(&email).unwrap(); let mut ord_new = acc.new_order(domain, &[]).unwrap(); let ord_csr = loop { if let Some(ord_csr) = ord_new.confirm_validations() { break ord_csr; } let auths = ord_new.authorizations().unwrap(); let challenge = auths[0].dns_challenge(); let domain_parts: Vec<&str> = domain.split('.').collect(); let root_domain = format!("{}.{}", domain_parts[domain_parts.len() - 2], domain_parts[domain_parts.len() - 1]); let zones = api_client .request(&zone::ListZones { params: zone::ListZonesParams { name: Some(root_domain.to_string()), ..Default::default() }, }) .await .unwrap() .result; let zone_identifier = &zones[0].id; let record_name = format!("_acme-challenge.{}", domain.replace("*.", "")); let dns_records = api_client .request(&dns::ListDnsRecords { zone_identifier: &zone_identifier, params: dns::ListDnsRecordsParams { name: Some(record_name.to_string()), ..Default::default() }, }) .await .unwrap() .result; if dns_records.is_empty() { let dns_record = api_client .request(&dns::CreateDnsRecord { zone_identifier: &zone_identifier, params: dns::CreateDnsRecordParams { name: &record_name, content: dns::DnsContent::TXT { content: challenge.dns_proof() }, ttl: None, proxied: None, priority: None, }, }) .await .unwrap() .result; println!("[certs] created dns record: {:?}", dns_record); } else { let dns_record = api_client .request(&dns::UpdateDnsRecord { zone_identifier: &zone_identifier, identifier: &dns_records[0].id, params: dns::UpdateDnsRecordParams { name: &record_name, content: dns::DnsContent::TXT { content: challenge.dns_proof() }, ttl: None, proxied: None, }, }) .await .unwrap() .result; println!("[certs] updated dns record: {:?}", dns_record); } println!("validating the proof..."); let dur = time::Duration::from_secs(10); thread::sleep(dur); challenge.validate(5000).unwrap(); ord_new.refresh().unwrap(); }; let pkey_pri = create_p384_key(); let ord_cert = ord_csr.finalize_pkey(pkey_pri, 5000).unwrap(); let cert = ord_cert.download_and_save_cert().unwrap(); NewCertificate { private_key: cert.private_key().to_string(), certificate: cert.certificate().to_string(), domain: domain.to_string(), valid_days_left: cert.valid_days_left() as i32, expiration_date: crate::utils::default_date(), } } #[db_struct { new_name = "Certificate", base_id = "AIRTABLE_BASE_ID_MISC", table = "AIRTABLE_CERTIFICATES_TABLE", }] #[derive(Debug, Insertable, AsChangeset, PartialEq, Clone, JsonSchema, Deserialize, Serialize)] #[table_name = "certificates"] pub struct NewCertificate { pub domain: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub certificate: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub private_key: String, #[serde(default)] pub valid_days_left: i32, #[serde(default = "crate::utils::default_date", serialize_with = "crate::configs::null_date_format::serialize")] pub expiration_date: NaiveDate, } impl NewCertificate { #[instrument] #[inline] pub async fn populate(&mut self) { *self = create_ssl_certificate(&self.domain).await; } #[instrument] #[inline] pub async fn populate_from_github(&mut self, github: &Github) { let repo = github.repo(github_org(), "configs"); let r = repo.get().await.unwrap(); let cert = repo .content() .file(&format!("nginx/ssl/{}/fullchain.pem", self.domain.replace("*.", "wildcard.")), &r.default_branch) .await .unwrap(); let priv_key = repo .content() .file(&format!("nginx/ssl/{}/privkey.pem", self.domain.replace("*.", "wildcard.")), &r.default_branch) .await .unwrap(); self.certificate = from_utf8(&cert.content).unwrap().to_string(); self.private_key = from_utf8(&priv_key.content).unwrap().to_string(); let exp_date = self.expiration_date(); self.expiration_date = exp_date.date().naive_utc(); self.valid_days_left = self.valid_days_left(); } #[instrument] #[inline] pub fn populate_from_disk(&mut self, dir: &str) { let path = self.get_path(dir); self.certificate = fs::read_to_string(path.join("fullchain.pem")).unwrap_or_default(); self.private_key = fs::read_to_string(path.join("privkey.pem")).unwrap_or_default(); if !self.certificate.is_empty() { let exp_date = self.expiration_date(); self.expiration_date = exp_date.date().naive_utc(); self.valid_days_left = self.valid_days_left(); } } #[instrument] #[inline] fn get_path(&self, dir: &str) -> PathBuf { Path::new(dir).join(self.domain.replace("*.", "wildcard.")) } #[instrument] #[inline] pub fn save_to_directory(&self, dir: &str) { let path = self.get_path(dir); fs::create_dir_all(path.clone()).unwrap(); fs::write(path.join("fullchain.pem"), self.certificate.as_bytes()).unwrap(); fs::write(path.join("privkey.pem"), self.private_key.as_bytes()).unwrap(); } #[instrument] #[inline] pub fn valid_days_left(&self) -> i32 { let expires = self.expiration_date(); let dur = expires - Utc::now(); dur.num_days() as i32 } #[instrument] #[inline] pub fn expiration_date(&self) -> DateTime<Utc> { let x509 = X509::from_pem(self.certificate.as_bytes()).expect("from_pem"); let not_after = format!("{}", x509.not_after()); Utc.datetime_from_str(&not_after, "%h %e %H:%M:%S %Y %Z").expect("strptime") } } #[async_trait] impl UpdateAirtableRecord<Certificate> for Certificate { async fn update_airtable_record(&mut self, _record: Certificate) {} }
use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::str::from_utf8; use std::thread; use std::time; use acme_lib::create_p384_key; use acme_lib::persist::FilePersist; use acme_lib::{Directory, DirectoryUrl}; use async_trait::async_trait; use chrono::NaiveDate; use chrono::{DateTime, TimeZone, Utc}; use cloudflare::endpoints::{dns, zone}; use cloudflare::framework::{ async_api::{ApiClient, Client}, auth::Credentials, Environment, HttpApiClientConfig, }; use hubcaps::Github; use macros::db_struct; use openssl::x509::X509; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use tracing::instrument; use crate::airtable::{AIRTABLE_BASE_ID_MISC, AIRTABLE_CERTIFICATES_TABLE}; use crate::core::UpdateAirtableRecord; use crate::schema::certificates; use crate::utils::github_org; #[instrument] #[inline] pub async fn create_ssl_certificate(domain: &str) -> NewCertificate { let email = env::var("CLOUDFLARE_EMAIL").unwrap(); let cf_creds = Credentials::UserAuthKey { email: env::var("CLOUDFLARE_EMAIL").unwrap(), key: env::var("CLOUDFLARE_TOKEN").unwrap(), }; let api_client = Client::new(cf_creds, HttpApiClientConfig::default(), Environment::Production).unwrap(); let persist = FilePersist::new(env::temp_dir()); let dir = Directory::from_url(persist, DirectoryUrl::LetsEncrypt).unwrap(); let acc = dir.account(&email).unwrap(); let mut ord_new = acc.new_order(domain, &[]).unwrap(); let ord_csr = loop { if let Some(ord_csr) = ord_new.confirm_validations() { break ord_csr; } let auths = ord_new.authorizations().unwrap(); let challenge = auths[0].dns_challenge(); let domain_parts: Vec<&str> = domain.split('.').collect(); let root_domain = format!("{}.{}", domain_parts[domain_parts.len() - 2], domain_parts[domain_parts.len() - 1]); let zones = api_client .request(&zone::ListZones { params: zone::ListZonesParams { name: Some(root_domain.to_string()), ..Default::default() }, }) .await .unwrap() .result; let zone_identifier = &zones[0].id; let record_name = format!("_acme-challenge.{}", domain.replace("*.", "")); let dns_records = api_client .request(&dns::ListDnsRecords { zone_identifier: &zone_identifier, params: dns::ListDnsRecordsParams { name: Some(record_name.to_string()), ..Default::default() }, }) .await .unwrap() .result; if dns_records.is_empty() { let dns_record = api_client .request(&dns::CreateDnsRecord { zone_identifier: &zone_identifier, params: dns::CreateDnsRecordParams { name: &record_name, content: dns::DnsContent::TXT { content: challenge.dns_proof() }, ttl: None, proxied: None, priority: None, }, }) .await .unwrap() .result; println!("[certs] created dns record: {:?}", dns_record); } else { let dns_record = api_client .request(&dns::UpdateDnsRecord { zone_identifier: &zone_identifier, identifier: &dns_records[0].id, params: dns::UpdateDnsRecordParams { name: &record_name, content: dns::DnsContent::TXT { content: challenge.dns_proof() }, ttl: None, proxied: None, }, }) .await .unwrap() .result; println!("[certs] updated dns record: {:?}", dns_record); } println!("validating the proof..."); let dur = time::Duration::from_secs(10); thread::sleep(dur); challenge.validate(5000).unwrap(); ord_new.refresh().unwrap(); }; let pkey_pri = create_p384_key(); let ord_cert = ord_csr.finalize_pkey(pkey_pri, 5000).unwrap(); let cert = ord_cert.download_and_save_cert().unwrap(); NewCertificate { private_key: cert.private_key().to_string(), certificate: cert.certificate().to_string(), domain: domain.to_string(), valid_days_left: cert.valid_days_left() as i32, expiration_date: crate::utils::default_date(), } } #[db_struct { new_name = "Certificate", base_id = "AIRTABLE_BASE_ID_MISC", table = "AIRTABLE_CERTIFICATES_TABLE", }] #[derive(Debug, Insertable, AsChangeset, PartialEq, Clone, JsonSchema, Deserialize, Serialize)] #[table_name = "certificates"] pub struct NewCertificate { pub domain: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub certificate: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub private_key: String, #[serde(default)] pub valid_days_left: i32, #[serde(default = "crate::utils::default_date", serialize_with = "crate::configs::null_date_format::serialize")] pub expiration_date: NaiveDate, } impl NewCertificate { #[instrument] #[inline] pub async fn populate(&mut self) { *self = create_ssl_certificate(&self.domain).await; } #[instrument] #[inline] pub async fn populate_from_github(&mut self, github: &Github) { let repo = github.repo(github_org(), "configs"); let r = repo.get().await.unwrap(); let cert = repo .content() .file(&format!("nginx/ssl/{}/fullchain.pem", self.domain.replace("*.", "wildcard.")), &r.default_branch) .await .unwrap(); let priv_key = repo .content() .file(&format!("nginx/ssl/{}/privkey.pem", self.domain.replace("*.", "wildcard.")), &r.default_branch) .await .unwrap(); self.certificate = from_utf8(&cert.content).unwrap().to_string(); self.private_key = from_utf8(&priv_key.content).unwrap().to_string(); let exp_date = self.expiration_date(); self.expiration_date = exp_date.date().naive_utc(); self.valid_days_left = self.valid_days_left(); } #[instrument] #[inline] pub fn populate_from_disk(&mut self, dir: &str) { let path = self.get_path(dir); self.certificate = fs::read_to_string(path.join("fullchain.pem")).unwrap_or_default(); self.private_key = fs::read_to_string(path.join("privkey.pem")).unwrap_or_default(); if !self.certificate.is_empty() {
#[instrument] #[inline] fn get_path(&self, dir: &str) -> PathBuf { Path::new(dir).join(self.domain.replace("*.", "wildcard.")) } #[instrument] #[inline] pub fn save_to_directory(&self, dir: &str) { let path = self.get_path(dir); fs::create_dir_all(path.clone()).unwrap(); fs::write(path.join("fullchain.pem"), self.certificate.as_bytes()).unwrap(); fs::write(path.join("privkey.pem"), self.private_key.as_bytes()).unwrap(); } #[instrument] #[inline] pub fn valid_days_left(&self) -> i32 { let expires = self.expiration_date(); let dur = expires - Utc::now(); dur.num_days() as i32 } #[instrument] #[inline] pub fn expiration_date(&self) -> DateTime<Utc> { let x509 = X509::from_pem(self.certificate.as_bytes()).expect("from_pem"); let not_after = format!("{}", x509.not_after()); Utc.datetime_from_str(&not_after, "%h %e %H:%M:%S %Y %Z").expect("strptime") } } #[async_trait] impl UpdateAirtableRecord<Certificate> for Certificate { async fn update_airtable_record(&mut self, _record: Certificate) {} }
let exp_date = self.expiration_date(); self.expiration_date = exp_date.date().naive_utc(); self.valid_days_left = self.valid_days_left(); } }
function_block-function_prefix_line
[]
Rust
capsules/src/ninedof.rs
x37v/tock
683d545b408864d58c6e84ae0536ac416dafa6d3
use core::cell::Cell; use kernel::{AppId, Callback, Container, Driver}; use kernel::ReturnCode; use kernel::hil; use kernel::process::Error; #[derive(Clone,Copy,PartialEq)] pub enum NineDofCommand { Exists, ReadAccelerometer, ReadMagnetometer, ReadGyroscope, } pub struct App { callback: Option<Callback>, pending_command: bool, command: NineDofCommand, arg1: usize, } impl Default for App { fn default() -> App { App { callback: None, pending_command: false, command: NineDofCommand::Exists, arg1: 0, } } } pub struct NineDof<'a> { driver: &'a hil::sensors::NineDof, apps: Container<App>, current_app: Cell<Option<AppId>>, } impl<'a> NineDof<'a> { pub fn new(driver: &'a hil::sensors::NineDof, container: Container<App>) -> NineDof<'a> { NineDof { driver: driver, apps: container, current_app: Cell::new(None), } } fn enqueue_command(&self, command: NineDofCommand, arg1: usize, appid: AppId) -> ReturnCode { self.apps .enter(appid, |app, _| if self.current_app.get().is_none() { self.current_app.set(Some(appid)); self.call_driver(command, arg1) } else { if app.pending_command == true { ReturnCode::ENOMEM } else { app.pending_command = true; app.command = command; app.arg1 = arg1; ReturnCode::SUCCESS } }) .unwrap_or_else(|err| match err { Error::OutOfMemory => ReturnCode::ENOMEM, Error::AddressOutOfBounds => ReturnCode::EINVAL, Error::NoSuchApp => ReturnCode::EINVAL, }) } fn call_driver(&self, command: NineDofCommand, _: usize) -> ReturnCode { match command { NineDofCommand::ReadAccelerometer => self.driver.read_accelerometer(), NineDofCommand::ReadMagnetometer => self.driver.read_magnetometer(), NineDofCommand::ReadGyroscope => self.driver.read_gyroscope(), _ => ReturnCode::ENOSUPPORT, } } } impl<'a> hil::sensors::NineDofClient for NineDof<'a> { fn callback(&self, arg1: usize, arg2: usize, arg3: usize) { let mut finished_command = NineDofCommand::Exists; let mut finished_command_arg = 0; self.current_app.get().map(|appid| { self.current_app.set(None); let _ = self.apps.enter(appid, |app, _| { app.pending_command = false; finished_command = app.command; finished_command_arg = app.arg1; app.callback.map(|mut cb| { cb.schedule(arg1, arg2, arg3); }); }); }); for cntr in self.apps.iter() { let started_command = cntr.enter(|app, _| { if app.pending_command && app.command == finished_command && app.arg1 == finished_command_arg { app.pending_command = false; app.callback.map(|mut cb| { cb.schedule(arg1, arg2, arg3); }); false } else if app.pending_command { app.pending_command = false; self.current_app.set(Some(app.appid())); self.call_driver(app.command, app.arg1) == ReturnCode::SUCCESS } else { false } }); if started_command { break; } } } } impl<'a> Driver for NineDof<'a> { fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode { match subscribe_num { 0 => { self.apps .enter(callback.app_id(), |app, _| { app.callback = Some(callback); ReturnCode::SUCCESS }) .unwrap_or_else(|err| match err { Error::OutOfMemory => ReturnCode::ENOMEM, Error::AddressOutOfBounds => ReturnCode::EINVAL, Error::NoSuchApp => ReturnCode::EINVAL, }) } _ => ReturnCode::ENOSUPPORT, } } fn command(&self, command_num: usize, arg1: usize, appid: AppId) -> ReturnCode { match command_num { 0 => /* This driver exists. */ ReturnCode::SUCCESS, 1 => self.enqueue_command(NineDofCommand::ReadAccelerometer, arg1, appid), 100 => self.enqueue_command(NineDofCommand::ReadMagnetometer, arg1, appid), 200 => self.enqueue_command(NineDofCommand::ReadGyroscope, arg1, appid), _ => ReturnCode::ENOSUPPORT, } } }
use core::cell::Cell; use kernel::{AppId, Callback, Container, Driver}; use kernel::ReturnCode; use kernel::hil; use kernel::process::Error; #[derive(Clone,Copy,PartialEq)] pub enum NineDofCommand { Exists, ReadAccelerometer, ReadMagnetometer, ReadGyroscope, } pub struct App { callback: Option<Callback>, pending_command: bool, command: NineDofCommand, arg1: usize, } impl Default for App { fn default() -> App { App { callback: None, pending_command: false, command: NineDofCommand::Exists, arg1: 0, } } } pub struct NineDof<'a> { driver: &'a hil::sensors::NineDof, apps: Container<App>, current_app: Cell<Option<AppId>>, } impl<'a> NineDof<'a> { pub fn new(driver: &'a hil::sensors::NineDof, container: Container<App>) -> NineDof<'a> { NineDof { driver: driver, apps: container, current_app: Cell::new(None), } } fn enqueue_command(&self, command: NineDofCommand, arg1: usize, appid: AppId) -> ReturnCode { self.apps .enter(appid, |app, _| if self.current_app.get().is_none() { self.current_app.set(Some(appid)); self.call_driver(command, arg1) } else { if app.pending_command == true { ReturnCode::ENOMEM } else { app.pending_command = true; app.command = command; app.arg1 = arg1; ReturnCode::SUCCESS } }) .unwrap_or_else(|err| match err { Error::OutOfMemory => ReturnCode::ENOMEM, Error::AddressOutOfBounds => ReturnCode::EINVAL, Error::NoSuchApp => ReturnCode::EINVAL, }) } fn call_driver(&self, command: NineDofCommand, _:
ReturnCode::SUCCESS, 1 => self.enqueue_command(NineDofCommand::ReadAccelerometer, arg1, appid), 100 => self.enqueue_command(NineDofCommand::ReadMagnetometer, arg1, appid), 200 => self.enqueue_command(NineDofCommand::ReadGyroscope, arg1, appid), _ => ReturnCode::ENOSUPPORT, } } }
usize) -> ReturnCode { match command { NineDofCommand::ReadAccelerometer => self.driver.read_accelerometer(), NineDofCommand::ReadMagnetometer => self.driver.read_magnetometer(), NineDofCommand::ReadGyroscope => self.driver.read_gyroscope(), _ => ReturnCode::ENOSUPPORT, } } } impl<'a> hil::sensors::NineDofClient for NineDof<'a> { fn callback(&self, arg1: usize, arg2: usize, arg3: usize) { let mut finished_command = NineDofCommand::Exists; let mut finished_command_arg = 0; self.current_app.get().map(|appid| { self.current_app.set(None); let _ = self.apps.enter(appid, |app, _| { app.pending_command = false; finished_command = app.command; finished_command_arg = app.arg1; app.callback.map(|mut cb| { cb.schedule(arg1, arg2, arg3); }); }); }); for cntr in self.apps.iter() { let started_command = cntr.enter(|app, _| { if app.pending_command && app.command == finished_command && app.arg1 == finished_command_arg { app.pending_command = false; app.callback.map(|mut cb| { cb.schedule(arg1, arg2, arg3); }); false } else if app.pending_command { app.pending_command = false; self.current_app.set(Some(app.appid())); self.call_driver(app.command, app.arg1) == ReturnCode::SUCCESS } else { false } }); if started_command { break; } } } } impl<'a> Driver for NineDof<'a> { fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode { match subscribe_num { 0 => { self.apps .enter(callback.app_id(), |app, _| { app.callback = Some(callback); ReturnCode::SUCCESS }) .unwrap_or_else(|err| match err { Error::OutOfMemory => ReturnCode::ENOMEM, Error::AddressOutOfBounds => ReturnCode::EINVAL, Error::NoSuchApp => ReturnCode::EINVAL, }) } _ => ReturnCode::ENOSUPPORT, } } fn command(&self, command_num: usize, arg1: usize, appid: AppId) -> ReturnCode { match command_num { 0 => /* This driver exists. */
random
[ { "content": "pub fn schedule(callback: FunctionCall, appid: AppId) -> bool {\n\n let procs = unsafe { &mut PROCS };\n\n let idx = appid.idx();\n\n if idx >= procs.len() {\n\n return false;\n\n }\n\n\n\n match procs[idx] {\n\n None => false,\n\n Some(ref mut p) => {\n\n ...
Rust
src/domain/runtime/type/remote_object/mod.rs
cloudflare/chrome-devtools-rs
d8fdf820d5337df1586fa0ff89b2bf420172522f
use std::fmt; pub mod r#type; use r#type::object::{ObjectPreview, Subtype}; use r#type::Type; use serde::{Deserialize, Serialize}; use unescape::unescape; use console::style; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct RemoteObject { pub r#type: Type, pub subtype: Option<Subtype>, pub description: Option<String>, pub class_name: Option<String>, pub value: Option<serde_json::Value>, pub preview: Option<ObjectPreview>, } impl RemoteObject { fn parse_error(&self) -> String { let e = if let Some(subtype) = &self.subtype { format!("{}", subtype) } else { format!("{}", &self.r#type) }; format!("{{unknown {}}}", e) } fn display_description(&self) -> String { if let Some(description) = &self.description { description.to_string() } else { self.parse_error() } } fn display_value(&self) -> String { if let Some(value) = &self.value { value.to_string() } else { self.parse_error() } } fn display_object(&self) -> String { if let Some(preview) = &self.preview { preview.to_string() } else if let Some(subtype) = &self.subtype { if subtype.to_string() == "null" { let mut null = "null".to_string(); if cfg!(feature = "color") { null = format!("{}", style(null).bold()); } null } else { self.parse_error() } } else { self.parse_error() } } } impl fmt::Display for RemoteObject { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let formatted = match &self.r#type { Type::Undefined => { let mut disp = "undefined".to_string(); if cfg!(feature = "color") { disp = format!("{}", style(disp).dim()) } disp } Type::Boolean => { let mut disp = self.display_value(); if cfg!(feature = "color") { disp = format!("{}", style(disp).yellow()); } disp } Type::String => { if let Some(value) = &self.value { let value = value.to_string(); let end = value.len() - 1; if let Some(s) = unescape(&value[1..end]) { s } else { self.parse_error() } } else { self.parse_error() } } Type::Object => self.display_object(), Type::BigInt | Type::Number | Type::Symbol => { let mut disp = self.display_description(); if cfg!(feature = "color") { disp = format!("{}", style(disp).yellow()); } disp } Type::Function => { let mut disp = self.display_description(); if cfg!(feature = "color") { disp = format!("{}", style(disp).cyan()); } disp } Type::Accessor => self.display_object(), }; write!(f, "{}", formatted) } }
use std::fmt; pub mod r#type; use r#type::object::{ObjectPreview, Subtype}; use r#type::Type; use serde::{Deserialize, Serialize}; use unescape::unescape; use console::style; #[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct RemoteObject { pub r#type: Type, pub subtype: Option<Subtype>, pub description: Option<String>, pub class_name: Option<String>, pub value: Option<serde_json::Value>, pub preview: Option<ObjectPreview>, } impl RemoteObject { fn parse_error(&self) -> String { let e = if let Some(subtype) = &self.subtype { format!("{}", subtype) } else { format!("{}", &self.r#type) }; format!("{{unknown {}}}", e) } fn display_description(&self) -> String { if let Some(description) = &self.description { description.to_string() } else { self.parse_error() } } fn display_value(&self) -> String { if let Some(value) = &self.value { value.to_string() } else { self.parse_error() } }
} impl fmt::Display for RemoteObject { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let formatted = match &self.r#type { Type::Undefined => { let mut disp = "undefined".to_string(); if cfg!(feature = "color") { disp = format!("{}", style(disp).dim()) } disp } Type::Boolean => { let mut disp = self.display_value(); if cfg!(feature = "color") { disp = format!("{}", style(disp).yellow()); } disp } Type::String => { if let Some(value) = &self.value { let value = value.to_string(); let end = value.len() - 1; if let Some(s) = unescape(&value[1..end]) { s } else { self.parse_error() } } else { self.parse_error() } } Type::Object => self.display_object(), Type::BigInt | Type::Number | Type::Symbol => { let mut disp = self.display_description(); if cfg!(feature = "color") { disp = format!("{}", style(disp).yellow()); } disp } Type::Function => { let mut disp = self.display_description(); if cfg!(feature = "color") { disp = format!("{}", style(disp).cyan()); } disp } Type::Accessor => self.display_object(), }; write!(f, "{}", formatted) } }
fn display_object(&self) -> String { if let Some(preview) = &self.preview { preview.to_string() } else if let Some(subtype) = &self.subtype { if subtype.to_string() == "null" { let mut null = "null".to_string(); if cfg!(feature = "color") { null = format!("{}", style(null).bold()); } null } else { self.parse_error() } } else { self.parse_error() } }
function_block-full_function
[ { "content": "use std::fmt;\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// Object subtype hint. Specified for the `object` [Type][crate::domain::runtime::type::remote_object::type::Type] values only\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\n#[serde(rename_all = \"lowercase\")]\n\npub enum Su...
Rust
vendor/unicode-segmentation/src/sentence.rs
yilinhan/crates-io
eb259811db1316ec63d9dd01cda3d87e3b860ca0
use core::cmp; use core::iter::Filter; mod fwd { use tables::sentence::SentenceCat; use core::cmp; #[derive(Clone, Copy, PartialEq, Eq)] enum StatePart { Sot, Eot, Other, CR, LF, Sep, ATerm, UpperLower, ClosePlus, SpPlus, STerm } #[derive(Clone, PartialEq, Eq)] struct SentenceBreaksState(pub [StatePart; 4]); const INITIAL_STATE: SentenceBreaksState = SentenceBreaksState([ StatePart::Sot, StatePart::Sot, StatePart::Sot, StatePart::Sot ]); #[derive(Clone)] pub struct SentenceBreaks<'a> { pub string: &'a str, pos: usize, state: SentenceBreaksState } impl SentenceBreaksState { fn next(&self, cat: SentenceCat) -> SentenceBreaksState { let &SentenceBreaksState(parts) = self; let parts = match (parts[3], cat) { (StatePart::ClosePlus, SentenceCat::SC_Close) => parts, (StatePart::SpPlus, SentenceCat::SC_Sp) => parts, _ => [ parts[1], parts[2], parts[3], match cat { SentenceCat::SC_CR => StatePart::CR, SentenceCat::SC_LF => StatePart::LF, SentenceCat::SC_Sep => StatePart::Sep, SentenceCat::SC_ATerm => StatePart::ATerm, SentenceCat::SC_Upper | SentenceCat::SC_Lower => StatePart::UpperLower, SentenceCat::SC_Close => StatePart::ClosePlus, SentenceCat::SC_Sp => StatePart::SpPlus, SentenceCat::SC_STerm => StatePart::STerm, _ => StatePart::Other } ] }; SentenceBreaksState(parts) } fn end(&self) -> SentenceBreaksState { let &SentenceBreaksState(parts) = self; SentenceBreaksState([ parts[1], parts[2], parts[3], StatePart::Eot ]) } fn match1(&self, part: StatePart) -> bool { let &SentenceBreaksState(parts) = self; part == parts[3] } fn match2(&self, part1: StatePart, part2: StatePart) -> bool { let &SentenceBreaksState(parts) = self; part1 == parts[2] && part2 == parts[3] } } fn match_sb8(state: &SentenceBreaksState, ahead: &str) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = if parts[3] == StatePart::SpPlus { 2 } else { 3 }; if parts[idx] == StatePart::ClosePlus { idx -= 1 } if parts[idx] == StatePart::ATerm { use tables::sentence as se; for next_char in ahead.chars() { match se::sentence_category(next_char) { se::SC_Lower => return true, se::SC_OLetter | se::SC_Upper | se::SC_Sep | se::SC_CR | se::SC_LF | se::SC_STerm | se::SC_ATerm => return false, _ => continue } } } false } fn match_sb8a(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = if parts[3] == StatePart::SpPlus { 2 } else { 3 }; if parts[idx] == StatePart::ClosePlus { idx -= 1 } parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } fn match_sb9(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let idx = if parts[3] == StatePart::ClosePlus { 2 } else { 3 }; parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } fn match_sb11(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = match parts[3] { StatePart::Sep | StatePart::CR | StatePart::LF => 2, _ => 3 }; if parts[idx] == StatePart::SpPlus { idx -= 1 } if parts[idx] == StatePart::ClosePlus { idx -= 1} parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } impl<'a> Iterator for SentenceBreaks<'a> { type Item = usize; #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let slen = self.string.len(); (cmp::min(slen, 2), Some(slen + 1)) } #[inline] fn next(&mut self) -> Option<usize> { use tables::sentence as se; for next_char in self.string[self.pos..].chars() { let position_before = self.pos; let state_before = self.state.clone(); let next_cat = se::sentence_category(next_char); self.pos += next_char.len_utf8(); self.state = self.state.next(next_cat); match next_cat { _ if state_before.match1(StatePart::Sot) => return Some(position_before), SentenceCat::SC_LF if state_before.match1(StatePart::CR) => continue, _ if state_before.match1(StatePart::Sep) || state_before.match1(StatePart::CR) || state_before.match1(StatePart::LF) => return Some(position_before), SentenceCat::SC_Extend | SentenceCat::SC_Format => self.state = state_before, SentenceCat::SC_Numeric if state_before.match1(StatePart::ATerm) => continue, SentenceCat::SC_Upper if state_before.match2(StatePart::UpperLower, StatePart::ATerm) => continue, _ if match_sb8(&state_before, &self.string[position_before..]) => continue, SentenceCat::SC_SContinue | SentenceCat::SC_STerm | SentenceCat::SC_ATerm if match_sb8a(&state_before) => continue, SentenceCat::SC_Close | SentenceCat::SC_Sp | SentenceCat::SC_Sep | SentenceCat::SC_CR | SentenceCat::SC_LF if match_sb9(&state_before) => continue, SentenceCat::SC_Sp | SentenceCat::SC_Sep | SentenceCat::SC_CR | SentenceCat::SC_LF if match_sb8a(&state_before) => continue, _ if match_sb11(&state_before) => return Some(position_before), _ => continue } } if self.state.match1(StatePart::Sot) { None } else if self.state.match1(StatePart::Eot) { None } else { self.state = self.state.end(); Some(self.pos) } } } pub fn new_sentence_breaks<'a>(source: &'a str) -> SentenceBreaks<'a> { SentenceBreaks { string: source, pos: 0, state: INITIAL_STATE } } } #[derive(Clone)] pub struct UnicodeSentences<'a> { inner: Filter<USentenceBounds<'a>, fn(&&str) -> bool>, } #[derive(Clone)] pub struct USentenceBounds<'a> { iter: fwd::SentenceBreaks<'a>, sentence_start: Option<usize> } #[derive(Clone)] pub struct USentenceBoundIndices<'a> { start_offset: usize, iter: USentenceBounds<'a>, } #[inline] pub fn new_sentence_bounds<'a>(source: &'a str) -> USentenceBounds<'a> { USentenceBounds { iter: fwd::new_sentence_breaks(source), sentence_start: None } } #[inline] pub fn new_sentence_bound_indices<'a>(source: &'a str) -> USentenceBoundIndices<'a> { USentenceBoundIndices { start_offset: source.as_ptr() as usize, iter: new_sentence_bounds(source) } } #[inline] pub fn new_unicode_sentences<'b>(s: &'b str) -> UnicodeSentences<'b> { use super::UnicodeSegmentation; use tables::util::is_alphanumeric; fn has_alphanumeric(s: &&str) -> bool { s.chars().any(|c| is_alphanumeric(c)) } let has_alphanumeric: fn(&&str) -> bool = has_alphanumeric; UnicodeSentences { inner: s.split_sentence_bounds().filter(has_alphanumeric) } } impl<'a> Iterator for UnicodeSentences<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { self.inner.next() } } impl<'a> Iterator for USentenceBounds<'a> { type Item = &'a str; #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (lower, upper) = self.iter.size_hint(); (cmp::max(0, lower - 1), upper.map(|u| cmp::max(0, u - 1))) } #[inline] fn next(&mut self) -> Option<&'a str> { if self.sentence_start == None { if let Some(start_pos) = self.iter.next() { self.sentence_start = Some(start_pos) } else { return None } } if let Some(break_pos) = self.iter.next() { let start_pos = self.sentence_start.unwrap(); let sentence = &self.iter.string[start_pos..break_pos]; self.sentence_start = Some(break_pos); Some(sentence) } else { None } } } impl<'a> Iterator for USentenceBoundIndices<'a> { type Item = (usize, &'a str); #[inline] fn next(&mut self) -> Option<(usize, &'a str)> { self.iter.next().map(|s| (s.as_ptr() as usize - self.start_offset, s)) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } }
use core::cmp; use core::iter::Filter; mod fwd { use tables::sentence::SentenceCat; use core::cmp; #[derive(Clone, Copy, PartialEq, Eq)] enum StatePart { Sot, Eot, Other, CR, LF, Sep, ATerm, UpperLower, ClosePlus, SpPlus, STerm } #[derive(Clone, PartialEq, Eq)] struct SentenceBreaksState(pub [StatePart; 4]); const INITIAL_STATE: SentenceBreaksState = SentenceBreaksState([ StatePart::Sot, StatePart::Sot, StatePart::Sot, StatePart::Sot ]); #[derive(Clone)] pub struct SentenceBreaks<'a> { pub string: &'a str, pos: usize, state: SentenceBreaksState } impl SentenceBreaksState { fn next(&self, cat: SentenceCat) -> SentenceBreaksState { let &SentenceBreaksState(parts) = self; let parts = match (parts[3], cat) { (StatePart::ClosePlus, SentenceCat::SC_Close) => parts, (StatePart::SpPlus, SentenceCat::SC_Sp) => parts, _ => [ parts[1], parts[2], parts[3], match cat { SentenceCat::SC_CR => StatePart::CR, SentenceCat::SC_LF => StatePart::LF, SentenceCat::SC_Sep => StatePart::Sep, SentenceCat::SC_ATerm => StatePart::ATerm, SentenceCat::SC_Upper | SentenceCat::SC_Lower => StatePart::UpperLower, SentenceCat::SC_Close => StatePart::ClosePlus, SentenceCat::SC_Sp => StatePart::SpPlus, SentenceCat::SC_STerm => StatePart::STerm, _ => StatePart::Other } ] }; SentenceBreaksState(parts) } fn end(&self) -> SentenceBreaksState { let &SentenceBreaksState(parts) = self; SentenceBreaksState([ parts[1], parts[2], parts[3], StatePart::Eot ]) } fn match1(&self, part: StatePart) -> bool { let &SentenceBreaksState(parts) = self; part == parts[3] } fn match2(&self, part1: StatePart, part2: StatePart) -> bool { let &SentenceBreaksState(parts) = self; part1 == parts[2] && part2 == parts[3] } } fn match_sb8(state: &SentenceBreaksState, ahead: &str) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = if parts[3] == StatePart::SpPlus { 2 } else { 3 }; if parts[idx] == StatePart::ClosePlus { idx -= 1 } if parts[idx] == StatePart::ATerm { use tables::sentence as se; for next_char in ahead.chars() { match se::sentence_category(next_char) { se::SC_Lower => return true, se::SC_OLetter | se::SC_Upper | se::SC_Sep | se::SC_CR | se::SC_LF | se::SC_STerm | se::SC_ATerm => return false, _ => continue } } } false } fn match_sb8a(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = if parts[3] == StatePart::SpPlus { 2 } else { 3 }; if parts[idx] == StatePart::ClosePlus { idx -= 1 } parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } fn match_sb9(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let idx = if parts[3] == StatePart::ClosePlus { 2 } else { 3 }; parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } fn match_sb11(state: &SentenceBreaksState) -> bool { let &SentenceBreaksState(parts) = state; let mut idx = match parts[3] { StatePart::Sep | StatePart::CR | StatePart::LF => 2, _ => 3 }; if parts[idx] == StatePart::SpPlus { idx -= 1 } if parts[idx] == StatePart::ClosePlus { idx -= 1} parts[idx] == StatePart::STerm || parts[idx] == StatePart::ATerm } impl<'a> Iterator for SentenceBreaks<'a> { type Item = usize; #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let slen = self.string.len(); (cmp::min(slen, 2), Some(slen + 1)) } #[inline] fn next(&mut self) -> Option<usize> { use tables::sentence as se; for next_char in self.string[self.pos..].chars() { let position_before = self.pos; let state_before = self.state.clone(); let next_cat = se::sentence_category(next_char); self.pos += next_char.len_utf8(); self.state = self.state.next(next_cat); match next_cat { _ if state_before.match1(StatePart::Sot) => return Some(position_before), SentenceCat::SC_LF if state_before.match1(StatePart::CR) => continue, _ if state_before.match1(StatePart::Sep) || state_before.match1(StatePart::CR) || state_before.match1(StatePart::LF) => return Some(position_before), SentenceCat::SC_Extend | SentenceCat::SC_Format => self.state = state_before, SentenceCat::SC_Numeric if state_before.match1(StatePart::ATerm) => continue, SentenceCat::SC_Upper if state_before.match2(StatePart::UpperLower, StatePart::ATerm) => continue, _ if match_sb8(&state_before, &self.string[position_before..]) => continue, SentenceCat::SC_SContinue | SentenceCat::SC_STerm | SentenceCat::SC_ATerm if match_sb8a(&state_before) => continue, SentenceCat::SC_Close | SentenceCat::SC_Sp | SentenceCat::SC_Sep | SentenceCat::SC_CR | SentenceCat::SC_LF if match_sb9(&state_before) => continue, SentenceCat::SC_Sp | SentenceCat::SC_Sep | SentenceCat::SC_CR | SentenceCat::SC_LF if match_sb8a(&state_before) => continue, _ if match_sb11(&state_before) => return Some(position_before), _ => continue } } if self.state.
eaks<'a>(source: &'a str) -> SentenceBreaks<'a> { SentenceBreaks { string: source, pos: 0, state: INITIAL_STATE } } } #[derive(Clone)] pub struct UnicodeSentences<'a> { inner: Filter<USentenceBounds<'a>, fn(&&str) -> bool>, } #[derive(Clone)] pub struct USentenceBounds<'a> { iter: fwd::SentenceBreaks<'a>, sentence_start: Option<usize> } #[derive(Clone)] pub struct USentenceBoundIndices<'a> { start_offset: usize, iter: USentenceBounds<'a>, } #[inline] pub fn new_sentence_bounds<'a>(source: &'a str) -> USentenceBounds<'a> { USentenceBounds { iter: fwd::new_sentence_breaks(source), sentence_start: None } } #[inline] pub fn new_sentence_bound_indices<'a>(source: &'a str) -> USentenceBoundIndices<'a> { USentenceBoundIndices { start_offset: source.as_ptr() as usize, iter: new_sentence_bounds(source) } } #[inline] pub fn new_unicode_sentences<'b>(s: &'b str) -> UnicodeSentences<'b> { use super::UnicodeSegmentation; use tables::util::is_alphanumeric; fn has_alphanumeric(s: &&str) -> bool { s.chars().any(|c| is_alphanumeric(c)) } let has_alphanumeric: fn(&&str) -> bool = has_alphanumeric; UnicodeSentences { inner: s.split_sentence_bounds().filter(has_alphanumeric) } } impl<'a> Iterator for UnicodeSentences<'a> { type Item = &'a str; #[inline] fn next(&mut self) -> Option<&'a str> { self.inner.next() } } impl<'a> Iterator for USentenceBounds<'a> { type Item = &'a str; #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (lower, upper) = self.iter.size_hint(); (cmp::max(0, lower - 1), upper.map(|u| cmp::max(0, u - 1))) } #[inline] fn next(&mut self) -> Option<&'a str> { if self.sentence_start == None { if let Some(start_pos) = self.iter.next() { self.sentence_start = Some(start_pos) } else { return None } } if let Some(break_pos) = self.iter.next() { let start_pos = self.sentence_start.unwrap(); let sentence = &self.iter.string[start_pos..break_pos]; self.sentence_start = Some(break_pos); Some(sentence) } else { None } } } impl<'a> Iterator for USentenceBoundIndices<'a> { type Item = (usize, &'a str); #[inline] fn next(&mut self) -> Option<(usize, &'a str)> { self.iter.next().map(|s| (s.as_ptr() as usize - self.start_offset, s)) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } }
match1(StatePart::Sot) { None } else if self.state.match1(StatePart::Eot) { None } else { self.state = self.state.end(); Some(self.pos) } } } pub fn new_sentence_br
random
[]
Rust
parallel-processor-rs/src/debug_allocator.rs
Guilucand/genome-assembly
a18ce27eab733a95de40276348f22277e83a565a
use dashmap::DashMap; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::to_string_pretty; use std::alloc::{GlobalAlloc, Layout, System}; use std::fs::File; use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; pub struct DebugAllocator { default_allocator: std::alloc::System, } struct AllocationInfo { bt: String, current_count: AtomicUsize, current_size: AtomicUsize, max_size: AtomicUsize, total_count: AtomicUsize, } impl AllocationInfo { pub fn as_writable(&self) -> AllocationInfoWritable { AllocationInfoWritable { bt: self.bt.clone(), current_count: self.current_count.load(Ordering::Relaxed), current_size: self.current_size.load(Ordering::Relaxed), max_size: self.max_size.load(Ordering::Relaxed), total_count: self.total_count.load(Ordering::Relaxed), } } } #[derive(Serialize, Deserialize, Clone)] struct AllocationInfoWritable { bt: String, current_count: usize, current_size: usize, max_size: usize, total_count: usize, } lazy_static! { static ref ALLOCATION_INFOS: DashMap<String, AllocationInfo> = DashMap::new(); static ref ADDRESSES_BACKTRACE: DashMap<usize, String> = DashMap::new(); } pub fn debug_print_allocations(dir: impl AsRef<Path>, period: Duration) { let dir = dir.as_ref().to_path_buf(); std::thread::spawn(move || { IS_NESTED.with(|n| n.store(true, Ordering::Relaxed)); let mut count = 1; loop { std::thread::sleep(period); let path = dir.join(format!("memory-log{}.json", count)); let mut allocations: Vec<_> = ALLOCATION_INFOS.iter().map(|x| x.as_writable()).collect(); allocations.sort_by(|x, y| y.max_size.cmp(&x.max_size)); let _ = File::create(path) .unwrap() .write_all(to_string_pretty(&allocations).unwrap().as_bytes()); count += 1; } }); } fn store_backtrace(addr: *mut u8, size: usize) { let bt: backtrace::Backtrace = backtrace::Backtrace::new(); let bt_string = format!("{:?}", bt); let parts = bt_string.split(" 5:").collect::<Vec<_>>(); let bt_string = parts.last().unwrap().to_string(); ADDRESSES_BACKTRACE.insert(addr as usize, bt_string.clone()); let info = ALLOCATION_INFOS .entry(bt_string.clone()) .or_insert(AllocationInfo { bt: bt_string, current_count: AtomicUsize::new(0), current_size: AtomicUsize::new(0), max_size: AtomicUsize::new(0), total_count: AtomicUsize::new(0), }); info.current_count.fetch_add(1, Ordering::Relaxed); info.current_size.fetch_add(size, Ordering::Relaxed); info.total_count.fetch_add(1, Ordering::Relaxed); info.max_size .fetch_max(info.current_size.load(Ordering::Relaxed), Ordering::Relaxed); } fn update_backtrace(ptr: *mut u8, new_ptr: *mut u8, diff: isize) { let (_, bt) = ADDRESSES_BACKTRACE.remove(&(ptr as usize)).unwrap(); let aref = ALLOCATION_INFOS.get(&bt).unwrap(); if diff > 0 { aref.current_size .fetch_add(diff as usize, Ordering::Relaxed); aref.max_size .fetch_max(aref.current_size.load(Ordering::Relaxed), Ordering::Relaxed); } else { aref.current_size .fetch_sub((-diff) as usize, Ordering::Relaxed); } ADDRESSES_BACKTRACE.insert(new_ptr as usize, bt); } fn dealloc_backtrace(ptr: *mut u8, size: usize) { let (_, bt) = ADDRESSES_BACKTRACE.remove(&(ptr as usize)).unwrap(); let aref = ALLOCATION_INFOS.get(&bt).unwrap(); aref.current_count.fetch_sub(1, Ordering::Relaxed); aref.current_size.fetch_sub(size, Ordering::Relaxed); } impl DebugAllocator { pub const fn new() -> Self { Self { default_allocator: System, } } } thread_local! { static IS_NESTED: AtomicBool = AtomicBool::new(false); } unsafe impl GlobalAlloc for DebugAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let ptr = self.default_allocator.alloc(layout); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { store_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } ptr } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { dealloc_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } self.default_allocator.dealloc(ptr, layout) } unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { let ptr = self.default_allocator.alloc_zeroed(layout); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { store_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } ptr } unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { let new_ptr = self.default_allocator.realloc(ptr, layout, new_size); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { update_backtrace(ptr, new_ptr, (new_size as isize) - (layout.size() as isize)); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } new_ptr } }
use dashmap::DashMap; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_json::to_string_pretty; use std::alloc::{GlobalAlloc, Layout, System}; use std::fs::File; use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; pub struct DebugAllocator { default_allocator: std::alloc::System, } struct AllocationInfo { bt: String, current_count: AtomicUsize, current_size: AtomicUsize, max_size: AtomicUsize, total_count: AtomicUsize, } impl AllocationInfo { pub fn as_writable(&self) -> AllocationInfoWritable { AllocationInfoWritable { bt: self.bt.clone(), current_count: self.current_count.load(Ordering::Relaxed), current_size: self.current_size.load(Ordering::Relaxed), max_size: self.max_size.load(Ordering::Relaxed), total_count: self.total_count.load(Ordering::Relaxed), } } } #[derive(Serialize, Deserialize, Clone)] struct AllocationInfoWritable { bt: String, current_count: usize, current_size: usize, max_size: usize, total_count: usize, } lazy_static! { static ref ALLOCATION_INFOS: DashMap<String, AllocationInfo> = DashMap::new(); static ref ADDRESSES_BACKTRACE: DashMap<usize, String> = DashMap::new(); } pub fn debug_print_allocations(dir: impl AsRef<Path>, period: Duration) { let dir = dir.as_ref().to_path_buf(); std::thread::spawn(move || { IS_NESTED.with(|n| n.store(true, Ordering::Relaxed)); let mut count = 1; loop { std::thread::sleep(period); let path = dir.join(format!("memory-log{}.json", count)); let mut allocations: Vec<_> = ALLOCATION_INFOS.iter().map(|x| x.as_writable()).collect(); allocations.sort_by(|x, y| y.max_size.cmp(&x.max_size)); let _ = File::create(path) .unwrap() .write_all(to_string_pretty(&allocations).unwrap().as_bytes()); count += 1; } }); } fn store_backtrace(addr: *mut u8, size: usize) { let bt: backtrace::Backtrace = backtrace::Backtrace::new(); let bt_string = format!("{:?}", bt); let parts = bt_string.split(" 5:").collect::<Vec<_>>(); let bt_string = parts.last().unwrap().to_string(); ADDRESSES_BACKTRACE.insert(addr as usize, bt_string.clone()); let info = ALLOCATION_INFOS .entry(bt_string.clone()) .or_insert(AllocationInfo { bt: bt_string, current_count: AtomicUsize::new(0), current_size: AtomicUsize::new(0), max_size: AtomicUsize::new(0), total_count: AtomicUsize::new(0), }); info.current_count.fetch_add(1, Ordering::
fn update_backtrace(ptr: *mut u8, new_ptr: *mut u8, diff: isize) { let (_, bt) = ADDRESSES_BACKTRACE.remove(&(ptr as usize)).unwrap(); let aref = ALLOCATION_INFOS.get(&bt).unwrap(); if diff > 0 { aref.current_size .fetch_add(diff as usize, Ordering::Relaxed); aref.max_size .fetch_max(aref.current_size.load(Ordering::Relaxed), Ordering::Relaxed); } else { aref.current_size .fetch_sub((-diff) as usize, Ordering::Relaxed); } ADDRESSES_BACKTRACE.insert(new_ptr as usize, bt); } fn dealloc_backtrace(ptr: *mut u8, size: usize) { let (_, bt) = ADDRESSES_BACKTRACE.remove(&(ptr as usize)).unwrap(); let aref = ALLOCATION_INFOS.get(&bt).unwrap(); aref.current_count.fetch_sub(1, Ordering::Relaxed); aref.current_size.fetch_sub(size, Ordering::Relaxed); } impl DebugAllocator { pub const fn new() -> Self { Self { default_allocator: System, } } } thread_local! { static IS_NESTED: AtomicBool = AtomicBool::new(false); } unsafe impl GlobalAlloc for DebugAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let ptr = self.default_allocator.alloc(layout); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { store_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } ptr } unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { dealloc_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } self.default_allocator.dealloc(ptr, layout) } unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { let ptr = self.default_allocator.alloc_zeroed(layout); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { store_backtrace(ptr, layout.size()); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } ptr } unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { let new_ptr = self.default_allocator.realloc(ptr, layout, new_size); if !IS_NESTED.with(|n| n.swap(true, Ordering::Relaxed)) { update_backtrace(ptr, new_ptr, (new_size as isize) - (layout.size() as isize)); IS_NESTED.with(|n| n.store(false, Ordering::Relaxed)); } new_ptr } }
Relaxed); info.current_size.fetch_add(size, Ordering::Relaxed); info.total_count.fetch_add(1, Ordering::Relaxed); info.max_size .fetch_max(info.current_size.load(Ordering::Relaxed), Ordering::Relaxed); }
function_block-function_prefixed
[ { "content": "#[inline(always)]\n\npub fn decode_varint(mut read_byte: impl FnMut() -> Option<u8>) -> Option<u64> {\n\n let mut result = 0;\n\n let mut offset = 0u32;\n\n loop {\n\n let value = read_byte()?;\n\n let next = (value & 0b10000000) != 0;\n\n result |= ((value & 0b111111...
Rust
crates/eosio_macros_internal/src/internal.rs
adsorptionenthalpy/eosio-rust
f21a1ce86c6d7456bd05b3106c5a89ae593a487d
use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use std::fmt::{self, Display}; use syn::{ parse::{Error as ParseError, Result as ParseResult}, Attribute, Ident, Lit, LitStr, Meta, Meta::List, NestedMeta, Path, }; #[derive(Copy, Clone)] pub struct Symbol(&'static str); pub const EOSIO: Symbol = Symbol("eosio"); pub const TABLE_NAME: Symbol = Symbol("table_name"); pub const SINGLETON: Symbol = Symbol("singleton"); pub const PRIMARY_KEY: Symbol = Symbol("primary_key"); pub const SECONDARY_KEY: Symbol = Symbol("secondary_key"); pub const CRATE_PATH: Symbol = Symbol("crate_path"); impl PartialEq<Symbol> for Ident { fn eq(&self, word: &Symbol) -> bool { self == word.0 } } impl<'a> PartialEq<Symbol> for &'a Ident { fn eq(&self, word: &Symbol) -> bool { *self == word.0 } } impl PartialEq<Symbol> for Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl<'a> PartialEq<Symbol> for &'a Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl Display for Symbol { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(self.0) } } pub fn get_eosio_meta_items( attr: &syn::Attribute, ) -> Result<Vec<syn::NestedMeta>, ()> { if attr.path != EOSIO { return Ok(Vec::new()); } match attr.parse_meta() { Ok(List(meta)) => Ok(meta.nested.into_iter().collect()), _ => Err(()), } } pub fn get_root_path(attrs: &[Attribute]) -> Path { for meta_item in attrs.iter().flat_map(get_eosio_meta_items).flatten() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path == CRATE_PATH => { match m.lit { Lit::Str(string) => { if let Ok(path) = string.parse_with(Path::parse_mod_style) { return path; } else { panic!( "`#[eosio(crate_path = \"...\")]` received an \ invalid path" ); } } _ => { panic!("invalid eosio crate path"); } } } _ => continue, } } LitStr::new("::eosio", Span::call_site()) .parse_with(Path::parse_mod_style) .unwrap() } pub struct Attr<T> { name: Symbol, tokens: TokenStream, value: Option<T>, } impl<T> Attr<T> { pub fn none(name: Symbol) -> Self { Self { name, tokens: TokenStream::new(), value: None, } } pub fn set<A: ToTokens>(&mut self, obj: A, value: T) -> ParseResult<()> { let tokens = obj.into_token_stream(); if self.value.is_some() { Err(ParseError::new_spanned( tokens, format!("duplicate eosio attribute `{}`", self.name), )) } else { self.tokens = tokens; self.value = Some(value); Ok(()) } } pub fn get(self) -> Option<T> { self.value } pub fn get_with_tokens(self) -> Option<(TokenStream, T)> { match self.value { Some(v) => Some((self.tokens, v)), None => None, } } } pub struct BoolAttr(Attr<()>); impl BoolAttr { pub fn none(name: Symbol) -> Self { Self(Attr::none(name)) } pub fn set_true<A: ToTokens>(&mut self, obj: A) -> ParseResult<()> { self.0.set(obj, ()) } pub fn get(&self) -> bool { self.0.value.is_some() } }
use proc_macro2::{Span, TokenStream}; use quote::ToTokens; use std::fmt::{self, Display}; use syn::{ parse::{Error as ParseError, Result as ParseResult}, Attribute, Ident, Lit, LitStr, Meta, Meta::List, NestedMeta, Path, }; #[derive(Copy, Clone)] pub struct Symbol(&'static str); pub const EOSIO: Symbol = Symbol("eosio"); pub const TABLE_NAME: Symbol = Symbol("table_name"); pub const SINGLETON: Symbol = Symbol("singleton"); pub const PRIMARY_KEY: Symbol = Symbol("primary_key"); pub const SECONDARY_KEY: Symbol = Symbol("secondary_key"); pub const CRATE_PATH: Symbol = Symbol("crate_path"); impl PartialEq<Symbol> for Ident { fn eq(&self, word: &Symbol) -> bool { self == word.0 } } impl<'a> PartialEq<Symbol> for &'a Ident { fn eq(&self, word: &Symbol) -> bool { *self == word.0 } } impl PartialEq<Symbol> for Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl<'a> PartialEq<Symbol> for &'a Path { fn eq(&self, word: &Symbol) -> bool { self.is_ident(word.0) } } impl Display for Symbol { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(self.0) } } pub fn get_eosio_meta_items( attr: &syn::Attribute, ) -> Result<Vec<syn::NestedMeta>, ()> { if attr.path != EOSIO { return Ok(Vec::new()); } match attr.parse_meta() { Ok(List(meta)) => Ok(meta.nested.into_iter().collect()), _ => Err(()), } }
pub struct Attr<T> { name: Symbol, tokens: TokenStream, value: Option<T>, } impl<T> Attr<T> { pub fn none(name: Symbol) -> Self { Self { name, tokens: TokenStream::new(), value: None, } } pub fn set<A: ToTokens>(&mut self, obj: A, value: T) -> ParseResult<()> { let tokens = obj.into_token_stream(); if self.value.is_some() { Err(ParseError::new_spanned( tokens, format!("duplicate eosio attribute `{}`", self.name), )) } else { self.tokens = tokens; self.value = Some(value); Ok(()) } } pub fn get(self) -> Option<T> { self.value } pub fn get_with_tokens(self) -> Option<(TokenStream, T)> { match self.value { Some(v) => Some((self.tokens, v)), None => None, } } } pub struct BoolAttr(Attr<()>); impl BoolAttr { pub fn none(name: Symbol) -> Self { Self(Attr::none(name)) } pub fn set_true<A: ToTokens>(&mut self, obj: A) -> ParseResult<()> { self.0.set(obj, ()) } pub fn get(&self) -> bool { self.0.value.is_some() } }
pub fn get_root_path(attrs: &[Attribute]) -> Path { for meta_item in attrs.iter().flat_map(get_eosio_meta_items).flatten() { match meta_item { NestedMeta::Meta(Meta::NameValue(m)) if m.path == CRATE_PATH => { match m.lit { Lit::Str(string) => { if let Ok(path) = string.parse_with(Path::parse_mod_style) { return path; } else { panic!( "`#[eosio(crate_path = \"...\")]` received an \ invalid path" ); } } _ => { panic!("invalid eosio crate path"); } } } _ => continue, } } LitStr::new("::eosio", Span::call_site()) .parse_with(Path::parse_mod_style) .unwrap() }
function_block-full_function
[ { "content": "pub fn set_abi(account: impl AsRef<str>, abi_path: impl AsRef<str>) {\n\n let account = account.as_ref();\n\n let abi_path = abi_path.as_ref();\n\n println!(\"set abi {} {}\", account, abi_path);\n\n cleos()\n\n .arg(\"set\")\n\n .arg(\"abi\")\n\n .arg(account)\n\n...
Rust
src/wand/macros.rs
Atul9/magick-rust
65ae47fbf83182257bd69a6e38ade3d29412361d
/* * Copyright 2016 Mattis Marjak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ macro_rules! wand_common { ( $wand:ident, $new_wand:ident, $clear_wand:ident, $is_wand:ident, $clone:ident, $destroy:ident, $clear_exc:ident, $get_exc_type:ident, $get_exc:ident ) => { pub struct $wand { pub wand: *mut ::bindings::$wand, } impl $wand { pub fn new() -> Self { $wand { wand: unsafe { ::bindings::$new_wand() }, } } fn clear(&mut self) { unsafe { ::bindings::$clear_wand(self.wand) } } pub fn clear_exception(&mut self) -> Result<(), &'static str> { match unsafe { ::bindings::$clear_exc(self.wand) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!("failed to clear", stringify!($wand), "exception")), } } pub fn get_exception_type(&self) -> ::bindings::ExceptionType { unsafe { ::bindings::$get_exc_type(self.wand) } } pub fn get_exception(&self) -> Result<(String, ::bindings::ExceptionType), &'static str> { let mut severity: ::bindings::ExceptionType = ::bindings::ExceptionType_UndefinedException; let ptr = unsafe { ::bindings::$get_exc(self.wand, &mut severity as *mut _) }; if ptr.is_null() { Err(concat!( "null ptr returned by", stringify!($wand), "get_exception" )) } else { let c_str = unsafe { CStr::from_ptr(ptr) }; Ok((c_str.to_string_lossy().into_owned(), severity)) } } pub fn is_wand(&self) -> Result<(), &'static str> { match unsafe { ::bindings::$is_wand(self.wand) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($wand), " not a wand")), } } } impl Clone for $wand { fn clone(&self) -> Self { $wand { wand: unsafe { ::bindings::$clone(self.wand) }, } } } impl Drop for $wand { fn drop(&mut self) { unsafe { ::bindings::$clear_exc(self.wand); ::bindings::$destroy(self.wand); } } } }; } macro_rules! get { ($($get:ident, $c_get:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } )* } } macro_rules! set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } pub fn $set(&mut self, v: $typ) -> Result<(), &'static str> { match unsafe { ::bindings::$c_set(self.wand, v) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($set), " returned false")) } } )* pub fn fmt_checked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! set_get_unchecked { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } pub fn $set(&mut self, v: $typ) { unsafe { ::bindings::$c_set(self.wand, v) } } )* pub fn fmt_unchecked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! string_get { ($get:ident, $c_get:ident) => { pub fn $get(&self) -> Result<String, &'static str> { let ptr = unsafe { ::bindings::$c_get(self.wand) }; if ptr.is_null() { Err(concat!("null ptr returned by ", stringify!($get))) } else { let c_str = unsafe { ::std::ffi::CStr::from_ptr(ptr) }; let result: String = c_str.to_string_lossy().into_owned(); unsafe { ::bindings::free(ptr as *mut ::libc::c_void) }; Ok(result) } } } } macro_rules! string_set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident)*) => { $( string_get!($get, $c_get); pub fn $set(&mut self, s: &str) -> Result<(), &'static str> { let c_string = try!(::std::ffi::CString::new(s).map_err(|_| "could not convert to cstring")); match unsafe { ::bindings::$c_set(self.wand, c_string.as_ptr()) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($set), " returned false")) } } )* pub fn fmt_string_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! string_set_get_unchecked { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident )*) => { $( string_get!($get, $c_get); pub fn $set(&mut self, s: &str) -> Result<(), &'static str> { let c_string = try!(::std::ffi::CString::new(s).map_err(|_| "could not convert to cstring")); unsafe { ::bindings::$c_set(self.wand, c_string.as_ptr()) }; Ok(()) } )* pub fn fmt_string_unchecked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! pixel_set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident )*) => { $( pub fn $get(&self) -> ::PixelWand { let pw = ::PixelWand::new(); unsafe { ::bindings::$c_get(self.wand, pw.wand) }; pw } pub fn $set(&mut self, pw: &::PixelWand) { unsafe { ::bindings::$c_set(self.wand, pw.wand) } } )* pub fn fmt_pixel_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: ", prefix, stringify!($c_get))); try!(self.$get().fmt_w_prefix(f, &format!("{}{:<53}", prefix, " ") )); )* Ok(()) } } } macro_rules! color_set_get { ($( $get:ident, $get_quantum:ident, $set:ident, $set_quantum:ident, $c_get:ident, $c_get_quantum:ident, $c_set:ident, $c_set_quantum:ident )*) => { $( pub fn $get(&self) -> f64 { unsafe { ::bindings::$c_get(self.wand) } } pub fn $get_quantum(&self) -> bindings::Quantum { unsafe { ::bindings::$c_get_quantum(self.wand) } } pub fn $set(&mut self, v: f64) { unsafe { ::bindings::$c_set(self.wand, v) } } pub fn $set_quantum(&mut self, v: bindings::Quantum) { unsafe { ::bindings::$c_set_quantum(self.wand, v) } } )* pub fn fmt_color_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { try!(writeln!(f, "{}Color: {:?}, normalized: {:?}\n{}hsl: {:?}", prefix, self.get_color_as_string(), self.get_color_as_normalized_string(), prefix, self.get_hsl() )); $( try!(writeln!(f, "{}{:<10}: {:>} quantum: {}", prefix, stringify!($c_get).split_at(8).1, self.$get(), self.$get_quantum())); )* Ok(()) } } } macro_rules! mutations { ($($(#[$attr:meta])* $c_fun:ident => $fun:ident($($arg:ident: $ty:ty),*))*) => { $( $(#[$attr])* pub fn $fun(&self $(, $arg: $ty)*) -> Result<(), &'static str> { match unsafe { bindings::$c_fun(self.wand $(, $arg)*) } { bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($c_fun), " invocation failed")) } } )* } }
/* * Copyright 2016 Mattis Marjak * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ macro_rules! wand_common { ( $wand:ident, $new_wand:ident, $clear_wand:ident, $is_wand:ident, $clone:ident, $destroy:ident, $clear_exc:ident, $get_exc_type:ident, $get_exc:ident ) => { pub struct $wand { pub wand: *mut ::bindings::$wand, } impl $wand { pub fn new() -> Self { $wand { wand: unsafe { ::bindings::$new_wand() }, } } fn clear(&mut self) { unsafe { ::bindings::$clear_wand(self.wand) } } pub fn clear_exception(&mut self) -> Result<(), &'static str> { match unsafe { ::bindings::$clear_exc(self.wand) } { ::bindings
"null ptr returned by", stringify!($wand), "get_exception" )) } else { let c_str = unsafe { CStr::from_ptr(ptr) }; Ok((c_str.to_string_lossy().into_owned(), severity)) } } pub fn is_wand(&self) -> Result<(), &'static str> { match unsafe { ::bindings::$is_wand(self.wand) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($wand), " not a wand")), } } } impl Clone for $wand { fn clone(&self) -> Self { $wand { wand: unsafe { ::bindings::$clone(self.wand) }, } } } impl Drop for $wand { fn drop(&mut self) { unsafe { ::bindings::$clear_exc(self.wand); ::bindings::$destroy(self.wand); } } } }; } macro_rules! get { ($($get:ident, $c_get:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } )* } } macro_rules! set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } pub fn $set(&mut self, v: $typ) -> Result<(), &'static str> { match unsafe { ::bindings::$c_set(self.wand, v) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($set), " returned false")) } } )* pub fn fmt_checked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! set_get_unchecked { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident, $typ:ty )*) => { $( pub fn $get(&self) -> $typ { unsafe { ::bindings::$c_get(self.wand) } } pub fn $set(&mut self, v: $typ) { unsafe { ::bindings::$c_set(self.wand, v) } } )* pub fn fmt_unchecked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! string_get { ($get:ident, $c_get:ident) => { pub fn $get(&self) -> Result<String, &'static str> { let ptr = unsafe { ::bindings::$c_get(self.wand) }; if ptr.is_null() { Err(concat!("null ptr returned by ", stringify!($get))) } else { let c_str = unsafe { ::std::ffi::CStr::from_ptr(ptr) }; let result: String = c_str.to_string_lossy().into_owned(); unsafe { ::bindings::free(ptr as *mut ::libc::c_void) }; Ok(result) } } } } macro_rules! string_set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident)*) => { $( string_get!($get, $c_get); pub fn $set(&mut self, s: &str) -> Result<(), &'static str> { let c_string = try!(::std::ffi::CString::new(s).map_err(|_| "could not convert to cstring")); match unsafe { ::bindings::$c_set(self.wand, c_string.as_ptr()) } { ::bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($set), " returned false")) } } )* pub fn fmt_string_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! string_set_get_unchecked { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident )*) => { $( string_get!($get, $c_get); pub fn $set(&mut self, s: &str) -> Result<(), &'static str> { let c_string = try!(::std::ffi::CString::new(s).map_err(|_| "could not convert to cstring")); unsafe { ::bindings::$c_set(self.wand, c_string.as_ptr()) }; Ok(()) } )* pub fn fmt_string_unchecked_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: {:?}", prefix, stringify!($c_get), self.$get())); )* Ok(()) } } } macro_rules! pixel_set_get { ($($get:ident, $set:ident, $c_get:ident, $c_set:ident )*) => { $( pub fn $get(&self) -> ::PixelWand { let pw = ::PixelWand::new(); unsafe { ::bindings::$c_get(self.wand, pw.wand) }; pw } pub fn $set(&mut self, pw: &::PixelWand) { unsafe { ::bindings::$c_set(self.wand, pw.wand) } } )* pub fn fmt_pixel_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { $( try!(writeln!(f, "{}{:<50}: ", prefix, stringify!($c_get))); try!(self.$get().fmt_w_prefix(f, &format!("{}{:<53}", prefix, " ") )); )* Ok(()) } } } macro_rules! color_set_get { ($( $get:ident, $get_quantum:ident, $set:ident, $set_quantum:ident, $c_get:ident, $c_get_quantum:ident, $c_set:ident, $c_set_quantum:ident )*) => { $( pub fn $get(&self) -> f64 { unsafe { ::bindings::$c_get(self.wand) } } pub fn $get_quantum(&self) -> bindings::Quantum { unsafe { ::bindings::$c_get_quantum(self.wand) } } pub fn $set(&mut self, v: f64) { unsafe { ::bindings::$c_set(self.wand, v) } } pub fn $set_quantum(&mut self, v: bindings::Quantum) { unsafe { ::bindings::$c_set_quantum(self.wand, v) } } )* pub fn fmt_color_settings(&self, f: &mut ::std::fmt::Formatter, prefix: &str) -> ::std::fmt::Result { try!(writeln!(f, "{}Color: {:?}, normalized: {:?}\n{}hsl: {:?}", prefix, self.get_color_as_string(), self.get_color_as_normalized_string(), prefix, self.get_hsl() )); $( try!(writeln!(f, "{}{:<10}: {:>} quantum: {}", prefix, stringify!($c_get).split_at(8).1, self.$get(), self.$get_quantum())); )* Ok(()) } } } macro_rules! mutations { ($($(#[$attr:meta])* $c_fun:ident => $fun:ident($($arg:ident: $ty:ty),*))*) => { $( $(#[$attr])* pub fn $fun(&self $(, $arg: $ty)*) -> Result<(), &'static str> { match unsafe { bindings::$c_fun(self.wand $(, $arg)*) } { bindings::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!(stringify!($c_fun), " invocation failed")) } } )* } }
::MagickBooleanType_MagickTrue => Ok(()), _ => Err(concat!("failed to clear", stringify!($wand), "exception")), } } pub fn get_exception_type(&self) -> ::bindings::ExceptionType { unsafe { ::bindings::$get_exc_type(self.wand) } } pub fn get_exception(&self) -> Result<(String, ::bindings::ExceptionType), &'static str> { let mut severity: ::bindings::ExceptionType = ::bindings::ExceptionType_UndefinedException; let ptr = unsafe { ::bindings::$get_exc(self.wand, &mut severity as *mut _) }; if ptr.is_null() { Err(concat!(
random
[ { "content": "pub fn magick_query_fonts(pattern: &str) -> Result<Vec<String>, &'static str> {\n\n let mut number_fonts: size_t = 0;\n\n let c_string =\n\n try!(::std::ffi::CString::new(pattern).map_err(|_| \"could not convert to cstring\"));\n\n let ptr =\n\n unsafe { bindings::MagickQuer...
Rust
program/src/state.rs
0xNico/noir-pay
8ef1e219c75ce96d900247497885efae3235f626
use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use std::convert::TryInto; #[derive(Clone)] pub struct ChecksAndTransferState { is_initialized: bool, pub found_root: u8, pub found_nullifier: u8, pub executed_withdraw: u8, pub signing_address: Vec<u8>, pub relayer_refund: Vec<u8>, pub to_address: Vec<u8>, pub ext_amount: Vec<u8>, pub amount: Vec<u8>, pub root_hash: Vec<u8>, pub data_hash: Vec<u8>, pub tx_integrity_hash: Vec<u8>, pub current_instruction_index: usize, pub proof_a_b_c_leaves_and_nullifiers: Vec<u8>, pub changed_constants: [bool; 12], } impl Sealed for ChecksAndTransferState {} impl IsInitialized for ChecksAndTransferState { fn is_initialized(&self) -> bool { self.is_initialized } } impl Pack for ChecksAndTransferState { const LEN: usize = 3900; fn unpack_from_slice(input: &[u8]) -> Result<Self, ProgramError> { let input = array_ref![input, 0, ChecksAndTransferState::LEN]; let ( _is_initialized, found_root, found_nullifier, executed_withdraw, signing_address, relayer_refund, to_address, ext_amount, amount, root_hash, data_hash, tx_integrity_hash, current_instruction_index, _unused_remainder, proof_a_b_c_leaves_and_nullifiers, ) = array_refs![input, 1, 1, 1, 1, 32, 8, 32, 8, 32, 32, 32, 32, 8, 3296, 384]; Ok(ChecksAndTransferState { is_initialized: true, found_root: found_root[0], found_nullifier: found_nullifier[0], executed_withdraw: executed_withdraw[0], signing_address: signing_address.to_vec(), relayer_refund: relayer_refund.to_vec(), to_address: to_address.to_vec(), ext_amount: ext_amount.to_vec(), amount: amount.to_vec(), root_hash: root_hash.to_vec(), data_hash: data_hash.to_vec(), tx_integrity_hash: tx_integrity_hash.to_vec(), proof_a_b_c_leaves_and_nullifiers: proof_a_b_c_leaves_and_nullifiers.to_vec(), current_instruction_index: usize::from_le_bytes(*current_instruction_index), changed_constants: [false; 12], }) } fn pack_into_slice(&self, dst: &mut [u8]) { let dst = array_mut_ref![dst, 0, ChecksAndTransferState::LEN]; let ( _is_initialized_dst, found_root_dst, found_nullifier_dst, executed_withdraw_dst, signing_address_dst, relayer_refund_dst, to_address_dst, ext_amount_dst, amount_dst, root_hash_dst, data_hash_dst, tx_integrity_hash_dst, current_instruction_index_dst, _unused_remainder_dst, proof_a_b_c_leaves_and_nullifiers_dst, ) = mut_array_refs![dst, 1, 1, 1, 1, 32, 8, 32, 8, 32, 32, 32, 32, 8, 3296, 384]; for (i, const_has_changed) in self.changed_constants.iter().enumerate() { if *const_has_changed { if i == 0 { *found_root_dst = [self.found_root; 1]; } else if i == 1 { *found_nullifier_dst = [self.found_nullifier; 1]; } else if i == 2 { *executed_withdraw_dst = [self.executed_withdraw; 1]; } else if i == 3 { *signing_address_dst = self.signing_address.clone().try_into().unwrap(); } else if i == 4 { *relayer_refund_dst = self.relayer_refund.clone().try_into().unwrap(); } else if i == 5 { *to_address_dst = self.to_address.clone().try_into().unwrap(); } else if i == 6 { *ext_amount_dst = self.ext_amount.clone().try_into().unwrap(); } else if i == 7 { *amount_dst = self.amount.clone().try_into().unwrap(); } else if i == 8 { *root_hash_dst = self.root_hash.clone().try_into().unwrap(); } else if i == 9 { *data_hash_dst = self.data_hash.clone().try_into().unwrap(); } else if i == 10 { *tx_integrity_hash_dst = self.tx_integrity_hash.clone().try_into().unwrap(); } else if i == 11 { *proof_a_b_c_leaves_and_nullifiers_dst = self .proof_a_b_c_leaves_and_nullifiers .clone() .try_into() .unwrap(); } } } *current_instruction_index_dst = usize::to_le_bytes(self.current_instruction_index); } } #[derive(Debug, Clone)] pub struct InstructionIndex { is_initialized: bool, pub signer_pubkey: Pubkey, pub current_instruction_index: usize, } impl Sealed for InstructionIndex {} impl IsInitialized for InstructionIndex { fn is_initialized(&self) -> bool { self.is_initialized } } impl Pack for InstructionIndex { const LEN: usize = 3900; fn unpack_from_slice(input: &[u8]) -> Result<Self, ProgramError> { let input = array_ref![input, 0, InstructionIndex::LEN]; let ( is_initialized, _unused_remainder0, signer_pubkey, _unused_remainder1, current_instruction_index, _unused_remainder2, ) = array_refs![input, 1, 3, 32, 176, 8, 3680]; if is_initialized[0] == 0 { Err(ProgramError::InvalidAccountData) } else { Ok(InstructionIndex { is_initialized: true, signer_pubkey: solana_program::pubkey::Pubkey::new(signer_pubkey), current_instruction_index: usize::from_le_bytes(*current_instruction_index), }) } } fn pack_into_slice(&self, _dst: &mut [u8]) {} }
use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; use solana_program::{ program_error::ProgramError, program_pack::{IsInitialized, Pack, Sealed}, pubkey::Pubkey, }; use std::convert::TryInto; #[derive(Clone)] pub struct ChecksAndTransferState { is_initialized: bool, pub found_root: u8, pub found_nullifier: u8, pub executed_withdraw: u8, pub signing_address: Vec<u8>, pub relayer_refund: Vec<u8>, pub to_address: Vec<u8>, pub ext_amount: Vec<u8>, pub amount: Vec<u8>, pub root_hash: Vec<u8>, pub data_hash: Vec<u8>, pub tx_integrity_hash: Vec<u8>, pub current_instruction_index: usize, pub proof_a_b_c_leaves_and_nullifiers: Vec<u8>, pub changed_constants: [bool; 12], } impl Sealed for ChecksAndTransferState {} impl IsInitialized for ChecksAndTransferState { fn is_initialized(&self) -> bool { self.is_initialized } } impl Pack for ChecksAndTransferState { const LEN: usize = 3900; fn unpack_from_slice(input: &[u8]) -> Result<Self, ProgramError> { let input = array_ref![input, 0, ChecksAndTransferState::LEN]; let ( _is_initialized, found_root, found_nullifier, executed_withdraw, signing_address, relayer_refund, to_address, ext_amount, amount, root_hash, data_hash, tx_integrity_hash, current_instruction_index, _unused_remainder, proof_a_b_c_leaves_and_nullifiers, ) = array_refs![input, 1, 1, 1, 1, 32, 8, 32, 8, 32, 32, 32, 32, 8, 3296, 384]; Ok(ChecksAndTransferState { is_initialized: true, found_root: found_root[0], found_nullifier: found_nullifier[0], executed_withdraw: executed_withdraw[0], signing_address: signing_address.to_vec(), relayer_refund: relayer_refund.to_vec(), to_address: to_address.to_vec(), ext_amount: ext_amount.to_vec(), amount: amount.to_vec(), root_hash: root_hash.to_vec(), data_hash: data_hash.to_vec(), tx_integrity_hash: tx_integrity_hash.to_vec(), proof_a_b_c_leaves_and_nullifiers: proof_a_b_c_leaves_and_nullifiers.to_vec(), current_instruction_index: usize::from_le_bytes(*current_instruction_index), changed_constants: [false; 12], }) } fn pack_into_slice(&self, dst: &mut [u8]) { let dst = array_mut_ref![dst, 0, ChecksAndTransferState::LEN]; let ( _is_initialized_dst, found_root_dst, found_nullifier_dst, executed_withdraw_dst, signing_address_dst, relayer_refund_dst, to_address_dst, ext_amount_dst, amount_dst, root_hash_dst, data_hash_dst, tx_integrity_hash_dst, current_instruction_index_dst, _unused_remainder_dst, proof_a_b_c_leaves_and_nullifiers_dst, ) = mut_array_refs![dst, 1, 1, 1, 1, 32, 8, 32, 8, 32, 32, 32, 32, 8, 3296, 384]; for (i, const_has_changed) in self.changed_constants.iter().enumerate() { if *const_has_changed { if i == 0 { *found_root_dst = [self.found_root; 1]; } else if i == 1 { *found_nullifier_dst = [self.found_nullifier; 1]; } else if i == 2 { *executed_withdraw_dst = [self.executed_withdraw; 1]; } else if i == 3 { *signing_address_dst = self.signing_address.clone().try_into().unwrap(); } else if i == 4 { *relayer_refund_dst = self.relayer_refund.clone().try_into().unwrap(); } else if i == 5 { *to_address_dst = self.to_address.clone().try_into().unwrap(); } else if i == 6 { *ext_amount_dst = self.ext_amount.clone().try_into().unwrap(); } else if i == 7 { *amount_dst = self.amount.clone().try_into().unwrap(); } else if i == 8 { *root_hash_dst = self.root_hash.clone().try_into().unwrap(); } else if i == 9 { *data_hash_dst = self.data_hash.clone().try_into().unwrap(); } else if i == 10 { *tx_integrity_hash_dst = self.tx_integrity_hash.clone().try_into().unwrap(); } else if i == 11 { *proof_a_b_c_leaves_and_nullifiers_dst = self .proof_a_b_c_leaves_and_nullifiers .clone() .try_into() .unwrap(); } } } *current_instruction_index_dst = usize::to_le_bytes(self.current_instruction_index); } } #[derive(Debug, Clone)] pub struct InstructionIndex { is_initialized: bool, pub signer_pubkey: Pubkey, pub current_instruction_index: usize, } impl Sealed for InstructionIndex {} impl IsInitialized for InstructionIndex { fn is_initialized(&self) -> bool { self.is_initialized } } impl Pack for InstructionIndex { const LEN: usize = 3900; fn unpack_from_slice(input: &[u8]) -> Result<Self, ProgramError> { let input = array_ref![input, 0, InstructionIndex::LEN]; let ( is_initialized, _unused_remainder0, signer_pubkey, _unused_remainder1, current_instruction_index, _unused_remainder2, ) = array_refs![input, 1, 3, 32, 176, 8, 3680]; if is_initialized[0] == 0 { Err(ProgramError::InvalidAccountData) } else {
} } fn pack_into_slice(&self, _dst: &mut [u8]) {} }
Ok(InstructionIndex { is_initialized: true, signer_pubkey: solana_program::pubkey::Pubkey::new(signer_pubkey), current_instruction_index: usize::from_le_bytes(*current_instruction_index), })
call_expression
[]
Rust
src/lib.rs
Ekranos/simple-async-pipe
422347782b362beed5d6da1e52d2015312d632cd
use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; pub struct PipeWrite { sender: mpsc::Sender<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } pub struct PipeRead { read_remaining: Vec<u8>, receiver: mpsc::Receiver<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } struct PipeShared { read_waker: Option<Waker>, write_waker: Option<Waker>, } pub fn pipe(buffer: usize) -> (PipeRead, PipeWrite) { let (sender, receiver) = mpsc::channel(buffer); let shared = Arc::new(Mutex::new(PipeShared { read_waker: Default::default(), write_waker: Default::default(), })); let read = PipeRead { receiver, read_remaining: Default::default(), shared: shared.clone(), }; let write = PipeWrite { sender, shared: shared.clone(), }; (read, write) } impl AsyncWrite for PipeWrite { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, std::io::Error>> { match self.sender.try_send(buf.to_vec()) { Ok(_) => { if let Some(read_waker) = self.shared.lock().unwrap().read_waker.take() { read_waker.wake(); } Poll::Ready(Ok(buf.len())) } Err(e) => match e { TrySendError::Full(_) => { self.shared.lock().unwrap().write_waker = Some(cx.waker().clone()); Poll::Pending } TrySendError::Closed(_) => Poll::Ready(Err(std::io::Error::new( std::io::ErrorKind::BrokenPipe, "receiver closed", ))), }, } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> { Poll::Ready(Ok(())) } fn poll_shutdown( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Result<(), std::io::Error>> { Poll::Ready(Ok(())) } } impl AsyncRead for PipeRead { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<std::io::Result<()>> { let mut write_to_buf = |vec: &[u8]| -> Vec<u8> { let end = std::cmp::min(buf.remaining(), vec.len()); let slice_to_write = &vec[0..end]; buf.put_slice(slice_to_write); let rest_of_vec = &vec[end..]; rest_of_vec.to_vec() }; if self.read_remaining.len() > 0 { self.read_remaining = write_to_buf(&mut self.read_remaining); return Poll::Ready(Ok(())); } match self.receiver.poll_recv(cx) { Poll::Ready(v) => match v { None => Poll::Ready(Err(std::io::Error::new( std::io::ErrorKind::BrokenPipe, "sender closed", ))), Some(v) => { self.read_remaining = write_to_buf(&v); if let Some(waker) = self.shared.lock().unwrap().write_waker.take() { waker.wake(); } Poll::Ready(Ok(())) } }, Poll::Pending => Poll::Pending, } } } #[cfg(test)] mod tests { use tokio::io::{AsyncReadExt, AsyncWriteExt}; use super::*; #[tokio::test] async fn test_single_write() { let (mut reader, mut writer) = pipe(512); let to_send = b"hello world"; writer.write_all(to_send).await.expect("error writing"); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } #[tokio::test] async fn test_multi_write() { let (mut reader, mut writer) = pipe(512); let to_send = b"hello world"; writer.write_all(b"hello").await.expect("error writing"); writer.write_all(b" world").await.expect("error writing"); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } #[tokio::test] async fn test_write_more_than_buffer() { let (mut reader, mut writer) = pipe(2); let to_send = b"hello world"; tokio::spawn(async move { writer.write_all(b"hello").await.expect("error writing"); writer.write_all(b" world").await.expect("error writing"); }); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } }
use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::sync::mpsc; use tokio::sync::mpsc::error::TrySendError; pub struct PipeWrite { sender: mpsc::Sender<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } pub struct PipeRead { read_remaining: Vec<u8>, receiver: mpsc::Receiver<Vec<u8>>, shared: Arc<Mutex<PipeShared>>, } struct PipeShared { read_waker: Option<Waker>, write_waker: Option<Waker>, } pub fn pipe(buffer: usize) -> (PipeRead, PipeWrite) { let (sender, receiver) = mpsc::channel(buffer); let shared = Arc::new(Mutex::new(PipeShared { read_waker: Default::default(), write_waker: Default::default(), })); let read = PipeRead { receiver, read_remaining: Default::default(), shared: shared.clone(), }; let write = PipeWrite { sender, shared: shared.clone(), }; (read, write) } impl AsyncWrite for PipeWrite { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, std::io::Error>> { match self.sender.try_send(buf.to_vec()) { Ok(_) => { if let Some(read_waker) = self.shared.lock().unwrap().read_waker.take() { read_waker.wake(); } Poll::Ready(Ok(buf.len())) } Err(e) => match e { TrySendError::Full(_) => { self.shared.lock().unwrap().write_waker = Some(cx.waker().clone()); Poll::Pending } TrySendError::Closed(_) => Poll::Ready(Err(std::io::Error::new( std::io::ErrorKind::BrokenPipe, "receiver closed", ))), }, } } fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> { Poll::Ready(Ok(())) } fn poll_shutdown( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Result<(), std::io::Error>> { Poll::Ready(Ok(())) } } impl AsyncRead for PipeRead { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<std::io::Result<()>> {
if self.read_remaining.len() > 0 { self.read_remaining = write_to_buf(&mut self.read_remaining); return Poll::Ready(Ok(())); } match self.receiver.poll_recv(cx) { Poll::Ready(v) => match v { None => Poll::Ready(Err(std::io::Error::new( std::io::ErrorKind::BrokenPipe, "sender closed", ))), Some(v) => { self.read_remaining = write_to_buf(&v); if let Some(waker) = self.shared.lock().unwrap().write_waker.take() { waker.wake(); } Poll::Ready(Ok(())) } }, Poll::Pending => Poll::Pending, } } } #[cfg(test)] mod tests { use tokio::io::{AsyncReadExt, AsyncWriteExt}; use super::*; #[tokio::test] async fn test_single_write() { let (mut reader, mut writer) = pipe(512); let to_send = b"hello world"; writer.write_all(to_send).await.expect("error writing"); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } #[tokio::test] async fn test_multi_write() { let (mut reader, mut writer) = pipe(512); let to_send = b"hello world"; writer.write_all(b"hello").await.expect("error writing"); writer.write_all(b" world").await.expect("error writing"); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } #[tokio::test] async fn test_write_more_than_buffer() { let (mut reader, mut writer) = pipe(2); let to_send = b"hello world"; tokio::spawn(async move { writer.write_all(b"hello").await.expect("error writing"); writer.write_all(b" world").await.expect("error writing"); }); let mut buffer = vec![0u8; to_send.len()]; reader.read_exact(&mut buffer).await.expect("error reading"); assert_eq!(&buffer, to_send); } }
let mut write_to_buf = |vec: &[u8]| -> Vec<u8> { let end = std::cmp::min(buf.remaining(), vec.len()); let slice_to_write = &vec[0..end]; buf.put_slice(slice_to_write); let rest_of_vec = &vec[end..]; rest_of_vec.to_vec() };
assignment_statement
[ { "content": "# simple-async-pipe\n\n\n\nAims to provide a simple pipe-like functionality for async code. Created to be used in\n\ntests. No performance optimization done.\n\n\n\n[Documentation](https://docs.rs/simple_async_pipe/)\n\n\n\n## License\n\n\n\nThis project is licensed under either of\n\n\n\n* Apache...
Rust
clippy_lints/src/copies.rs
g-bartoszek/rust-clippy
cefddf784373392768b84ebec7be4c697d0b029a
use crate::utils::{get_parent_expr, higher, in_macro_or_desugar, snippet, span_lint_and_then, span_note_and_lint}; use crate::utils::{SpanlessEq, SpanlessHash}; use rustc::hir::*; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::ty::Ty; use rustc::{declare_lint_pass, declare_tool_lint}; use rustc_data_structures::fx::FxHashMap; use smallvec::SmallVec; use std::collections::hash_map::Entry; use std::hash::BuildHasherDefault; use syntax::symbol::LocalInternedString; declare_clippy_lint! { pub IFS_SAME_COND, correctness, "consecutive `ifs` with the same condition" } declare_clippy_lint! { pub IF_SAME_THEN_ELSE, correctness, "if with the same *then* and *else* blocks" } declare_clippy_lint! { pub MATCH_SAME_ARMS, pedantic, "`match` with identical arm bodies" } declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { if !in_macro_or_desugar(expr.span) { if let Some(expr) = get_parent_expr(cx, expr) { if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) { if else_expr.hir_id == expr.hir_id { return; } } } let (conds, blocks) = if_sequence(expr); lint_same_then_else(cx, &blocks); lint_same_cond(cx, &conds); lint_match_arms(cx, expr); } } } fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) { let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) }; if let Some((i, j)) = search_same_sequenced(blocks, eq) { span_note_and_lint( cx, IF_SAME_THEN_ELSE, j.span, "this `if` has identical blocks", i.span, "same as this", ); } } fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) { let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 { let mut h = SpanlessHash::new(cx, cx.tables); h.hash_expr(expr); h.finish() }; let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) }; for (i, j) in search_same(conds, hash, eq) { span_note_and_lint( cx, IFS_SAME_COND, j.span, "this `if` has the same condition as a previous if", i.span, "same as this", ); } } fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) { if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node { let hash = |&(_, arm): &(usize, &Arm)| -> u64 { let mut h = SpanlessHash::new(cx, cx.tables); h.hash_expr(&arm.body); h.finish() }; let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool { let min_index = usize::min(lindex, rindex); let max_index = usize::max(lindex, rindex); (min_index..=max_index).all(|index| arms[index].guard.is_none()) && SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) && bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0]) }; let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect(); for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) { span_lint_and_then( cx, MATCH_SAME_ARMS, j.body.span, "this `match` has identical arm bodies", |db| { db.span_note(i.body.span, "same as this"); if i.pats.len() == 1 && j.pats.len() == 1 { let lhs = snippet(cx, i.pats[0].span, "<pat1>"); let rhs = snippet(cx, j.pats[0].span, "<pat2>"); if let PatKind::Wild = j.pats[0].node { db.span_note( i.body.span, &format!( "`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs ), ); } else { db.span_help( i.pats[0].span, &format!("consider refactoring into `{} | {}`", lhs, rhs), ); } } }, ); } } } fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) { let mut conds = SmallVec::new(); let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new(); while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) { conds.push(&**cond); if let ExprKind::Block(ref block, _) = then_expr.node { blocks.push(block); } else { panic!("ExprKind::If node is not an ExprKind::Block"); } if let Some(ref else_expr) = *else_expr { expr = else_expr; } else { break; } } if !blocks.is_empty() { if let ExprKind::Block(ref block, _) = expr.node { blocks.push(&**block); } } (conds, blocks) } fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> { fn bindings_impl<'a, 'tcx>( cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>, ) { match pat.node { PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map), PatKind::TupleStruct(_, ref pats, _) => { for pat in pats { bindings_impl(cx, pat, map); } }, PatKind::Binding(.., ident, ref as_pat) => { if let Entry::Vacant(v) = map.entry(ident.as_str()) { v.insert(cx.tables.pat_ty(pat)); } if let Some(ref as_pat) = *as_pat { bindings_impl(cx, as_pat, map); } }, PatKind::Struct(_, ref fields, _) => { for pat in fields { bindings_impl(cx, &pat.node.pat, map); } }, PatKind::Tuple(ref fields, _) => { for pat in fields { bindings_impl(cx, pat, map); } }, PatKind::Slice(ref lhs, ref mid, ref rhs) => { for pat in lhs { bindings_impl(cx, pat, map); } if let Some(ref mid) = *mid { bindings_impl(cx, mid, map); } for pat in rhs { bindings_impl(cx, pat, map); } }, PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (), } } let mut result = FxHashMap::default(); bindings_impl(cx, pat, &mut result); result } fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)> where Eq: Fn(&T, &T) -> bool, { for win in exprs.windows(2) { if eq(&win[0], &win[1]) { return Some((&win[0], &win[1])); } } None } fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)> where Eq: Fn(&T, &T) -> bool, { if exprs.len() < 2 { None } else if exprs.len() == 2 { if eq(&exprs[0], &exprs[1]) { Some((&exprs[0], &exprs[1])) } else { None } } else { None } } fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)> where Hash: Fn(&T) -> u64, Eq: Fn(&T, &T) -> bool, { if let Some(expr) = search_common_cases(&exprs, &eq) { return vec![expr]; } let mut match_expr_list: Vec<(&T, &T)> = Vec::new(); let mut map: FxHashMap<_, Vec<&_>> = FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default()); for expr in exprs { match map.entry(hash(expr)) { Entry::Occupied(mut o) => { for o in o.get() { if eq(o, expr) { match_expr_list.push((o, expr)); } } o.get_mut().push(expr); }, Entry::Vacant(v) => { v.insert(vec![expr]); }, } } match_expr_list }
use crate::utils::{get_parent_expr, higher, in_macro_or_desugar, snippet, span_lint_and_then, span_note_and_lint}; use crate::utils::{SpanlessEq, SpanlessHash}; use rustc::hir::*; use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; use rustc::ty::Ty; use rustc::{declare_lint_pass, declare_tool_lint}; use rustc_data_structures::fx::FxHashMap; use smallvec::SmallVec; use std::collections::hash_map::Entry; use std::hash::BuildHasherDefault; use syntax::symbol::LocalInternedString; declare_clippy_lint! { pub IFS_SAME_COND, correctness, "consecutive `ifs` with the same condition" } declare_clippy_lint! { pub IF_SAME_THEN_ELSE, correctness, "if with the same *then* and *else* blocks" } declare_clippy_lint! { pub MATCH_SAME_ARMS, pedantic, "`match` with identical arm bodies" } declare_lint_pass!(CopyAndPaste => [IFS_SAME_COND, IF_SAME_THEN_ELSE, MATCH_SAME_ARMS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CopyAndPaste { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { if !in_macro_or_desugar(expr.span) { if let Some(expr) = get_parent_expr(cx, expr) { if let Some((_, _, Some(ref else_expr))) = higher::if_block(&expr) { if else_expr.hir_id == expr.hir_id { return; } } } let (conds, blocks) = if_sequence(expr); lint_same_then_else(cx, &blocks); lint_same_cond(cx, &conds); lint_match_arms(cx, expr); } } } fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block]) { let eq: &dyn Fn(&&Block, &&Block) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).eq_block(lhs, rhs) }; if let Some((i, j)) = search_same_sequenced(blocks, eq) { span_note_and_lint( cx, IF_SAME_THEN_ELSE, j.span, "this `if` has identical blocks", i.span, "same as this", ); } } fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr]) { let hash: &dyn Fn(&&Expr) -> u64 = &|expr| -> u64 { let mut h = SpanlessHash::new(cx, cx.tables); h.hash_expr(expr); h.finish() }; let eq: &dyn Fn(&&Expr, &&Expr) -> bool = &|&lhs, &rhs| -> bool { SpanlessEq::new(cx).ignore_fn().eq_expr(lhs, rhs) }; for (i, j) in search_same(conds, hash, eq) { span_note_and_lint( cx, IFS_SAME_COND, j.span, "this `if` has the same condition as a previous if", i.span, "same as this", ); } } fn lint_match_arms(cx: &LateContext<'_, '_>, expr: &Expr) { if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.node { let hash = |&(_, arm): &(usize, &Arm)| -> u64 { let mut h = SpanlessHash::new(cx, cx.tables); h.hash_expr(&arm.body); h.finish() }; let eq = |&(lindex, lhs): &(usize, &Arm), &(rindex, rhs): &(usize, &Arm)| -> bool { let min_index = usize::min(lindex, rindex); let max_index = usize::max(lindex, rindex); (min_index..=max_index).all(|index| arms[index].guard.is_none()) && SpanlessEq::new(cx).eq_expr(&lhs.body, &rhs.body) && bindings(cx, &lhs.pats[0]) == bindings(cx, &rhs.pats[0]) }; let indexed_arms: Vec<(usize, &Arm)> = arms.iter().enumerate().collect(); for (&(_, i), &(_, j)) in search_same(&indexed_arms, hash, eq) { span_lint_and_then( cx, MATCH_SAME_ARMS, j.body.span, "this `match` has identical arm bodies", |db| { db.span_note(i.body.span, "same as this"); if i.pats.len() == 1 && j.pats.len() == 1 { let lhs = snippet(cx, i.pats[0].span, "<pat1>"); let rhs = snippet(cx, j.pats[0].span, "<pat2>"); if let PatKind::Wild = j.pats[0].node {
:default(); bindings_impl(cx, pat, &mut result); result } fn search_same_sequenced<T, Eq>(exprs: &[T], eq: Eq) -> Option<(&T, &T)> where Eq: Fn(&T, &T) -> bool, { for win in exprs.windows(2) { if eq(&win[0], &win[1]) { return Some((&win[0], &win[1])); } } None } fn search_common_cases<'a, T, Eq>(exprs: &'a [T], eq: &Eq) -> Option<(&'a T, &'a T)> where Eq: Fn(&T, &T) -> bool, { if exprs.len() < 2 { None } else if exprs.len() == 2 { if eq(&exprs[0], &exprs[1]) { Some((&exprs[0], &exprs[1])) } else { None } } else { None } } fn search_same<T, Hash, Eq>(exprs: &[T], hash: Hash, eq: Eq) -> Vec<(&T, &T)> where Hash: Fn(&T) -> u64, Eq: Fn(&T, &T) -> bool, { if let Some(expr) = search_common_cases(&exprs, &eq) { return vec![expr]; } let mut match_expr_list: Vec<(&T, &T)> = Vec::new(); let mut map: FxHashMap<_, Vec<&_>> = FxHashMap::with_capacity_and_hasher(exprs.len(), BuildHasherDefault::default()); for expr in exprs { match map.entry(hash(expr)) { Entry::Occupied(mut o) => { for o in o.get() { if eq(o, expr) { match_expr_list.push((o, expr)); } } o.get_mut().push(expr); }, Entry::Vacant(v) => { v.insert(vec![expr]); }, } } match_expr_list }
db.span_note( i.body.span, &format!( "`{}` has the same arm body as the `_` wildcard, consider removing it`", lhs ), ); } else { db.span_help( i.pats[0].span, &format!("consider refactoring into `{} | {}`", lhs, rhs), ); } } }, ); } } } fn if_sequence(mut expr: &Expr) -> (SmallVec<[&Expr; 1]>, SmallVec<[&Block; 1]>) { let mut conds = SmallVec::new(); let mut blocks: SmallVec<[&Block; 1]> = SmallVec::new(); while let Some((ref cond, ref then_expr, ref else_expr)) = higher::if_block(&expr) { conds.push(&**cond); if let ExprKind::Block(ref block, _) = then_expr.node { blocks.push(block); } else { panic!("ExprKind::If node is not an ExprKind::Block"); } if let Some(ref else_expr) = *else_expr { expr = else_expr; } else { break; } } if !blocks.is_empty() { if let ExprKind::Block(ref block, _) = expr.node { blocks.push(&**block); } } (conds, blocks) } fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat) -> FxHashMap<LocalInternedString, Ty<'tcx>> { fn bindings_impl<'a, 'tcx>( cx: &LateContext<'a, 'tcx>, pat: &Pat, map: &mut FxHashMap<LocalInternedString, Ty<'tcx>>, ) { match pat.node { PatKind::Box(ref pat) | PatKind::Ref(ref pat, _) => bindings_impl(cx, pat, map), PatKind::TupleStruct(_, ref pats, _) => { for pat in pats { bindings_impl(cx, pat, map); } }, PatKind::Binding(.., ident, ref as_pat) => { if let Entry::Vacant(v) = map.entry(ident.as_str()) { v.insert(cx.tables.pat_ty(pat)); } if let Some(ref as_pat) = *as_pat { bindings_impl(cx, as_pat, map); } }, PatKind::Struct(_, ref fields, _) => { for pat in fields { bindings_impl(cx, &pat.node.pat, map); } }, PatKind::Tuple(ref fields, _) => { for pat in fields { bindings_impl(cx, pat, map); } }, PatKind::Slice(ref lhs, ref mid, ref rhs) => { for pat in lhs { bindings_impl(cx, pat, map); } if let Some(ref mid) = *mid { bindings_impl(cx, mid, map); } for pat in rhs { bindings_impl(cx, pat, map); } }, PatKind::Lit(..) | PatKind::Range(..) | PatKind::Wild | PatKind::Path(..) => (), } } let mut result = FxHashMap:
random
[ { "content": "fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr, arms: &[Arm], expr: &Expr) {\n\n if arms.len() == 2\n\n && arms[0].pats.len() == 1\n\n && arms[0].guard.is_none()\n\n && arms[1].pats.len() == 1\n\n && arms[1].guard.is_none()\n\n {\n\n let arm_ref:...
Rust
types/src/unit_tests/canonical_serialization_examples.rs
egabrielsen/libra
773b9142b12504eabd28ce135dd2de4ee7e54126
use crate::{ access_path::AccessPath, account_address::AccountAddress, account_config::lbr_type_tag, transaction::{ChangeSet, RawTransaction, Script, TransactionArgument, TransactionPayload}, write_set::{WriteOp, WriteSet, WriteSetMut}, }; use lcs::to_bytes; use std::time::Duration; #[test] fn test_access_path_canonical_serialization_example() { let account_address = AccountAddress::new([ 0x9a, 0x1a, 0xd0, 0x97, 0x42, 0xd1, 0xff, 0xc6, 0x2e, 0x65, 0x9e, 0x9a, 0x77, 0x97, 0x80, 0x8b, ]); let input = AccessPath::new( account_address, vec![ 0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18, 0x25, 0xcf, 0xb2, 0x67, 0x6d, 0xae, 0xcc, 0xe3, 0xbf, 0x3d, 0xe0, 0x3c, 0xf2, 0x66, 0x47, 0xc7, 0x8d, 0xf0, 0x0b, 0x37, 0x1b, 0x25, 0xcc, 0x97, ], ); let expected_output = vec![ 0x9A, 0x1A, 0xD0, 0x97, 0x42, 0xD1, 0xFF, 0xC6, 0x2E, 0x65, 0x9E, 0x9A, 0x77, 0x97, 0x80, 0x8B, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_account_address_canonical_serialization_example() { let input = AccountAddress::new([ 0xca, 0x82, 0x0b, 0xf9, 0x30, 0x5e, 0xb9, 0x7d, 0x0d, 0x78, 0x4f, 0x71, 0xb3, 0x95, 0x54, 0x57, ]); let expected_output: Vec<u8> = vec![ 0xCA, 0x82, 0x0B, 0xF9, 0x30, 0x5E, 0xB9, 0x7D, 0x0D, 0x78, 0x4F, 0x71, 0xB3, 0x95, 0x54, 0x57, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_program_canonical_serialization_example() { let input = get_common_program(); let expected_output: Vec<u8> = vec![ 0x04, 0x6D, 0x6F, 0x76, 0x65, 0x01, 0x00, 0xEF, 0xBE, 0xAD, 0xDE, 0x0D, 0xD0, 0xFE, 0xCA, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_raw_transaction_with_a_program_canonical_serialization_example() { let input = RawTransaction::new_script( AccountAddress::new([ 0x3a, 0x24, 0xa6, 0x1e, 0x05, 0xd1, 0x29, 0xca, 0xce, 0x9e, 0x0e, 0xfc, 0x8b, 0xc9, 0xe3, 0x38, ]), 32, get_common_program(), 10000, 20000, lbr_type_tag(), Duration::from_secs(86400), ); let expected_output = vec![ 58, 36, 166, 30, 5, 209, 41, 202, 206, 158, 14, 252, 139, 201, 227, 56, 32, 0, 0, 0, 0, 0, 0, 0, 2, 4, 109, 111, 118, 101, 1, 0, 239, 190, 173, 222, 13, 208, 254, 202, 16, 39, 0, 0, 0, 0, 0, 0, 32, 78, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 76, 66, 82, 1, 84, 0, 128, 81, 1, 0, 0, 0, 0, 0, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_raw_transaction_with_a_write_set_canonical_serialization_example() { let input = RawTransaction::new_write_set( AccountAddress::new([ 0xc3, 0x39, 0x8a, 0x59, 0x9a, 0x6f, 0x3b, 0x9f, 0x30, 0xb6, 0x35, 0xaf, 0x29, 0xf2, 0xba, 0x04, ]), 32, get_common_write_set(), ); let expected_output = vec![ 195, 57, 138, 89, 154, 111, 59, 159, 48, 182, 53, 175, 41, 242, 186, 4, 32, 0, 0, 0, 0, 0, 0, 0, 1, 2, 167, 29, 118, 250, 162, 210, 213, 195, 34, 78, 195, 212, 29, 235, 41, 57, 33, 1, 33, 125, 166, 198, 179, 225, 159, 24, 37, 207, 178, 103, 109, 174, 204, 227, 191, 61, 224, 60, 242, 102, 71, 199, 141, 240, 11, 55, 27, 37, 204, 151, 0, 196, 198, 63, 128, 199, 75, 17, 38, 62, 66, 30, 191, 132, 134, 164, 227, 9, 1, 33, 125, 166, 198, 179, 225, 159, 24, 1, 4, 202, 254, 208, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 76, 66, 82, 1, 84, 0, 255, 255, 255, 255, 255, 255, 255, 255, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_address_canonical_serialization_example() { let input = TransactionArgument::Address(AccountAddress::new([ 0x2c, 0x25, 0x99, 0x17, 0x85, 0x34, 0x3b, 0x23, 0xae, 0x07, 0x3a, 0x50, 0xe5, 0xfd, 0x80, 0x9a, ])); let expected_output: Vec<u8> = vec![ 0x01, 0x2C, 0x25, 0x99, 0x17, 0x85, 0x34, 0x3B, 0x23, 0xAE, 0x07, 0x3A, 0x50, 0xE5, 0xFD, 0x80, 0x9A, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_byte_array_canonical_serialization_example() { let input = TransactionArgument::U8Vector(vec![0xCA, 0xFE, 0xD0, 0x0D]); let expected_output: Vec<u8> = vec![0x02, 0x04, 0xCA, 0xFE, 0xD0, 0x0D]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_u64_canonical_serialization_example() { let input = TransactionArgument::U64(9_213_671_392_124_193_148); let expected_output: Vec<u8> = vec![0x00, 0x7C, 0xC9, 0xBD, 0xA4, 0x50, 0x89, 0xDD, 0x7F]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_payload_with_a_program_canonical_serialization_example() { let input = TransactionPayload::Script(get_common_program()); let expected_output = vec![ 0x02, 0x04, 0x6D, 0x6F, 0x76, 0x65, 0x01, 0x00, 0xEF, 0xBE, 0xAD, 0xDE, 0x0D, 0xD0, 0xFE, 0xCA, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_payload_with_a_write_set_canonical_serialization_example() { let input = TransactionPayload::WriteSet(ChangeSet::new(get_common_write_set(), vec![])); let expected_output = vec![ 0x01, 0x02, 0xA7, 0x1D, 0x76, 0xFA, 0xA2, 0xD2, 0xD5, 0xC3, 0x22, 0x4E, 0xC3, 0xD4, 0x1D, 0xEB, 0x29, 0x39, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, 0x00, 0xC4, 0xC6, 0x3F, 0x80, 0xC7, 0x4B, 0x11, 0x26, 0x3E, 0x42, 0x1E, 0xBF, 0x84, 0x86, 0xA4, 0xE3, 0x09, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D, 0x00, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_write_op_delete_canonical_serialization_example() { let input = WriteOp::Deletion; let expected_output = vec![0x00]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_write_op_value_canonical_serialization_example() { let input = WriteOp::Value(vec![0xca, 0xfe, 0xd0, 0x0d]); let expected_output = vec![0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_write_set_canonical_serialization_example() { let input = get_common_write_set(); let expected_output = vec![ 0x02, 0xA7, 0x1D, 0x76, 0xFA, 0xA2, 0xD2, 0xD5, 0xC3, 0x22, 0x4E, 0xC3, 0xD4, 0x1D, 0xEB, 0x29, 0x39, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, 0x00, 0xC4, 0xC6, 0x3F, 0x80, 0xC7, 0x4B, 0x11, 0x26, 0x3E, 0x42, 0x1E, 0xBF, 0x84, 0x86, 0xA4, 0xE3, 0x09, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } fn get_common_program() -> Script { Script::new( b"move".to_vec(), vec![TransactionArgument::U64(0xcafe_d00d_dead_beef)], ) } fn get_common_write_set() -> WriteSet { WriteSetMut::new(vec![ ( AccessPath::new( AccountAddress::new([ 0xa7, 0x1d, 0x76, 0xfa, 0xa2, 0xd2, 0xd5, 0xc3, 0x22, 0x4e, 0xc3, 0xd4, 0x1d, 0xeb, 0x29, 0x39, ]), vec![ 0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18, 0x25, 0xcf, 0xb2, 0x67, 0x6d, 0xae, 0xcc, 0xe3, 0xbf, 0x3d, 0xe0, 0x3c, 0xf2, 0x66, 0x47, 0xc7, 0x8d, 0xf0, 0x0b, 0x37, 0x1b, 0x25, 0xcc, 0x97, ], ), WriteOp::Deletion, ), ( AccessPath::new( AccountAddress::new([ 0xc4, 0xc6, 0x3f, 0x80, 0xc7, 0x4b, 0x11, 0x26, 0x3e, 0x42, 0x1e, 0xbf, 0x84, 0x86, 0xa4, 0xe3, ]), vec![0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18], ), WriteOp::Value(vec![0xca, 0xfe, 0xd0, 0x0d]), ), ]) .freeze() .unwrap() }
use crate::{ access_path::AccessPath, account_address::AccountAddress, account_config::lbr_type_tag, transaction::{ChangeSet, RawTransaction, Script, TransactionArgument, TransactionPayload}, write_set::{WriteOp, WriteSet, WriteSetMut}, }; use lcs::to_bytes; use std::time::Duration; #[test] fn test_access_path_canonical_serialization_example() { let account_address = AccountAddress::new([ 0x9a, 0x1a, 0xd0, 0x97, 0x42, 0xd1, 0xff, 0xc6, 0x2e, 0x65, 0x9e, 0x9a, 0x77, 0x97, 0x80, 0x8b, ]); let input = AccessPath::new( account_address, vec![ 0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18, 0x25, 0xcf, 0xb2, 0x67, 0x6d, 0xae, 0xcc, 0xe3, 0xbf, 0x3d, 0xe0, 0x3c, 0xf2, 0x66, 0x47, 0xc7, 0x8d, 0xf0, 0x0b, 0x37, 0x1b, 0x25, 0xcc, 0x97, ], ); let expected_output = vec![ 0x9A, 0x1A, 0xD0, 0x97, 0x42, 0xD1, 0xFF, 0xC6, 0x2E, 0x65, 0x9E, 0x9A, 0x77, 0x97, 0x80, 0x8B, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_account_address_canonical_serialization_example() { let input = AccountAddress::new([ 0xca, 0x82, 0x0b, 0xf9, 0x30, 0x5e, 0xb9, 0x7d, 0x0d, 0x78, 0x4f, 0x71, 0xb3, 0x95, 0x54, 0x57, ]); let expected_output: Vec<u8> = vec![ 0xCA, 0x82, 0x0B, 0xF9, 0x30, 0x5E, 0xB9, 0x7D, 0x0D, 0x78, 0x4F, 0x71, 0xB3, 0x95, 0x54, 0x57, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_program_canonical_serialization_example() { let input = get_common_program(); let expected_output: Vec<u8> = vec![ 0x04, 0x6D, 0x6F, 0x76, 0x65, 0x01, 0x00, 0xEF, 0xBE, 0xAD, 0xDE, 0x0D, 0xD0, 0xFE, 0xCA, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_raw_transaction_with_a_program_canonical_serialization_example() { let input = RawTransaction::new_script( AccountAddress::new([ 0x3a, 0x24, 0xa6, 0x1e, 0x05, 0xd1, 0x29, 0xca, 0xce, 0x9e, 0x0e, 0xfc, 0x8b, 0xc9, 0xe3, 0x38, ]), 32, get_common_program(), 10000, 20000, lbr_type_tag(), Duration::from_secs(86400), ); let expected_output = vec![ 58, 36, 166, 30, 5, 209, 41, 202, 206, 158, 14, 252, 139, 201, 227, 56, 32, 0, 0, 0, 0, 0, 0, 0, 2, 4, 109, 111, 118, 101, 1, 0, 239, 190, 173, 222, 13, 208, 254, 202, 16, 39, 0, 0, 0, 0, 0, 0, 32, 78, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 76, 66, 82, 1, 84, 0, 128, 81, 1, 0, 0, 0, 0, 0, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_raw_transaction_with_a_write_set_canonical_serialization_example() { let input = RawTransaction::new_write_set( AccountAddress::new([ 0xc3, 0x39, 0x8a, 0x59, 0x9a, 0x6f, 0x3b, 0x9f, 0x30, 0xb6, 0x35, 0xaf, 0x29, 0xf2, 0xba, 0x04, ]), 32, get_common_write_set(), ); let expected_output = vec![ 195, 57, 138, 89, 154, 111, 59, 159, 48, 182, 53, 175, 41, 242, 186, 4, 32, 0, 0, 0, 0, 0, 0, 0, 1, 2, 167, 29, 118, 250, 162, 210, 213, 195, 34, 78, 195, 212, 29, 235, 41, 57, 33, 1, 33, 125, 166, 198, 179, 225, 159, 24, 37, 207, 178, 103, 109, 174, 204, 227, 191, 61, 224, 60, 242, 102, 71, 199, 141, 240, 11, 55, 27, 37, 204, 151, 0, 196, 198, 63, 128, 199, 75, 17, 38, 62, 66, 30, 191, 132, 134, 164, 227, 9, 1, 33, 125, 166, 198, 179, 225, 159, 24, 1, 4, 202, 254, 208, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 76, 66, 82, 1, 84, 0, 255, 255, 255, 255, 255, 255, 255, 255, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_address_canonical_serialization_example() { let input = TransactionArgument::Address(AccountAddress::new([ 0x2c, 0x25, 0x99, 0x17, 0x85, 0x34, 0x3b, 0x23, 0xae, 0x07, 0x3a, 0x50, 0xe5, 0xfd, 0x80, 0x9a, ])); let expected_output: Vec<u8> = vec![ 0x01, 0x2C, 0x25, 0x99, 0x17, 0x85, 0x34, 0x3B, 0x23, 0xAE, 0x07, 0x3A, 0x50, 0xE5, 0xFD, 0x80, 0x9A, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_byte_array_canonical_serialization_example() { let input = TransactionArgument::U8Vector(vec![0xCA, 0xFE, 0xD0, 0x0D]); let expected_output: Vec<u8> = vec![0x02, 0x04, 0xCA, 0xFE, 0xD0, 0x0D]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_argument_u64_canonical_serialization_example() { let input = TransactionArgument::U64(9_213_671_392_124_193_148); let expected_output: Vec<u8> = vec![0x00, 0x7C, 0xC9, 0xBD, 0xA4, 0x50, 0x89, 0xDD, 0x7F]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_payload_with_a_program_canonical_serialization_example() { let input = TransactionPayload::Script(get_common_program()); let expected_output = vec![ 0x02, 0x04, 0x6D, 0x6F, 0x76, 0x65, 0x01, 0x00, 0xEF, 0xBE, 0xAD, 0xDE, 0x0D, 0xD0, 0xFE, 0xCA, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_transaction_payload_with_a_write_set_canonical_serialization_example() { let input = TransactionPayload::WriteSet(ChangeSet::new(get_common_write_set(), vec![])); let expected_output = vec![ 0x01, 0x02, 0xA7, 0x1D, 0x76, 0xFA, 0xA2, 0xD2, 0xD5, 0xC3, 0x22, 0x4E, 0xC3, 0xD4, 0x1D, 0xEB, 0x29, 0x39, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, 0x00, 0xC4, 0xC6, 0x3F, 0x80, 0xC7, 0x4B, 0x11, 0x26, 0x3E, 0x42, 0x1E, 0xBF, 0x84, 0x86, 0xA4, 0xE3, 0x09, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D, 0x00, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test] fn test_write_op_delete_canonical_serialization_example() { let input = WriteOp::Deletion; let expected_output = vec![0x00]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } #[test]
#[test] fn test_write_set_canonical_serialization_example() { let input = get_common_write_set(); let expected_output = vec![ 0x02, 0xA7, 0x1D, 0x76, 0xFA, 0xA2, 0xD2, 0xD5, 0xC3, 0x22, 0x4E, 0xC3, 0xD4, 0x1D, 0xEB, 0x29, 0x39, 0x21, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x25, 0xCF, 0xB2, 0x67, 0x6D, 0xAE, 0xCC, 0xE3, 0xBF, 0x3D, 0xE0, 0x3C, 0xF2, 0x66, 0x47, 0xC7, 0x8D, 0xF0, 0x0B, 0x37, 0x1B, 0x25, 0xCC, 0x97, 0x00, 0xC4, 0xC6, 0x3F, 0x80, 0xC7, 0x4B, 0x11, 0x26, 0x3E, 0x42, 0x1E, 0xBF, 0x84, 0x86, 0xA4, 0xE3, 0x09, 0x01, 0x21, 0x7D, 0xA6, 0xC6, 0xB3, 0xE1, 0x9F, 0x18, 0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D, ]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); } fn get_common_program() -> Script { Script::new( b"move".to_vec(), vec![TransactionArgument::U64(0xcafe_d00d_dead_beef)], ) } fn get_common_write_set() -> WriteSet { WriteSetMut::new(vec![ ( AccessPath::new( AccountAddress::new([ 0xa7, 0x1d, 0x76, 0xfa, 0xa2, 0xd2, 0xd5, 0xc3, 0x22, 0x4e, 0xc3, 0xd4, 0x1d, 0xeb, 0x29, 0x39, ]), vec![ 0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18, 0x25, 0xcf, 0xb2, 0x67, 0x6d, 0xae, 0xcc, 0xe3, 0xbf, 0x3d, 0xe0, 0x3c, 0xf2, 0x66, 0x47, 0xc7, 0x8d, 0xf0, 0x0b, 0x37, 0x1b, 0x25, 0xcc, 0x97, ], ), WriteOp::Deletion, ), ( AccessPath::new( AccountAddress::new([ 0xc4, 0xc6, 0x3f, 0x80, 0xc7, 0x4b, 0x11, 0x26, 0x3e, 0x42, 0x1e, 0xbf, 0x84, 0x86, 0xa4, 0xe3, ]), vec![0x01, 0x21, 0x7d, 0xa6, 0xc6, 0xb3, 0xe1, 0x9f, 0x18], ), WriteOp::Value(vec![0xca, 0xfe, 0xd0, 0x0d]), ), ]) .freeze() .unwrap() }
fn test_write_op_value_canonical_serialization_example() { let input = WriteOp::Value(vec![0xca, 0xfe, 0xd0, 0x0d]); let expected_output = vec![0x01, 0x04, 0xCA, 0xFE, 0xD0, 0x0D]; let actual_output = to_bytes(&input).unwrap(); assert_eq!(expected_output, actual_output); }
function_block-full_function
[ { "content": "fn test_save_blocks_impl(input: Vec<(Vec<TransactionToCommit>, LedgerInfoWithSignatures)>) {\n\n let tmp_dir = TempPath::new();\n\n let db = LibraDB::new(&tmp_dir);\n\n\n\n let num_batches = input.len();\n\n let mut cur_ver = 0;\n\n for (batch_idx, (txns_to_commit, ledger_info_with_...
Rust
tokio-tls/src/lib.rs
swarmer/tokio
c15e01a09bd2a3f9ac8e720069ee4ecfc8a4815a
#![doc(html_root_url = "https://docs.rs/tokio-tls/0.3.0-alpha.6")] #![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] #![deny(intra_doc_link_resolution_failure)] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables)) ))] use tokio::io::{AsyncRead, AsyncWrite}; use native_tls::{Error, HandshakeError, MidHandshakeTlsStream}; use std::fmt; use std::future::Future; use std::io::{self, Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::ptr::null_mut; use std::task::{Context, Poll}; #[derive(Debug)] struct AllowStd<S> { inner: S, context: *mut (), } #[derive(Debug)] pub struct TlsStream<S>(native_tls::TlsStream<AllowStd<S>>); #[derive(Clone)] pub struct TlsConnector(native_tls::TlsConnector); #[derive(Clone)] pub struct TlsAcceptor(native_tls::TlsAcceptor); struct MidHandshake<S>(Option<MidHandshakeTlsStream<AllowStd<S>>>); enum StartedHandshake<S> { Done(TlsStream<S>), Mid(MidHandshakeTlsStream<AllowStd<S>>), } struct StartedHandshakeFuture<F, S>(Option<StartedHandshakeFutureInner<F, S>>); struct StartedHandshakeFutureInner<F, S> { f: F, stream: S, } struct Guard<'a, S>(&'a mut TlsStream<S>) where AllowStd<S>: Read + Write; impl<S> Drop for Guard<'_, S> where AllowStd<S>: Read + Write, { fn drop(&mut self) { (self.0).0.get_mut().context = null_mut(); } } unsafe impl<S: Send> Send for AllowStd<S> {} unsafe impl<S: Sync> Sync for AllowStd<S> {} impl<S> AllowStd<S> where S: Unpin, { fn with_context<F, R>(&mut self, f: F) -> R where F: FnOnce(&mut Context<'_>, Pin<&mut S>) -> R, { unsafe { assert!(!self.context.is_null()); let waker = &mut *(self.context as *mut _); f(waker, Pin::new(&mut self.inner)) } } } impl<S> Read for AllowStd<S> where S: AsyncRead + Unpin, { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.with_context(|ctx, stream| stream.poll_read(ctx, buf)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } impl<S> Write for AllowStd<S> where S: AsyncWrite + Unpin, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match self.with_context(|ctx, stream| stream.poll_write(ctx, buf)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } fn flush(&mut self) -> io::Result<()> { match self.with_context(|ctx, stream| stream.poll_flush(ctx)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } fn cvt<T>(r: io::Result<T>) -> Poll<io::Result<T>> { match r { Ok(v) => Poll::Ready(Ok(v)), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } impl<S> TlsStream<S> { fn with_context<F, R>(&mut self, ctx: &mut Context<'_>, f: F) -> R where F: FnOnce(&mut native_tls::TlsStream<AllowStd<S>>) -> R, AllowStd<S>: Read + Write, { self.0.get_mut().context = ctx as *mut _ as *mut (); let g = Guard(self); f(&mut (g.0).0) } pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, { &self.0.get_ref().inner } pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, { &mut self.0.get_mut().inner } } impl<S> AsyncRead for TlsStream<S> where S: AsyncRead + AsyncWrite + Unpin, { unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool { false } fn poll_read( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { self.with_context(ctx, |s| cvt(s.read(buf))) } } impl<S> AsyncWrite for TlsStream<S> where S: AsyncRead + AsyncWrite + Unpin, { fn poll_write( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.with_context(ctx, |s| cvt(s.write(buf))) } fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { self.with_context(ctx, |s| cvt(s.flush())) } fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { match self.with_context(ctx, |s| s.shutdown()) { Ok(()) => Poll::Ready(Ok(())), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } } async fn handshake<F, S>(f: F, stream: S) -> Result<TlsStream<S>, Error> where F: FnOnce( AllowStd<S>, ) -> Result<native_tls::TlsStream<AllowStd<S>>, HandshakeError<AllowStd<S>>> + Unpin, S: AsyncRead + AsyncWrite + Unpin, { let start = StartedHandshakeFuture(Some(StartedHandshakeFutureInner { f, stream })); match start.await { Err(e) => Err(e), Ok(StartedHandshake::Done(s)) => Ok(s), Ok(StartedHandshake::Mid(s)) => MidHandshake(Some(s)).await, } } impl<F, S> Future for StartedHandshakeFuture<F, S> where F: FnOnce( AllowStd<S>, ) -> Result<native_tls::TlsStream<AllowStd<S>>, HandshakeError<AllowStd<S>>> + Unpin, S: Unpin, AllowStd<S>: Read + Write, { type Output = Result<StartedHandshake<S>, Error>; fn poll( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<StartedHandshake<S>, Error>> { let inner = self.0.take().expect("future polled after completion"); let stream = AllowStd { inner: inner.stream, context: ctx as *mut _ as *mut (), }; match (inner.f)(stream) { Ok(mut s) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Done(TlsStream(s)))) } Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Mid(s))) } Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), } } } impl TlsConnector { pub async fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, Error> where S: AsyncRead + AsyncWrite + Unpin, { handshake(move |s| self.0.connect(domain, s), stream).await } } impl fmt::Debug for TlsConnector { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsConnector").finish() } } impl From<native_tls::TlsConnector> for TlsConnector { fn from(inner: native_tls::TlsConnector) -> TlsConnector { TlsConnector(inner) } } impl TlsAcceptor { pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, Error> where S: AsyncRead + AsyncWrite + Unpin, { handshake(move |s| self.0.accept(s), stream).await } } impl fmt::Debug for TlsAcceptor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsAcceptor").finish() } } impl From<native_tls::TlsAcceptor> for TlsAcceptor { fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor { TlsAcceptor(inner) } } impl<S: AsyncRead + AsyncWrite + Unpin> Future for MidHandshake<S> { type Output = Result<TlsStream<S>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut_self = self.get_mut(); let mut s = mut_self.0.take().expect("future polled after completion"); s.get_mut().context = cx as *mut _ as *mut (); match s.handshake() { Ok(stream) => Poll::Ready(Ok(TlsStream(stream))), Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); mut_self.0 = Some(s); Poll::Pending } } } }
#![doc(html_root_url = "https://docs.rs/tokio-tls/0.3.0-alpha.6")] #![warn( missing_debug_implementations, missing_docs, rust_2018_idioms, unreachable_pub )] #![deny(intra_doc_link_resolution_failure)] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables)) ))] use tokio::io::{AsyncRead, AsyncWrite}; use native_tls::{Error, HandshakeError, MidHandshakeTlsStream}; use std::fmt; use std::future::Future; use std::io::{self, Read, Write}; use std::marker::Unpin; use std::pin::Pin; use std::ptr::null_mut; use std::task::{Context, Poll}; #[derive(Debug)] struct AllowStd<S> { inner: S, context: *mut (), } #[derive(Debug)] pub struct TlsStream<S>(native_tls::TlsStream<AllowStd<S>>); #[derive(Clone)] pub struct TlsConnector(native_tls::TlsConnector); #[derive(Clone)] pub struct TlsAcceptor(native_tls::TlsAcceptor); struct MidHandshake<S>(Option<MidHandshakeTlsStream<AllowStd<S>>>); enum StartedHandshake<S> { Done(TlsStream<S>), Mid(MidHandshakeTlsStream<AllowStd<S>>), } struct StartedHandshakeFuture<F, S>(Option<StartedHandshakeFutureInner<F, S>>); struct StartedHandshakeFutureInner<F, S> { f: F, stream: S, } struct Guard<'a, S>(&'a mut TlsStream<S>) where AllowStd<S>: Read + Write; impl<S> Drop for Guard<'_, S> where AllowStd<S>: Read + Write, { fn drop(&mut self) { (self.0).0.get_mut().context = null_mut(); } } unsafe impl<S: Send> Send for AllowStd<S> {} unsafe impl<S: Sync> Sync for AllowStd<S> {} impl<S> AllowStd<S> where S: Unpin, { fn with_context<F, R>(&mut self, f: F) -> R where F: FnOnce(&mut Context<'_>, Pin<&mut S>) -> R, { unsafe { assert!(!self.context.is_null()); let waker = &mut *(self.context as *mut _); f(waker, Pin::new(&mut self.inner)) } } } impl<S> Read for AllowStd<S> where S: AsyncRead + Unpin, { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self.with_context(|ctx, stream| stream.poll_read(ctx, buf)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } impl<S> Write for AllowStd<S> where S: AsyncWrite + Unpin, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { match self.with_context(|ctx, stream| stream.poll_write(ctx, buf)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } fn flush(&mut self) -> io::Result<()> { match self.with_context(|ctx, stream| stream.poll_flush(ctx)) { Poll::Ready(r) => r, Poll::Pending => Err(io::Error::from(io::ErrorKind::WouldBlock)), } } } fn cvt<T>(r: io::Result<T>) -> Poll<io::Result<T>> { match r { Ok(v) => Poll::Ready(Ok(v)), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } impl<S> TlsStream<S> { fn with_context<F, R>(&mut self, ct
pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, { &self.0.get_ref().inner } pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, { &mut self.0.get_mut().inner } } impl<S> AsyncRead for TlsStream<S> where S: AsyncRead + AsyncWrite + Unpin, { unsafe fn prepare_uninitialized_buffer(&self, _: &mut [u8]) -> bool { false } fn poll_read( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { self.with_context(ctx, |s| cvt(s.read(buf))) } } impl<S> AsyncWrite for TlsStream<S> where S: AsyncRead + AsyncWrite + Unpin, { fn poll_write( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.with_context(ctx, |s| cvt(s.write(buf))) } fn poll_flush(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { self.with_context(ctx, |s| cvt(s.flush())) } fn poll_shutdown(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> { match self.with_context(ctx, |s| s.shutdown()) { Ok(()) => Poll::Ready(Ok(())), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Poll::Pending, Err(e) => Poll::Ready(Err(e)), } } } async fn handshake<F, S>(f: F, stream: S) -> Result<TlsStream<S>, Error> where F: FnOnce( AllowStd<S>, ) -> Result<native_tls::TlsStream<AllowStd<S>>, HandshakeError<AllowStd<S>>> + Unpin, S: AsyncRead + AsyncWrite + Unpin, { let start = StartedHandshakeFuture(Some(StartedHandshakeFutureInner { f, stream })); match start.await { Err(e) => Err(e), Ok(StartedHandshake::Done(s)) => Ok(s), Ok(StartedHandshake::Mid(s)) => MidHandshake(Some(s)).await, } } impl<F, S> Future for StartedHandshakeFuture<F, S> where F: FnOnce( AllowStd<S>, ) -> Result<native_tls::TlsStream<AllowStd<S>>, HandshakeError<AllowStd<S>>> + Unpin, S: Unpin, AllowStd<S>: Read + Write, { type Output = Result<StartedHandshake<S>, Error>; fn poll( mut self: Pin<&mut Self>, ctx: &mut Context<'_>, ) -> Poll<Result<StartedHandshake<S>, Error>> { let inner = self.0.take().expect("future polled after completion"); let stream = AllowStd { inner: inner.stream, context: ctx as *mut _ as *mut (), }; match (inner.f)(stream) { Ok(mut s) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Done(TlsStream(s)))) } Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); Poll::Ready(Ok(StartedHandshake::Mid(s))) } Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), } } } impl TlsConnector { pub async fn connect<S>(&self, domain: &str, stream: S) -> Result<TlsStream<S>, Error> where S: AsyncRead + AsyncWrite + Unpin, { handshake(move |s| self.0.connect(domain, s), stream).await } } impl fmt::Debug for TlsConnector { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsConnector").finish() } } impl From<native_tls::TlsConnector> for TlsConnector { fn from(inner: native_tls::TlsConnector) -> TlsConnector { TlsConnector(inner) } } impl TlsAcceptor { pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, Error> where S: AsyncRead + AsyncWrite + Unpin, { handshake(move |s| self.0.accept(s), stream).await } } impl fmt::Debug for TlsAcceptor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TlsAcceptor").finish() } } impl From<native_tls::TlsAcceptor> for TlsAcceptor { fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor { TlsAcceptor(inner) } } impl<S: AsyncRead + AsyncWrite + Unpin> Future for MidHandshake<S> { type Output = Result<TlsStream<S>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut_self = self.get_mut(); let mut s = mut_self.0.take().expect("future polled after completion"); s.get_mut().context = cx as *mut _ as *mut (); match s.handshake() { Ok(stream) => Poll::Ready(Ok(TlsStream(stream))), Err(HandshakeError::Failure(e)) => Poll::Ready(Err(e)), Err(HandshakeError::WouldBlock(mut s)) => { s.get_mut().context = null_mut(); mut_self.0 = Some(s); Poll::Pending } } } }
x: &mut Context<'_>, f: F) -> R where F: FnOnce(&mut native_tls::TlsStream<AllowStd<S>>) -> R, AllowStd<S>: Read + Write, { self.0.get_mut().context = ctx as *mut _ as *mut (); let g = Guard(self); f(&mut (g.0).0) }
function_block-function_prefixed
[ { "content": "/// Run the provided closure with a `MockClock` that starts at the current time.\n\npub fn mock<F, R>(f: F) -> R\n\nwhere\n\n F: FnOnce(&mut Handle) -> R,\n\n{\n\n let mut mock = MockClock::new();\n\n mock.enter(f)\n\n}\n\n\n", "file_path": "tokio-test/src/clock.rs", "rank": 0, ...
Rust
near/oysterpack-smart-near/src/data/object.rs
oysterpack/oysterpack-smart
f2985636d7c035de06e319f7ac8bec92e1293362
use near_sdk::{ borsh::{BorshDeserialize, BorshSerialize}, env, }; use std::ops::{Deref, DerefMut}; use std::{fmt::Debug, hash::Hash}; #[derive(Clone, Debug, PartialEq)] pub struct Object<K, V>(K, V) where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq; impl<K, V> Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { pub fn new(key: K, value: V) -> Self { Self(key, value) } pub fn key(&self) -> &K { &self.0 } pub fn exists(key: &K) -> bool { object_exists(key) } pub fn load(key: &K) -> Option<Self> { let key_bytes = object_serialize_key(key); env::storage_read(&key_bytes) .map(|value| V::try_from_slice(&value).unwrap()) .map(|value| Object(key.clone(), value)) } pub fn save(&self) { let key = object_serialize_key(&self.0); let value = self.1.try_to_vec().unwrap(); env::storage_write(&key, &value); } pub fn delete(self) -> bool { Self::delete_by_key(&self.0) } pub fn delete_by_key(key: &K) -> bool { let key = object_serialize_key(key); env::storage_remove(&key) } } impl<K, V> Deref for Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { type Target = V; fn deref(&self) -> &Self::Target { &self.1 } } impl<K, V> DerefMut for Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.1 } } pub fn object_exists<K: BorshSerialize>(key: &K) -> bool { let key = object_serialize_key(key); env::storage_has_key(&key) } fn object_serialize_key<K: BorshSerialize>(key: &K) -> Vec<u8> { let bytes = key.try_to_vec().unwrap(); env::sha256(&bytes) } #[cfg(test)] mod test { use super::*; use oysterpack_smart_near_test::*; type Data = Object<u128, u128>; #[test] fn crud() { let context = new_context("bob"); testing_env!(context); let data = Data::new(1, 2); assert!(!object_exists(data.key())); data.save(); assert!(object_exists(data.key())); let mut data2 = Data::load(data.key()).unwrap(); assert_eq!(data, data2); *data2 = 3_u128; assert_eq!(*data2, 3); data2.save(); let data3 = Data::load(data.key()).unwrap(); assert_eq!(data3, data2); assert!(data3.delete()); assert!(Data::load(data.key()).is_none()) } }
use near_sdk::{ borsh::{BorshDeserialize, BorshSerialize}, env, }; use std::ops::{Deref, DerefMut}; use std::{fmt::Debug, hash::Hash}; #[derive(Clone, Debug, PartialEq)] pub struct Object<K, V>(K, V) where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq; impl<K, V> Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { pub fn new(key: K, value: V) -> Self { Self(key, value) } pub fn key(&self) -> &K { &self.0 } pub fn exists(key: &K) -> bool { object_exists(key) } pub fn load(key: &K) -> Option<Self> { let key_bytes = object_serialize_key(key); env::storage_read(&key_bytes) .map(|value| V::try_from_slice(&value).unwrap()) .map(|value| Object(key.clone(), value)) } pub fn save(&self) { let key = object_serialize_key(&self.0); let value = self.1.try_to_vec().unwrap(); env::storage_write(&key, &value); } pub fn delete(self) -> bool { Self::delete_by_key(&self.0) } pub fn delete_by_key(key: &K) -> bool { let key = object_serialize_key(key); env::storage_remove(&key) } } impl<K, V> Deref for Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { type Target = V; fn deref(&self) -> &Self::Target { &self.1 } } impl<K, V> DerefMut for Object<K, V> where K: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq + Hash, V: BorshSerialize + BorshDeserialize + Clone + Debug + PartialEq, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.1 } } pub fn object_exists<K: BorshSerialize>(key: &K) -> bool { let key = object_serialize_key(key); env::storage_has_key(&key) } fn object_serialize_key<K: BorshSerialize>(key: &K) -> Vec<u8> { let bytes = key.try_to_vec().unwrap(); env::sha256(&bytes) } #[cfg(test)] mod test { use super::*; use oysterpack_smart_near_test::*; type Data = Object<u128, u128>; #[test]
}
fn crud() { let context = new_context("bob"); testing_env!(context); let data = Data::new(1, 2); assert!(!object_exists(data.key())); data.save(); assert!(object_exists(data.key())); let mut data2 = Data::load(data.key()).unwrap(); assert_eq!(data, data2); *data2 = 3_u128; assert_eq!(*data2, 3); data2.save(); let data3 = Data::load(data.key()).unwrap(); assert_eq!(data3, data2); assert!(data3.delete()); assert!(Data::load(data.key()).is_none()) }
function_block-full_function
[]
Rust
src/events/mod.rs
nthorne/rssnek
f877f5d1f4cc38ec22df1690e51d0566d57837c3
extern crate slog; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use slog::Logger; #[allow(dead_code)] pub struct Dispatcher<T> { channels: Vec<Sender<T>>, logger: slog::Logger, pub msg_tx: Sender<T>, msg_rx: Receiver<T>, } impl <T>Dispatcher<T> where T: Send + Clone + Debug + 'static { pub fn new(root_logger: &Logger) -> Dispatcher<T> { let (tx, rx) = mpsc::channel(); Dispatcher { channels: Vec::new(), logger: root_logger.clone(), msg_tx: tx, msg_rx: rx, } } pub fn start(&mut self) { info!(self.logger, "Starting message dispatcher loop.."); loop { if let Ok(msg) = self.msg_rx.recv() { info!(self.logger, "Got message"; "msg" => format!("{:?}", msg)); let current_channels = self.channels.clone(); self.channels.clear(); for c in current_channels { if let Ok(_) = c.send(msg.clone()) { info!(self.logger, "Sending to channel"; "chan" => format!("{:?}", c)); self.channels.push(c); } else { info!(self.logger, "Channel closed. Dropping it."; "chan" => format!("{:?}", c)); } } } } } pub fn subscribe(&mut self, channel: Sender<T>) { info!(self.logger, "Adding subscriber"; "channel" => format!("{:?}", channel)); self.channels.push(channel); } } #[allow(unused_variables)] #[allow(dead_code)] #[cfg(test)] mod tests { extern crate slog; extern crate slog_term; use std::sync::mpsc::channel; use events::{Dispatcher}; use slog::{DrainExt, Logger}; use std::thread; #[derive(Clone, Debug, PartialEq)] enum TestEvent { Event1, Event2, Event3, } struct TestSubscriber { pub result: bool, } fn construct_dispatcher() -> Dispatcher<TestEvent> { let logger = Logger::root(slog_term::streamer().build().fuse(), o!()); Dispatcher::<TestEvent>::new(&logger) } #[test] fn test_start_loop() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let chld = thread::spawn(move || { dis.start(); }); assert_eq!(true, tx.send(TestEvent::Event1).is_ok()); } #[test] fn test_subscribe() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); dis.subscribe(sub1_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); } #[test] fn test_subscribing_to_multiple_messages() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); let (sub2_tx, sub2_rx) = channel(); dis.subscribe(sub1_tx); dis.subscribe(sub2_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); assert_eq!(Ok(TestEvent::Event1), sub2_rx.recv()); } #[test] fn test_dispatching_multiple_messages() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); dis.subscribe(sub1_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); tx.send(TestEvent::Event2).unwrap(); assert_eq!(Ok(TestEvent::Event2), sub1_rx.recv()); tx.send(TestEvent::Event3).unwrap(); assert_eq!(Ok(TestEvent::Event3), sub1_rx.recv()); } }
extern crate slog; use std::fmt::Debug; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use slog::Logger; #[allow(dead_code)] pub struct Dispatcher<T> { channels: Vec<Sender<T>>, logger: slog::Logger, pub msg_tx: Sender<T>, msg_rx: Receiver<T>, } impl <T>Dispatcher<T> where T: Send + Clone + Debug + 'static { pub fn new(root_logger: &Logger) -> Dispatcher<T> { let (tx, rx) = mpsc::channel(); Dispatcher { channels: Vec::new(), logger: root_logger.clone(), msg_tx: tx, msg_rx: rx, } } pub fn start(&mut self) { info!(self.logger, "Starting message dispatcher loop.."); loop {
} } pub fn subscribe(&mut self, channel: Sender<T>) { info!(self.logger, "Adding subscriber"; "channel" => format!("{:?}", channel)); self.channels.push(channel); } } #[allow(unused_variables)] #[allow(dead_code)] #[cfg(test)] mod tests { extern crate slog; extern crate slog_term; use std::sync::mpsc::channel; use events::{Dispatcher}; use slog::{DrainExt, Logger}; use std::thread; #[derive(Clone, Debug, PartialEq)] enum TestEvent { Event1, Event2, Event3, } struct TestSubscriber { pub result: bool, } fn construct_dispatcher() -> Dispatcher<TestEvent> { let logger = Logger::root(slog_term::streamer().build().fuse(), o!()); Dispatcher::<TestEvent>::new(&logger) } #[test] fn test_start_loop() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let chld = thread::spawn(move || { dis.start(); }); assert_eq!(true, tx.send(TestEvent::Event1).is_ok()); } #[test] fn test_subscribe() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); dis.subscribe(sub1_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); } #[test] fn test_subscribing_to_multiple_messages() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); let (sub2_tx, sub2_rx) = channel(); dis.subscribe(sub1_tx); dis.subscribe(sub2_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); assert_eq!(Ok(TestEvent::Event1), sub2_rx.recv()); } #[test] fn test_dispatching_multiple_messages() { let mut dis = construct_dispatcher(); let tx = dis.msg_tx.clone(); let (sub1_tx, sub1_rx) = channel(); dis.subscribe(sub1_tx); let chld = thread::spawn(move || { dis.start(); }); tx.send(TestEvent::Event1).unwrap(); assert_eq!(Ok(TestEvent::Event1), sub1_rx.recv()); tx.send(TestEvent::Event2).unwrap(); assert_eq!(Ok(TestEvent::Event2), sub1_rx.recv()); tx.send(TestEvent::Event3).unwrap(); assert_eq!(Ok(TestEvent::Event3), sub1_rx.recv()); } }
if let Ok(msg) = self.msg_rx.recv() { info!(self.logger, "Got message"; "msg" => format!("{:?}", msg)); let current_channels = self.channels.clone(); self.channels.clear(); for c in current_channels { if let Ok(_) = c.send(msg.clone()) { info!(self.logger, "Sending to channel"; "chan" => format!("{:?}", c)); self.channels.push(c); } else { info!(self.logger, "Channel closed. Dropping it."; "chan" => format!("{:?}", c)); } } }
if_condition
[ { "content": "pub fn setup() -> slog::Logger {\n\n let file = File::create(\"rssnek.log\").expect(\"Could not open log file.\");\n\n let file_drain = slog_stream::stream(file, slog_json::default()).fuse();\n\n //let drain = slog_term::streamer().compact().build().fuse();\n\n Logger::root(file_drain,...
Rust
src/usbphy/rx_set.rs
conorpp/lpc55-pac
eb30d633de05113362de01095123d70c54e63ef4
#[doc = "Reader of register RX_SET"] pub type R = crate::R<u32, super::RX_SET>; #[doc = "Writer for register RX_SET"] pub type W = crate::W<u32, super::RX_SET>; #[doc = "Register RX_SET `reset()`'s with value 0"] impl crate::ResetValue for super::RX_SET { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "The ENVADJ field adjusts the trip point for the envelope detector\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum ENVADJ_A { #[doc = "0: Trip-Level Voltage is 0.1000 V"] VALUE0 = 0, #[doc = "1: Trip-Level Voltage is 0.1125 V"] VALUE1 = 1, #[doc = "2: Trip-Level Voltage is 0.1250 V"] VALUE2 = 2, #[doc = "3: Trip-Level Voltage is 0.0875 V"] VALUE3 = 3, } impl From<ENVADJ_A> for u8 { #[inline(always)] fn from(variant: ENVADJ_A) -> Self { variant as _ } } #[doc = "Reader of field `ENVADJ`"] pub type ENVADJ_R = crate::R<u8, ENVADJ_A>; impl ENVADJ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, ENVADJ_A> { use crate::Variant::*; match self.bits { 0 => Val(ENVADJ_A::VALUE0), 1 => Val(ENVADJ_A::VALUE1), 2 => Val(ENVADJ_A::VALUE2), 3 => Val(ENVADJ_A::VALUE3), i => Res(i), } } #[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == ENVADJ_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == ENVADJ_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == ENVADJ_A::VALUE2 } #[doc = "Checks if the value of the field is `VALUE3`"] #[inline(always)] pub fn is_value3(&self) -> bool { *self == ENVADJ_A::VALUE3 } } #[doc = "Write proxy for field `ENVADJ`"] pub struct ENVADJ_W<'a> { w: &'a mut W, } impl<'a> ENVADJ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ENVADJ_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Trip-Level Voltage is 0.1000 V"] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE0) } #[doc = "Trip-Level Voltage is 0.1125 V"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE1) } #[doc = "Trip-Level Voltage is 0.1250 V"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE2) } #[doc = "Trip-Level Voltage is 0.0875 V"] #[inline(always)] pub fn value3(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07); self.w } } #[doc = "The DISCONADJ field adjusts the trip point for the disconnect detector.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum DISCONADJ_A { #[doc = "0: Trip-Level Voltage is 0.56875 V"] VALUE0 = 0, #[doc = "1: Trip-Level Voltage is 0.55000 V"] VALUE1 = 1, #[doc = "2: Trip-Level Voltage is 0.58125 V"] VALUE2 = 2, #[doc = "3: Trip-Level Voltage is 0.60000 V"] VALUE3 = 3, } impl From<DISCONADJ_A> for u8 { #[inline(always)] fn from(variant: DISCONADJ_A) -> Self { variant as _ } } #[doc = "Reader of field `DISCONADJ`"] pub type DISCONADJ_R = crate::R<u8, DISCONADJ_A>; impl DISCONADJ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, DISCONADJ_A> { use crate::Variant::*; match self.bits { 0 => Val(DISCONADJ_A::VALUE0), 1 => Val(DISCONADJ_A::VALUE1), 2 => Val(DISCONADJ_A::VALUE2), 3 => Val(DISCONADJ_A::VALUE3), i => Res(i), } } #[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == DISCONADJ_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == DISCONADJ_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == DISCONADJ_A::VALUE2 } #[doc = "Checks if the value of the field is `VALUE3`"] #[inline(always)] pub fn is_value3(&self) -> bool { *self == DISCONADJ_A::VALUE3 } } #[doc = "Write proxy for field `DISCONADJ`"] pub struct DISCONADJ_W<'a> { w: &'a mut W, } impl<'a> DISCONADJ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DISCONADJ_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Trip-Level Voltage is 0.56875 V"] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE0) } #[doc = "Trip-Level Voltage is 0.55000 V"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE1) } #[doc = "Trip-Level Voltage is 0.58125 V"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE2) } #[doc = "Trip-Level Voltage is 0.60000 V"] #[inline(always)] pub fn value3(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4); self.w } } #[doc = "This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXDBYPASS_A { #[doc = "0: Normal operation."] VALUE0 = 0, #[doc = "1: Use the output of the USB_DP single-ended receiver in place of the full-speed differential receiver"] VALUE1 = 1, } impl From<RXDBYPASS_A> for bool { #[inline(always)] fn from(variant: RXDBYPASS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXDBYPASS`"] pub type RXDBYPASS_R = crate::R<bool, RXDBYPASS_A>; impl RXDBYPASS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXDBYPASS_A { match self.bits { false => RXDBYPASS_A::VALUE0, true => RXDBYPASS_A::VALUE1, } } #[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == RXDBYPASS_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == RXDBYPASS_A::VALUE1 } } #[doc = "Write proxy for field `RXDBYPASS`"] pub struct RXDBYPASS_W<'a> { w: &'a mut W, } impl<'a> RXDBYPASS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXDBYPASS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Normal operation."] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(RXDBYPASS_A::VALUE0) } #[doc = "Use the output of the USB_DP single-ended receiver in place of the full-speed differential receiver"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(RXDBYPASS_A::VALUE1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } impl R { #[doc = "Bits 0:2 - The ENVADJ field adjusts the trip point for the envelope detector"] #[inline(always)] pub fn envadj(&self) -> ENVADJ_R { ENVADJ_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 4:6 - The DISCONADJ field adjusts the trip point for the disconnect detector."] #[inline(always)] pub fn disconadj(&self) -> DISCONADJ_R { DISCONADJ_R::new(((self.bits >> 4) & 0x07) as u8) } #[doc = "Bit 22 - This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver"] #[inline(always)] pub fn rxdbypass(&self) -> RXDBYPASS_R { RXDBYPASS_R::new(((self.bits >> 22) & 0x01) != 0) } } impl W { #[doc = "Bits 0:2 - The ENVADJ field adjusts the trip point for the envelope detector"] #[inline(always)] pub fn envadj(&mut self) -> ENVADJ_W { ENVADJ_W { w: self } } #[doc = "Bits 4:6 - The DISCONADJ field adjusts the trip point for the disconnect detector."] #[inline(always)] pub fn disconadj(&mut self) -> DISCONADJ_W { DISCONADJ_W { w: self } } #[doc = "Bit 22 - This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver"] #[inline(always)] pub fn rxdbypass(&mut self) -> RXDBYPASS_W { RXDBYPASS_W { w: self } } }
#[doc = "Reader of register RX_SET"] pub type R = crate::R<u32, super::RX_SET>; #[doc = "Writer for register RX_SET"] pub type W = crate::W<u32, super::RX_SET>; #[doc = "Register RX_SET `reset()`'s with value 0"] impl crate::ResetValue for super::RX_SET { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "The ENVADJ field adjusts the trip point for the envelope detector\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum ENVADJ_A { #[doc = "0: Trip-Level Voltage is 0.1000 V"] VALUE0 = 0, #[doc = "1: Trip-Level Voltage is 0.1125 V"] VALUE1 = 1, #[doc = "2: Trip-Level Voltage is 0.1250 V"] VALUE2 = 2, #[doc = "3: Trip-Level Voltage is 0.0875 V"] VALUE3 = 3, } impl From<ENVADJ_A> for u8 { #[inline(always)] fn from(variant: ENVADJ_A) -> Self { variant as _ } } #[doc = "Reader of field `ENVADJ`"] pub type ENVADJ_R = crate::R<u8, ENVADJ_A>; impl ENVADJ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, ENVADJ_A> { use crate::Variant::*; match self.bits { 0 => Val(ENVADJ_A::VALUE0), 1 => Val(ENVADJ_A::VALUE
#[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == ENVADJ_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == ENVADJ_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == ENVADJ_A::VALUE2 } #[doc = "Checks if the value of the field is `VALUE3`"] #[inline(always)] pub fn is_value3(&self) -> bool { *self == ENVADJ_A::VALUE3 } } #[doc = "Write proxy for field `ENVADJ`"] pub struct ENVADJ_W<'a> { w: &'a mut W, } impl<'a> ENVADJ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ENVADJ_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Trip-Level Voltage is 0.1000 V"] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE0) } #[doc = "Trip-Level Voltage is 0.1125 V"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE1) } #[doc = "Trip-Level Voltage is 0.1250 V"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE2) } #[doc = "Trip-Level Voltage is 0.0875 V"] #[inline(always)] pub fn value3(self) -> &'a mut W { self.variant(ENVADJ_A::VALUE3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07); self.w } } #[doc = "The DISCONADJ field adjusts the trip point for the disconnect detector.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum DISCONADJ_A { #[doc = "0: Trip-Level Voltage is 0.56875 V"] VALUE0 = 0, #[doc = "1: Trip-Level Voltage is 0.55000 V"] VALUE1 = 1, #[doc = "2: Trip-Level Voltage is 0.58125 V"] VALUE2 = 2, #[doc = "3: Trip-Level Voltage is 0.60000 V"] VALUE3 = 3, } impl From<DISCONADJ_A> for u8 { #[inline(always)] fn from(variant: DISCONADJ_A) -> Self { variant as _ } } #[doc = "Reader of field `DISCONADJ`"] pub type DISCONADJ_R = crate::R<u8, DISCONADJ_A>; impl DISCONADJ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, DISCONADJ_A> { use crate::Variant::*; match self.bits { 0 => Val(DISCONADJ_A::VALUE0), 1 => Val(DISCONADJ_A::VALUE1), 2 => Val(DISCONADJ_A::VALUE2), 3 => Val(DISCONADJ_A::VALUE3), i => Res(i), } } #[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == DISCONADJ_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == DISCONADJ_A::VALUE1 } #[doc = "Checks if the value of the field is `VALUE2`"] #[inline(always)] pub fn is_value2(&self) -> bool { *self == DISCONADJ_A::VALUE2 } #[doc = "Checks if the value of the field is `VALUE3`"] #[inline(always)] pub fn is_value3(&self) -> bool { *self == DISCONADJ_A::VALUE3 } } #[doc = "Write proxy for field `DISCONADJ`"] pub struct DISCONADJ_W<'a> { w: &'a mut W, } impl<'a> DISCONADJ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DISCONADJ_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Trip-Level Voltage is 0.56875 V"] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE0) } #[doc = "Trip-Level Voltage is 0.55000 V"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE1) } #[doc = "Trip-Level Voltage is 0.58125 V"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE2) } #[doc = "Trip-Level Voltage is 0.60000 V"] #[inline(always)] pub fn value3(self) -> &'a mut W { self.variant(DISCONADJ_A::VALUE3) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 4)) | (((value as u32) & 0x07) << 4); self.w } } #[doc = "This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXDBYPASS_A { #[doc = "0: Normal operation."] VALUE0 = 0, #[doc = "1: Use the output of the USB_DP single-ended receiver in place of the full-speed differential receiver"] VALUE1 = 1, } impl From<RXDBYPASS_A> for bool { #[inline(always)] fn from(variant: RXDBYPASS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXDBYPASS`"] pub type RXDBYPASS_R = crate::R<bool, RXDBYPASS_A>; impl RXDBYPASS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXDBYPASS_A { match self.bits { false => RXDBYPASS_A::VALUE0, true => RXDBYPASS_A::VALUE1, } } #[doc = "Checks if the value of the field is `VALUE0`"] #[inline(always)] pub fn is_value0(&self) -> bool { *self == RXDBYPASS_A::VALUE0 } #[doc = "Checks if the value of the field is `VALUE1`"] #[inline(always)] pub fn is_value1(&self) -> bool { *self == RXDBYPASS_A::VALUE1 } } #[doc = "Write proxy for field `RXDBYPASS`"] pub struct RXDBYPASS_W<'a> { w: &'a mut W, } impl<'a> RXDBYPASS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXDBYPASS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Normal operation."] #[inline(always)] pub fn value0(self) -> &'a mut W { self.variant(RXDBYPASS_A::VALUE0) } #[doc = "Use the output of the USB_DP single-ended receiver in place of the full-speed differential receiver"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(RXDBYPASS_A::VALUE1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } impl R { #[doc = "Bits 0:2 - The ENVADJ field adjusts the trip point for the envelope detector"] #[inline(always)] pub fn envadj(&self) -> ENVADJ_R { ENVADJ_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 4:6 - The DISCONADJ field adjusts the trip point for the disconnect detector."] #[inline(always)] pub fn disconadj(&self) -> DISCONADJ_R { DISCONADJ_R::new(((self.bits >> 4) & 0x07) as u8) } #[doc = "Bit 22 - This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver"] #[inline(always)] pub fn rxdbypass(&self) -> RXDBYPASS_R { RXDBYPASS_R::new(((self.bits >> 22) & 0x01) != 0) } } impl W { #[doc = "Bits 0:2 - The ENVADJ field adjusts the trip point for the envelope detector"] #[inline(always)] pub fn envadj(&mut self) -> ENVADJ_W { ENVADJ_W { w: self } } #[doc = "Bits 4:6 - The DISCONADJ field adjusts the trip point for the disconnect detector."] #[inline(always)] pub fn disconadj(&mut self) -> DISCONADJ_W { DISCONADJ_W { w: self } } #[doc = "Bit 22 - This test mode is intended for lab use only, replace FS differential receiver with DP single ended receiver"] #[inline(always)] pub fn rxdbypass(&mut self) -> RXDBYPASS_W { RXDBYPASS_W { w: self } } }
1), 2 => Val(ENVADJ_A::VALUE2), 3 => Val(ENVADJ_A::VALUE3), i => Res(i), } }
function_block-function_prefixed
[]
Rust
core/tests/rocket.rs
CugeDe/rocket-config
23083728ea17e9b82d73807dbd98885899e99fb5
#![feature(decl_macro, proc_macro_hygiene)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_config; #[macro_use] extern crate serde_json; extern crate tempfile; use rocket::local::Client; use rocket_config::Factory as ConfigurationsFairing; use std::env; use std::fs::OpenOptions; use std::io::Result; use std::io::Write as _; use std::path::{Path, PathBuf}; configuration!("diesel"); fn create_temporary_file(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::NamedTempFile> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_bytes) .tempfile_in(dest) } fn delete_temporary_file(temp_file: tempfile::NamedTempFile) { let _ = temp_file.close(); } fn create_temporary_directory(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::TempDir> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_bytes) .tempdir_in(dest) } fn delete_temporary_directory(temp_dir: tempfile::TempDir) { let _ = temp_dir.close(); } fn cwd(path: &Path) -> PathBuf { let current_dir = env::current_dir() .expect("failed to retrieve current directory"); env::set_current_dir(path) .expect("failed to change current directory"); current_dir } fn mount_load_env(path: &Path) -> (Vec<tempfile::TempDir>, Vec<tempfile::NamedTempFile>) { let mut directories = Vec::new(); let mut files = Vec::new(); { directories.push( create_temporary_directory("config", "", 0, path).unwrap() ); directories.push( create_temporary_directory("dev", "", 0, directories[0].path()).unwrap() ); } { files.push( create_temporary_file("no_extension", "", 16, directories[0].path()).unwrap() ); files.push( create_temporary_file("invalid_extension_dev", "toto", 4, directories[1].path()).unwrap() ); { files.push( create_temporary_file("diesel", ".json", 0, directories[0].path()).unwrap() ); let mut diesel_dot_json = OpenOptions::new() .write(true) .open(files.last().unwrap().path()) .expect("failed to open diesel.json"); let _ = diesel_dot_json .write(&serde_json::to_vec(&json!({ "parameters": { "env(DATABASE_URL)": "", "inital_id": 0, "limit_id": -1, }, "diesel": { "dbal": { "driver": "mysql", "server_version": 5.7, "charset": "utf8", "default_table_options": { "charset": "utf8", "collate": "utf8_unicode_ci" }, "url": "%env(resolve:DATABASE_URL)%" } } } )).expect("failed to serialize example json")[..]); } { files.push( create_temporary_file("diesel", ".json", 0, directories[1].path()).unwrap() ); let mut diesel_dot_json = OpenOptions::new() .write(true) .open(files.last().unwrap().path()) .expect("failed to open diesel.json"); let _ = diesel_dot_json .write(&serde_json::to_vec(&json!({ "parameters": { "env(DATABASE_URL)": "", "inital_id": 0, "limit_id": -1, }, "diesel": { "dbal": { "driver": "mysql", "server_version": 5.7, "charset": "utf8", "default_table_options": { "charset": "utf8", "collate": "utf8_unicode_ci" }, "url": "%env(resolve:DATABASE_URL)%" } } } )).expect("failed to serialize example json")[..]); } } (directories, files) } fn unmount_load_env(directories: Vec<tempfile::TempDir>, files: Vec<tempfile::NamedTempFile>) { for file in files { delete_temporary_file(file); } for directory in directories { delete_temporary_directory(directory); } } #[get("/<name>/<age>")] fn hello(configuration: DieselConfiguration, name: String, age: u8) -> String { println!("Configuration: {:?}", configuration); format!("Hello, {} year old named {}!", age, name) } #[test] fn rocket_test() { let temp_dir = tempfile::tempdir().expect( &format!("failed to create temp dir in {:?}", env::temp_dir()) ); let (directories, files) = mount_load_env(temp_dir.path()); let previous_dir = cwd(temp_dir.path()); { let rocket = rocket::ignite() .attach(ConfigurationsFairing::new()) .mount("/hello", routes![hello]); let client = Client::new(rocket).expect("valid rocket instance"); let req = client.get("/hello/John%20Doe/37"); let mut response = req.dispatch(); let body = response.body_string(); assert!(body.is_some()); assert_eq!(body.unwrap(), "Hello, 37 year old named John Doe!"); } unmount_load_env(directories, files); let _ = cwd(&previous_dir); delete_temporary_directory(temp_dir); }
#![feature(decl_macro, proc_macro_hygiene)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_config; #[macro_use] extern crate serde_json; extern crate tempfile; use rocket::local::Client; use rocket_config::Factory as ConfigurationsFairing; use std::env; use std::fs::OpenOptions; use std::io::Result; use std::io::Write as _; use std::path::{Path, PathBuf}; configura
elete_temporary_file(temp_file: tempfile::NamedTempFile) { let _ = temp_file.close(); } fn create_temporary_directory(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::TempDir> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_bytes) .tempdir_in(dest) } fn delete_temporary_directory(temp_dir: tempfile::TempDir) { let _ = temp_dir.close(); } fn cwd(path: &Path) -> PathBuf { let current_dir = env::current_dir() .expect("failed to retrieve current directory"); env::set_current_dir(path) .expect("failed to change current directory"); current_dir } fn mount_load_env(path: &Path) -> (Vec<tempfile::TempDir>, Vec<tempfile::NamedTempFile>) { let mut directories = Vec::new(); let mut files = Vec::new(); { directories.push( create_temporary_directory("config", "", 0, path).unwrap() ); directories.push( create_temporary_directory("dev", "", 0, directories[0].path()).unwrap() ); } { files.push( create_temporary_file("no_extension", "", 16, directories[0].path()).unwrap() ); files.push( create_temporary_file("invalid_extension_dev", "toto", 4, directories[1].path()).unwrap() ); { files.push( create_temporary_file("diesel", ".json", 0, directories[0].path()).unwrap() ); let mut diesel_dot_json = OpenOptions::new() .write(true) .open(files.last().unwrap().path()) .expect("failed to open diesel.json"); let _ = diesel_dot_json .write(&serde_json::to_vec(&json!({ "parameters": { "env(DATABASE_URL)": "", "inital_id": 0, "limit_id": -1, }, "diesel": { "dbal": { "driver": "mysql", "server_version": 5.7, "charset": "utf8", "default_table_options": { "charset": "utf8", "collate": "utf8_unicode_ci" }, "url": "%env(resolve:DATABASE_URL)%" } } } )).expect("failed to serialize example json")[..]); } { files.push( create_temporary_file("diesel", ".json", 0, directories[1].path()).unwrap() ); let mut diesel_dot_json = OpenOptions::new() .write(true) .open(files.last().unwrap().path()) .expect("failed to open diesel.json"); let _ = diesel_dot_json .write(&serde_json::to_vec(&json!({ "parameters": { "env(DATABASE_URL)": "", "inital_id": 0, "limit_id": -1, }, "diesel": { "dbal": { "driver": "mysql", "server_version": 5.7, "charset": "utf8", "default_table_options": { "charset": "utf8", "collate": "utf8_unicode_ci" }, "url": "%env(resolve:DATABASE_URL)%" } } } )).expect("failed to serialize example json")[..]); } } (directories, files) } fn unmount_load_env(directories: Vec<tempfile::TempDir>, files: Vec<tempfile::NamedTempFile>) { for file in files { delete_temporary_file(file); } for directory in directories { delete_temporary_directory(directory); } } #[get("/<name>/<age>")] fn hello(configuration: DieselConfiguration, name: String, age: u8) -> String { println!("Configuration: {:?}", configuration); format!("Hello, {} year old named {}!", age, name) } #[test] fn rocket_test() { let temp_dir = tempfile::tempdir().expect( &format!("failed to create temp dir in {:?}", env::temp_dir()) ); let (directories, files) = mount_load_env(temp_dir.path()); let previous_dir = cwd(temp_dir.path()); { let rocket = rocket::ignite() .attach(ConfigurationsFairing::new()) .mount("/hello", routes![hello]); let client = Client::new(rocket).expect("valid rocket instance"); let req = client.get("/hello/John%20Doe/37"); let mut response = req.dispatch(); let body = response.body_string(); assert!(body.is_some()); assert_eq!(body.unwrap(), "Hello, 37 year old named John Doe!"); } unmount_load_env(directories, files); let _ = cwd(&previous_dir); delete_temporary_directory(temp_dir); }
tion!("diesel"); fn create_temporary_file(prefix: &str, suffix: &str, rand_bytes: usize, dest: &Path) -> Result<tempfile::NamedTempFile> { tempfile::Builder::new() .prefix(prefix) .suffix(suffix) .rand_bytes(rand_bytes) .tempfile_in(dest) } fn d
random
[ { "content": "# rocket-config\n\n\n\nrocket-config is a [Fairing](https://api.rocket.rs/v0.4/rocket/fairing/trait.Fairing.html)\n\ndesigned for Rocket, a web framework for Rust (nightly).\n\n\n\n```rust\n\n#![feature(proc_macro_hygiene)]\n\n\n\n#[macro_use] extern crate rocket;\n\nextern crate rocket_config;\n\...
Rust
src/structs/drawing/charts/legend.rs
MathNya/umya-spreadsheet
d9c8bb9919fe0b42733269fca5a81866a139fbcc
use super::LegendPosition; use super::Layout; use super::Overlay; use super::TextProperties; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Legend { legend_position: LegendPosition, layout: Option<Layout>, overlay: Overlay, text_properties: Option<TextProperties>, } impl Legend { pub fn get_legend_position(&self)-> &LegendPosition { &self.legend_position } pub fn get_legend_position_mut(&mut self)-> &mut LegendPosition { &mut self.legend_position } pub fn set_legend_position(&mut self, value:LegendPosition)-> &mut Legend { self.legend_position = value.into(); self } pub fn get_layout(&self)-> &Option<Layout> { &self.layout } pub fn get_layout_mut(&mut self)-> &mut Option<Layout> { &mut self.layout } pub fn set_layout(&mut self, value:Layout)-> &mut Legend { self.layout = Some(value); self } pub fn get_overlay(&self)-> &Overlay { &self.overlay } pub fn get_overlay_mut(&mut self)-> &mut Overlay { &mut self.overlay } pub fn set_overlay(&mut self, value:Overlay)-> &mut Legend { self.overlay = value; self } pub fn get_text_properties(&self)-> &Option<TextProperties> { &self.text_properties } pub fn get_text_properties_mut(&mut self)-> &mut Option<TextProperties> { &mut self.text_properties } pub fn set_text_properties(&mut self, value:TextProperties)-> &mut Legend { self.text_properties = Some(value); self } pub(crate) fn set_attributes<R: std::io::BufRead>( &mut self, reader:&mut Reader<R>, _e:&BytesStart ) { let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) => { match e.name() { b"c:layout" => { let mut obj = Layout::default(); obj.set_attributes(reader, e, false); self.set_layout(obj); }, b"c:txPr" => { let mut obj = TextProperties::default(); obj.set_attributes(reader, e); self.set_text_properties(obj); }, _ => (), } }, Ok(Event::Empty(ref e)) => { match e.name() { b"c:legendPos" => { self.legend_position.set_attributes(reader, e); }, b"c:layout" => { let mut obj = Layout::default(); obj.set_attributes(reader, e, true); self.set_layout(obj); }, b"c:overlay" => { self.overlay.set_attributes(reader, e); }, _ => (), } }, Ok(Event::End(ref e)) => { match e.name() { b"c:legend" => return, _ => (), } }, Ok(Event::Eof) => panic!("Error not find {} end element", "c:legend"), Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } buf.clear(); } } pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { write_start_tag(writer, "c:legend", vec![], false); &self.legend_position.write_to(writer); match &self.layout { Some(v) => {v.write_to(writer);}, None => {} } &self.overlay.write_to(writer); match &self.text_properties { Some(v) => {v.write_to(writer);}, None => {} } write_end_tag(writer, "c:legend"); } }
use super::LegendPosition; use super::Layout; use super::Overlay; use super::TextProperties; use writer::driver::*; use quick_xml::Reader; use quick_xml::events::{Event, BytesStart}; use quick_xml::Writer; use std::io::Cursor; #[derive(Default, Debug)] pub struct Legend { legend_position: LegendPosition, layout: Option<Layout>, overla
[], false); &self.legend_position.write_to(writer); match &self.layout { Some(v) => {v.write_to(writer);}, None => {} } &self.overlay.write_to(writer); match &self.text_properties { Some(v) => {v.write_to(writer);}, None => {} } write_end_tag(writer, "c:legend"); } }
y: Overlay, text_properties: Option<TextProperties>, } impl Legend { pub fn get_legend_position(&self)-> &LegendPosition { &self.legend_position } pub fn get_legend_position_mut(&mut self)-> &mut LegendPosition { &mut self.legend_position } pub fn set_legend_position(&mut self, value:LegendPosition)-> &mut Legend { self.legend_position = value.into(); self } pub fn get_layout(&self)-> &Option<Layout> { &self.layout } pub fn get_layout_mut(&mut self)-> &mut Option<Layout> { &mut self.layout } pub fn set_layout(&mut self, value:Layout)-> &mut Legend { self.layout = Some(value); self } pub fn get_overlay(&self)-> &Overlay { &self.overlay } pub fn get_overlay_mut(&mut self)-> &mut Overlay { &mut self.overlay } pub fn set_overlay(&mut self, value:Overlay)-> &mut Legend { self.overlay = value; self } pub fn get_text_properties(&self)-> &Option<TextProperties> { &self.text_properties } pub fn get_text_properties_mut(&mut self)-> &mut Option<TextProperties> { &mut self.text_properties } pub fn set_text_properties(&mut self, value:TextProperties)-> &mut Legend { self.text_properties = Some(value); self } pub(crate) fn set_attributes<R: std::io::BufRead>( &mut self, reader:&mut Reader<R>, _e:&BytesStart ) { let mut buf = Vec::new(); loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) => { match e.name() { b"c:layout" => { let mut obj = Layout::default(); obj.set_attributes(reader, e, false); self.set_layout(obj); }, b"c:txPr" => { let mut obj = TextProperties::default(); obj.set_attributes(reader, e); self.set_text_properties(obj); }, _ => (), } }, Ok(Event::Empty(ref e)) => { match e.name() { b"c:legendPos" => { self.legend_position.set_attributes(reader, e); }, b"c:layout" => { let mut obj = Layout::default(); obj.set_attributes(reader, e, true); self.set_layout(obj); }, b"c:overlay" => { self.overlay.set_attributes(reader, e); }, _ => (), } }, Ok(Event::End(ref e)) => { match e.name() { b"c:legend" => return, _ => (), } }, Ok(Event::Eof) => panic!("Error not find {} end element", "c:legend"), Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e), _ => (), } buf.clear(); } } pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) { write_start_tag(writer, "c:legend", vec!
random
[ { "content": "pub trait EnumTrait{\n\n fn get_value_string(&self)->&str;\n\n}\n", "file_path": "src/structs/enum_trait.rs", "rank": 0, "score": 100229.84228063838 }, { "content": "/// create new spreadsheet file.\n\n/// # Arguments\n\n/// # Return value\n\n/// * Spreadsheet structs object...
Rust
src/markdown/compound.rs
Canop/minimad
09b34e8f0173a777ec721bad1827f76b11e90ae0
use std::fmt::{self, Write}; #[derive(Clone, PartialEq, Eq, Hash)] pub struct Compound<'s> { pub src: &'s str, pub bold: bool, pub italic: bool, pub code: bool, pub strikeout: bool, } impl<'s> Compound<'s> { #[inline(always)] pub fn raw_str(src: &'s str) -> Compound<'s> { Compound { src, bold: false, italic: false, code: false, strikeout: false, } } pub fn set_str(&mut self, src: &'s str) { self.src = src; } pub fn set_attributes_from(&mut self, other: &Compound) { self.bold = other.bold; self.italic = other.italic; self.code = other.code; self.strikeout = other.strikeout; } #[inline(always)] pub fn sub(&self, r_start: usize, r_end: usize) -> Compound<'s> { Compound { src: &self.src[r_start..r_end], bold: self.bold, italic: self.italic, code: self.code, strikeout: self.strikeout, } } #[inline(always)] pub fn sub_chars(&self, r_start: usize, r_end: usize) -> Compound<'s> { let mut rb_start = 0; let mut rb_end = 0; for (char_idx, (byte_idx, _)) in self.as_str().char_indices().enumerate() { if char_idx == r_start { rb_start = byte_idx; } else if char_idx == r_end { rb_end = byte_idx; break; } } if rb_end == 0 && rb_start != 0 { self.tail(rb_start) } else { self.sub(rb_start, rb_end) } } #[inline(always)] pub fn tail(&self, r_start: usize) -> Compound<'s> { Compound { src: &self.src[r_start..], bold: self.bold, italic: self.italic, code: self.code, strikeout: self.strikeout, } } #[inline(always)] pub fn tail_chars(&self, r_start: usize) -> Compound<'s> { let mut rb_start = 0; for (char_idx, (byte_idx, _)) in self.as_str().char_indices().enumerate() { rb_start = byte_idx; if char_idx == r_start { break; } } self.tail(rb_start) } pub fn cut_tail(&mut self, tail_size: usize) -> Compound<'s> { let cut = self.src.len() - tail_size; let tail = Compound { src: &self.src[cut..], bold: self.bold, italic: self.italic, code: self.code, strikeout: self.strikeout, }; self.src = &self.src[0..cut]; tail } #[inline(always)] pub fn raw_part(src: &'s str, start: usize, end: usize) -> Compound<'s> { Compound { src: &src[start..end], bold: false, italic: false, code: false, strikeout: false, } } #[inline(always)] pub fn new( src: &'s str, start: usize, end: usize, bold: bool, italic: bool, code: bool, strikeout: bool, ) -> Compound<'s> { Compound { src: &src[start..end], italic, bold, code, strikeout, } } #[inline(always)] pub fn bold(mut self) -> Compound<'s> { self.bold = true; self } #[inline(always)] pub fn italic(mut self) -> Compound<'s> { self.italic = true; self } #[inline(always)] pub fn code(mut self) -> Compound<'s> { self.code = true; self } #[inline(always)] pub fn strikeout(mut self) -> Compound<'s> { self.strikeout = true; self } #[inline(always)] pub fn set_bold(&mut self, bold: bool) { self.bold = bold; } #[inline(always)] pub fn set_italic(&mut self, italic: bool) { self.italic = italic; } #[inline(always)] pub fn set_code(&mut self, code: bool) { self.code = code; } #[inline(always)] pub fn set_strikeout(&mut self, strikeout: bool) { self.strikeout = strikeout; } #[inline(always)] pub fn as_str(&self) -> &'s str { self.src } #[inline(always)] pub fn char_length(&self) -> usize { self.as_str().chars().count() } #[inline(always)] pub fn is_empty(&self) -> bool { self.src.is_empty() } } impl fmt::Display for Compound<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str())?; Ok(()) } } impl fmt::Debug for Compound<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.bold { f.write_char('B')?; } if self.italic { f.write_char('I')?; } if self.code { f.write_char('C')?; } if self.strikeout { f.write_char('S')?; } f.write_char('"')?; f.write_str(self.as_str())?; f.write_char('"')?; Ok(()) } }
use std::fmt::{self, Write}; #[derive(Clone, PartialEq, Eq, Hash)] pub struct Compound<'s> { pub src: &'s str, pub bold: bool, pub italic: bool, pub code: bool, pub strikeout: bool, } impl<'s> Compound<'s> { #[inline(always)] pub fn raw_str(src: &'s str) -> Compound<'s> { Compound { src, bold: false, italic: false, code: false, strikeout: false, } } pub fn set_str(&mut self, src: &'s str) { self.src = src; } pub fn set_attributes_from(&mut self, other: &Compound) { self.bold = other.bold; self.italic = other.italic; self.code = other.code; self.strikeout = other.strikeout; } #[inline(always)] pub fn sub(&self, r_start: usize, r_end: usize) -> Compound<'s> { Compound { src: &self.src[r_start..r_end], bold: self.bold, italic: self.italic, code: self.code, strikeout: s
italic: self.italic, code: self.code, strikeout: self.strikeout, }; self.src = &self.src[0..cut]; tail } #[inline(always)] pub fn raw_part(src: &'s str, start: usize, end: usize) -> Compound<'s> { Compound { src: &src[start..end], bold: false, italic: false, code: false, strikeout: false, } } #[inline(always)] pub fn new( src: &'s str, start: usize, end: usize, bold: bool, italic: bool, code: bool, strikeout: bool, ) -> Compound<'s> { Compound { src: &src[start..end], italic, bold, code, strikeout, } } #[inline(always)] pub fn bold(mut self) -> Compound<'s> { self.bold = true; self } #[inline(always)] pub fn italic(mut self) -> Compound<'s> { self.italic = true; self } #[inline(always)] pub fn code(mut self) -> Compound<'s> { self.code = true; self } #[inline(always)] pub fn strikeout(mut self) -> Compound<'s> { self.strikeout = true; self } #[inline(always)] pub fn set_bold(&mut self, bold: bool) { self.bold = bold; } #[inline(always)] pub fn set_italic(&mut self, italic: bool) { self.italic = italic; } #[inline(always)] pub fn set_code(&mut self, code: bool) { self.code = code; } #[inline(always)] pub fn set_strikeout(&mut self, strikeout: bool) { self.strikeout = strikeout; } #[inline(always)] pub fn as_str(&self) -> &'s str { self.src } #[inline(always)] pub fn char_length(&self) -> usize { self.as_str().chars().count() } #[inline(always)] pub fn is_empty(&self) -> bool { self.src.is_empty() } } impl fmt::Display for Compound<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str())?; Ok(()) } } impl fmt::Debug for Compound<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.bold { f.write_char('B')?; } if self.italic { f.write_char('I')?; } if self.code { f.write_char('C')?; } if self.strikeout { f.write_char('S')?; } f.write_char('"')?; f.write_str(self.as_str())?; f.write_char('"')?; Ok(()) } }
elf.strikeout, } } #[inline(always)] pub fn sub_chars(&self, r_start: usize, r_end: usize) -> Compound<'s> { let mut rb_start = 0; let mut rb_end = 0; for (char_idx, (byte_idx, _)) in self.as_str().char_indices().enumerate() { if char_idx == r_start { rb_start = byte_idx; } else if char_idx == r_end { rb_end = byte_idx; break; } } if rb_end == 0 && rb_start != 0 { self.tail(rb_start) } else { self.sub(rb_start, rb_end) } } #[inline(always)] pub fn tail(&self, r_start: usize) -> Compound<'s> { Compound { src: &self.src[r_start..], bold: self.bold, italic: self.italic, code: self.code, strikeout: self.strikeout, } } #[inline(always)] pub fn tail_chars(&self, r_start: usize) -> Compound<'s> { let mut rb_start = 0; for (char_idx, (byte_idx, _)) in self.as_str().char_indices().enumerate() { rb_start = byte_idx; if char_idx == r_start { break; } } self.tail(rb_start) } pub fn cut_tail(&mut self, tail_size: usize) -> Compound<'s> { let cut = self.src.len() - tail_size; let tail = Compound { src: &self.src[cut..], bold: self.bold,
random
[ { "content": "pub fn is_blank(s: &str) -> bool {\n\n s.chars().all(char::is_whitespace)\n\n}\n\n\n", "file_path": "src/clean.rs", "rank": 0, "score": 134340.7432941864 }, { "content": "/// count the number of '#' at start. Return 0 if they're\n\n/// not followed by a ' ' or if they're too...
Rust
src/sodium.rs
bob3000/thevault
8a60dc3a9aa892f1e16c820477bce97fb46c2c7a
use secstr::SecVec; use sodiumoxide::crypto::{pwhash, secretbox}; use std::io; use thiserror::Error; pub const HEADER_LEN: usize = 56; #[derive(Debug, Clone)] pub struct Crypto { key: secretbox::Key, nonce: secretbox::Nonce, salt: pwhash::Salt, } impl Crypto { pub async fn new_encrypter(password: &SecVec<u8>) -> anyhow::Result<Self> { let salt = pwhash::gen_salt(); let nonce = secretbox::gen_nonce(); let key = derrive_key(&password, salt); Ok(Crypto { key, nonce, salt }) } pub async fn new_decrypter( password: &SecVec<u8>, salt_slice: Vec<u8>, nonce_slice: Vec<u8>, ) -> anyhow::Result<Self, DecryptionError> { let salt = pwhash::Salt::from_slice(&salt_slice[..]).unwrap(); let nonce = secretbox::Nonce::from_slice(&nonce_slice[..]).unwrap(); let key = derrive_key(&password, salt); Ok(Crypto { key, nonce, salt }) } pub async fn encrypt(&self, plaintext: SecVec<u8>) -> Vec<u8> { secretbox::seal(&plaintext[..], &self.nonce, &self.key) } pub async fn decrypt(&self, cipher_package: &[u8]) -> Result<SecVec<u8>, DecryptionError> { match secretbox::open(&cipher_package, &self.nonce, &self.key) { Ok(t) => Ok(SecVec::new(t)), Err(_) => Err(DecryptionError::InvalidCipherLength), } } pub fn header(&self) -> Vec<u8> { let mut header = Vec::new(); header.append(&mut self.salt[..].to_vec()); header.append(&mut self.nonce[..].to_vec()); header } } fn derrive_key(password: &SecVec<u8>, salt: pwhash::Salt) -> secretbox::Key { let mut key = secretbox::Key([0; secretbox::KEYBYTES]); { let secretbox::Key(ref mut kb) = key; pwhash::derive_key( kb, &password.unsecure()[..], &salt, pwhash::OPSLIMIT_INTERACTIVE, pwhash::MEMLIMIT_INTERACTIVE, ) .unwrap(); } key } pub fn split_header(header: &[u8]) -> Result<(&[u8], &[u8]), DecryptionError> { if header.len() != HEADER_LEN { return Err(DecryptionError::InvalidCipherLength); } Ok((&header[..32], &header[32..])) } #[derive(Error, Debug)] pub enum DecryptionError { #[error("cipher text does not contain all necessary elements")] InvalidCipherLength, #[error("Improper header length")] HeaderError(#[from] io::Error), } #[cfg(test)] mod test { use super::*; use std::io::Cursor; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::test] async fn successful_encrypt_decrypt() { let password = SecVec::from("0123456789ABCDEF0123456789ABCDEF"); let message = SecVec::from("this is a very secret message!!!"); let mut cipher_package = Cursor::new(Vec::new()); let c = Crypto::new_encrypter(&password) .await .expect("error creating encrypter"); cipher_package.write_all(&c.header()).await.unwrap(); let ciphertext = c.encrypt(message.clone()).await; assert_ne!(&message.unsecure()[..], &ciphertext[..]); cipher_package .write_u32(ciphertext.len() as u32) .await .unwrap(); cipher_package.write_all(&ciphertext).await.unwrap(); cipher_package.set_position(0); let mut header = [0u8; HEADER_LEN]; cipher_package.read(&mut header).await.unwrap(); let (salt, init_vec) = split_header(&header).unwrap(); let d = Crypto::new_decrypter(&password, salt.to_vec(), init_vec.to_vec()) .await .expect("error creating crypto from cipher package"); let chunk_size = cipher_package.read_u32().await.unwrap(); let mut buf: Vec<u8> = Vec::with_capacity(chunk_size as usize); cipher_package.read_buf(&mut buf).await.unwrap(); let decrypted_text = d.decrypt(&buf).await.unwrap(); assert_eq!(&message.unsecure(), &decrypted_text.unsecure()); } }
use secstr::SecVec; use sodiumoxide::crypto::{pwhash, secretbox}; use std::io; use thiserror::Error; pub const HEADER_LEN: usize = 56; #[derive(Debug, Clone)] pub struct Crypto { key: secretbox::Key, nonce: secretbox::Nonce, salt: pwhash::Salt, } impl Crypto { pub async fn new_encrypter(password: &SecVec<u8>) -> anyhow::Result<Self> { let salt = pwhash::gen_salt(); let nonce = secretbox::gen_nonce(); let key = derrive_key(&password, salt); Ok(Crypto { key, nonce, salt }) } pub async fn new_decrypter( password: &SecVec<u8>, salt_slice: Vec<u8>, nonce_slice: Vec<u8>, ) -> anyhow::Result<Self, DecryptionError> { let salt = pwhash::Salt::from_slice(&salt_slice[..]).unwrap(); let nonce = secretbox::Nonce::from_slice(&nonce_slice[..]).unwrap(); let key = derrive_key(&password, salt); Ok(Crypto { key, nonce, salt }) } pub async fn encrypt(&self, plaintext: SecVec<u8>) -> Vec<u8> { secretbox::seal(&plaintext[..], &self.nonce, &self.key) } pub async fn decrypt(&self, cipher_package: &[u8]) -> Result<SecVec<u8>, DecryptionError> { match secretbox::open(&cipher_package, &self.nonce, &self.key) { Ok(t) => Ok(SecVec::new(t)), Err(_) => Err(DecryptionError::InvalidCipherLength), } } pub fn header(&self) -> Vec<u8> { let mut header = Vec::new(); header.append(&mut self.salt[..].to_vec()); header.append(&mut self.nonce[..].to_vec()); header } } fn derrive_key(password: &SecVec<u8>, salt: pwhash::Salt) -> secretbox::Key { let mut key = secretbox::Key([0; secretbox::KEYBYTES]); { let secretbox::Key(ref mut kb) = key; pwhash::derive_key( kb, &password.unsecure()[..], &salt, pwhash::OPSLIMIT_INTERACTIVE, pwhash::MEMLIMIT_INTERACTIVE, ) .unwrap(); } key } pub fn split_header(header: &[u8]) -> Result<(&[u8], &[u8]), DecryptionError> { if header.len() != HEADER_LEN { return Err(DecryptionError::InvalidCipherLength); } Ok((&header[..32], &header[32..])) } #[derive(Error, Debug)] pub enum DecryptionError { #[error("cipher text does not contain all necessary elements")] InvalidCipherLength, #[error("Improper header length")] HeaderError(#[from] io::Error), } #[cfg(test)] mod test { use super::*; use std::io::Cursor; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[tokio::test] async fn successful_encrypt_decrypt() { let password = SecVec::from("0123456789ABCDEF0123456789ABCDEF"); let message = SecVec::from("this is a very secret message!!!"); let mut cipher_package = Cursor::new(Vec::new());
}
let c = Crypto::new_encrypter(&password) .await .expect("error creating encrypter"); cipher_package.write_all(&c.header()).await.unwrap(); let ciphertext = c.encrypt(message.clone()).await; assert_ne!(&message.unsecure()[..], &ciphertext[..]); cipher_package .write_u32(ciphertext.len() as u32) .await .unwrap(); cipher_package.write_all(&ciphertext).await.unwrap(); cipher_package.set_position(0); let mut header = [0u8; HEADER_LEN]; cipher_package.read(&mut header).await.unwrap(); let (salt, init_vec) = split_header(&header).unwrap(); let d = Crypto::new_decrypter(&password, salt.to_vec(), init_vec.to_vec()) .await .expect("error creating crypto from cipher package"); let chunk_size = cipher_package.read_u32().await.unwrap(); let mut buf: Vec<u8> = Vec::with_capacity(chunk_size as usize); cipher_package.read_buf(&mut buf).await.unwrap(); let decrypted_text = d.decrypt(&buf).await.unwrap(); assert_eq!(&message.unsecure(), &decrypted_text.unsecure()); }
function_block-function_prefix_line
[ { "content": "// This function is searches for the encryption / decryption password on\n\n// different places in the following order:\n\n// 1. command line argument or environment variable\n\n// 2. password file\n\n// 3. read from TTY\n\npub fn get_password(\n\n password: &mut Option<String>,\n\n password...
Rust
src/fixed_heap.rs
rust-photogrammetry/hamming-queue
c7b7165ee000651a5323741fe7ec7d9a0192f766
#[derive(Clone, Debug)] pub struct FixedHammingHeap<T> { cap: usize, size: usize, worst: u32, distances: Vec<Vec<T>>, } impl<T> FixedHammingHeap<T> { pub fn new() -> Self { Self::default() } pub fn new_distances(distances: usize) -> Self { let mut s = Self::new(); s.set_distances(distances); s } pub fn set_capacity(&mut self, cap: usize) { assert_ne!(cap, 0); self.set_len(cap); self.cap = cap; self.worst = self.distances.len() as u32 - 1; if self.size == self.cap { self.update_worst(); } } pub fn set_len(&mut self, len: usize) { if len == 0 { let end = self.end(); for v in &mut self.distances[..=end] { v.clear(); } self.size = 0; self.worst = self.distances.len() as u32 - 1; } else if len < self.size { let end = self.end(); let mut remaining = self.size - len; for vec in &mut self.distances[..=end] { if vec.len() >= remaining { vec.drain(vec.len() - remaining..); break; } else { remaining -= vec.len(); vec.clear(); } } self.worst = self.distances.len() as u32 - 1; self.size = len; } } pub fn len(&self) -> usize { self.size } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn clear(&mut self) { assert_ne!( self.distances.len(), 0, "you must call set_distances() before calling clear()" ); let end = self.end(); for v in self.distances[..=end].iter_mut() { v.clear(); } self.size = 0; self.worst = self.distances.len() as u32 - 1; } pub fn set_distances(&mut self, distances: usize) { self.distances.clear(); self.distances.resize_with(distances, || vec![]); self.worst = self.distances.len() as u32 - 1; self.size = 0; } pub fn push(&mut self, distance: u32, item: T) -> bool { if self.size != self.cap { self.distances[distance as usize].push(item); self.size += 1; if self.size == self.cap { self.update_worst(); } true } else { unsafe { self.push_at_cap(distance, item) } } } pub fn fill_slice<'a>(&self, s: &'a mut [T]) -> &'a mut [T] where T: Clone, { let total_fill = std::cmp::min(s.len(), self.size); for (ix, f) in self.distances[..=self.end()] .iter() .flat_map(|v| v.iter()) .take(total_fill) .enumerate() { s[ix] = f.clone(); } &mut s[0..total_fill] } pub fn worst(&self) -> u32 { self.worst } pub fn at_cap(&self) -> bool { self.size == self.cap } pub fn iter(&mut self) -> impl Iterator<Item = (u32, &T)> { self.distances[..=self.end()] .iter() .enumerate() .flat_map(|(distance, v)| v.iter().map(move |item| (distance as u32, item))) } pub fn iter_mut(&mut self) -> impl Iterator<Item = (u32, &mut T)> { let end = self.end(); self.distances[..=end] .iter_mut() .enumerate() .flat_map(|(distance, v)| v.iter_mut().map(move |item| (distance as u32, item))) } pub unsafe fn push_at_cap(&mut self, distance: u32, item: T) -> bool { if distance < self.worst { self.distances[distance as usize].push(item); self.remove_worst(); true } else { false } } fn end(&self) -> usize { if self.at_cap() { self.worst as usize } else { self.distances.len() - 1 } } fn update_worst(&mut self) { self.worst = self.distances[0..=self.worst as usize] .iter() .rev() .position(|v| !v.is_empty()) .map(|n| self.worst - n as u32) .unwrap_or(self.distances.len() as u32 - 1); } fn remove_worst(&mut self) { self.distances[self.worst as usize].pop(); self.update_worst(); } } impl<T> Default for FixedHammingHeap<T> { fn default() -> Self { Self { cap: 0, size: 0, worst: 0, distances: vec![], } } } #[cfg(test)] #[test] fn test_fixed_heap() { let mut candidates: FixedHammingHeap<u32> = FixedHammingHeap::new(); candidates.set_distances(11); candidates.set_capacity(3); assert!(candidates.push(5, 0)); assert!(candidates.push(4, 1)); assert!(candidates.push(3, 2)); assert!(!candidates.push(6, 3)); assert!(!candidates.push(7, 4)); assert!(candidates.push(2, 5)); assert!(candidates.push(3, 6)); assert!(!candidates.push(10, 7)); assert!(!candidates.push(6, 8)); assert!(!candidates.push(4, 9)); assert!(candidates.push(1, 10)); assert!(candidates.push(2, 11)); let mut arr = [0; 3]; candidates.fill_slice(&mut arr); arr[1..3].sort_unstable(); assert_eq!(arr, [10, 5, 11]); }
#[derive(Clone, Debug)] pub struct FixedHammingHeap<T> { cap: usize, size: usize, worst: u32, distances: Vec<Vec<T>>, } impl<T> FixedHammingHeap<T> { pub fn new() -> Self { Self::default() } pub fn new_distances(distances: usize) -> Self { let mut s = Self::new(); s.set_distances(distances); s } pub fn set_capacity(&mut self, cap: usize) { assert_ne!(cap, 0); self.set_len(cap); self.cap = cap; self.worst = self.distances.len() as u32 - 1; if self.size == self.cap { self.update_worst(); } } pub fn set_len(&mut self, len: usize) { if len == 0 { let end = self.end(); for v in &mut self.distances[..=end] { v.clear(); } self.size = 0; self.worst = self.distances.len() as u32 - 1; } else if len < self.size { let end = self.end(); let mut remaining = self.size - len; for vec in &mut self.distances[..=end] { if vec.len() >= remaining { vec.drain(vec.len() - remaining..); break; } else { remaining -= vec.len(); vec.clear(); } } self.worst = self.distances.len() as u32 - 1; self.size = len; } } pub fn len(&self) -> usize { self.size } pub fn is_empty(&self) -> bool { self.size == 0 } pub fn clear(&mut self) { assert_ne!( self.distances.len(), 0, "you must call set_distances() before calling clear()" ); let end = self.end(); for v in self.distances[..=end].iter_mut() { v.clear(); } self.size = 0; self.worst = self.distances.len() as u32 - 1; } pub fn set_distances(&mut self, distances: usize) { self.distances.clear(); self.distances.resize_with(distances, || vec![]); self.worst = self.distances.len() as u32 - 1; self.size = 0; } pub fn push(&mut self, distance: u32, item: T) -> bool { if self.size != self.cap { self.distances[distance as usize].push(item); self.size += 1; if self.size == self.cap { self.update_worst(); } true } else { unsafe { self.push_at_cap(distance, item) } } } pub fn fill_slice<'a>(&self, s: &'a mut [T]) -> &'a mut [T] where T: Clone, { let total_fill = std::cmp::min(s.len(), self.size); for (ix, f) in self.distances[..=self.end()] .iter() .flat_map(|v| v.iter()) .take(total_fill) .enumerate() { s[ix] = f.clone(); } &mut s[0..total_fill] } pub fn worst(&self) -> u32 { self.worst } pub fn at_cap(&self) -> bool { self.size == self.cap } pub fn iter(&mut self) -> impl Iterator<Item = (u32, &T)> { self.distances[..=self.end()] .iter() .enumerate() .flat_map(|(distance, v)| v.iter().map(move |item| (distance as u32, item))) } pub fn iter_mut(&mut self) -> impl Iterator<Item = (u32, &mut T)> { let end = self.end(); self.distances[..=end] .iter_mut() .enumerate() .flat_map(|(distance, v)| v.iter_mut().map(move |item| (distance as u32, item))) } pub unsafe fn push_at_cap(&mut self, distance: u32, item: T) -> bool {
} fn end(&self) -> usize { if self.at_cap() { self.worst as usize } else { self.distances.len() - 1 } } fn update_worst(&mut self) { self.worst = self.distances[0..=self.worst as usize] .iter() .rev() .position(|v| !v.is_empty()) .map(|n| self.worst - n as u32) .unwrap_or(self.distances.len() as u32 - 1); } fn remove_worst(&mut self) { self.distances[self.worst as usize].pop(); self.update_worst(); } } impl<T> Default for FixedHammingHeap<T> { fn default() -> Self { Self { cap: 0, size: 0, worst: 0, distances: vec![], } } } #[cfg(test)] #[test] fn test_fixed_heap() { let mut candidates: FixedHammingHeap<u32> = FixedHammingHeap::new(); candidates.set_distances(11); candidates.set_capacity(3); assert!(candidates.push(5, 0)); assert!(candidates.push(4, 1)); assert!(candidates.push(3, 2)); assert!(!candidates.push(6, 3)); assert!(!candidates.push(7, 4)); assert!(candidates.push(2, 5)); assert!(candidates.push(3, 6)); assert!(!candidates.push(10, 7)); assert!(!candidates.push(6, 8)); assert!(!candidates.push(4, 9)); assert!(candidates.push(1, 10)); assert!(candidates.push(2, 11)); let mut arr = [0; 3]; candidates.fill_slice(&mut arr); arr[1..3].sort_unstable(); assert_eq!(arr, [10, 5, 11]); }
if distance < self.worst { self.distances[distance as usize].push(item); self.remove_worst(); true } else { false }
if_condition
[ { "content": "/// ```\n\n/// use hamming_heap::HammingHeap;\n\n/// let mut candidates = HammingHeap::new_distances(129);\n\n/// candidates.push((0u128 ^ !0u128).count_ones(), ());\n\n/// ```\n\n#[derive(Clone, Debug)]\n\npub struct HammingHeap<T> {\n\n distances: Vec<Vec<T>>,\n\n best: u32,\n\n}\n\n\n\nim...
Rust
explorer/src/pages/mod.rs
trustfractal/protocol
f6ccaeddc88e6fd2edb33aa522efe0526dce952a
use actix_web::{error::*, *}; use block_pool::Pool; use ramhorns::{Content, Ramhorns}; use std::collections::BTreeMap; use crate::data::*; pub fn resources() -> Vec<Resource> { vec![ web::resource("/").to(home), web::resource("/metrics/identities").to(metrics_identities), ] } pub fn templates() -> anyhow::Result<Ramhorns> { let mod_file = std::path::PathBuf::from(file!()); let pages = mod_file.parent().unwrap(); Ok(Ramhorns::from_folder(pages)?) } #[derive(Content)] struct Page { page: String, } fn html_page( templates: web::Data<Ramhorns>, content: impl ToString, ) -> actix_web::Result<HttpResponse> { let page = Page { page: content.to_string(), }; Ok(HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body( templates .get("root.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&page), )) } #[derive(Content)] struct IdentityCounts { points: Vec<Point>, latest: Latest, deltas: Vec<Delta>, } #[derive(Content)] struct Point { x: f32, y: f32, } #[derive(Content, Default)] struct Latest { block: u64, count: u64, } #[derive(Content)] struct Delta { name: String, amount: u64, percent: f32, } impl Delta { fn from_diff_values(block_diff: u64, name: &str, values: &BTreeMap<u64, u64>) -> Option<Self> { let (max_block, max_count) = values.range(..).next_back()?; let prev_block = max_block.checked_sub(block_diff)?; let (_, prev_count) = values.range(..=prev_block).next_back()?; if *prev_count == 0 { return None; } Some(Delta { name: name.to_string(), amount: max_count - prev_count, percent: ((*max_count as f32 / *prev_count as f32) - 1.) * 100., }) } } async fn metrics_identities( templates: web::Data<Ramhorns>, pg: web::Data<Pool<postgres::Client>>, ) -> actix_web::Result<HttpResponse> { let deltas = { const DAY: u64 = 14400; let mut map = BTreeMap::new(); map.insert(DAY, "Day"); map.insert(DAY * 7, "Week"); map.insert(DAY * 91, "Quarter"); map.insert(DAY * 365, "Year"); map }; let include_block_deltas = deltas.keys().cloned().collect::<Vec<_>>(); let values = retry_blocking(move || { let mut pg = pg.take(); let include = include_block_deltas.clone(); crate::indexing::identities::get_counts(1000, include, &mut pg) }) .await .map_err(ErrorInternalServerError)?; let deltas = deltas .into_iter() .filter_map(|(diff, name)| Delta::from_diff_values(diff, name, &values)) .collect(); let latest = values .range(..) .next_back() .map(|(&block, &count)| Latest { block, count }) .unwrap_or_default(); let counts = IdentityCounts { points: values .into_iter() .map(|(x, y)| Point { x: x as f32, y: y as f32, }) .collect(), latest, deltas, }; let page = templates .get("metrics/identities.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&counts); Ok(html_page(templates, page)?) } async fn retry_blocking<R, E, F>(f: F) -> Result<R, E> where F: FnMut() -> Result<R, E> + Send + 'static, R: Send + 'static, E: Send + core::fmt::Debug + 'static, { let mut tries = 3; let f = std::sync::Arc::new(std::sync::Mutex::new(f)); loop { let f = std::sync::Arc::clone(&f); let result = web::block(move || { let mut f = f.lock().unwrap(); f() }) .await; match result { Ok(v) => return Ok(v), Err(BlockingError::Error(e)) => return Err(e), Err(BlockingError::Canceled) => { tries -= 1; if tries == 0 { panic!("Blocking call cancelled."); } else { log::warn!("Blocking call cancelled."); } } } } } pub async fn not_found() -> actix_web::Result<String> { Err(error::ErrorNotFound("Not Found")) } #[derive(Content)] struct HomeData { blocks: Vec<Block>, extrinsics: Vec<ExtrinsicNoJson>, } async fn home( templates: web::Data<Ramhorns>, pg: web::Data<Pool<postgres::Client>>, ) -> actix_web::Result<HttpResponse> { let home_data = retry_blocking(move || get_home_data(&mut pg.take())) .await .map_err(ErrorInternalServerError)?; let page = templates .get("home.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&home_data); Ok(html_page(templates, page)?) } fn get_home_data(pg: &mut postgres::Client) -> anyhow::Result<HomeData> { let blocks = pg .query( "SELECT json FROM block_json ORDER BY number DESC LIMIT 20", &[], )? .into_iter() .map(|row| serde_json::from_str(row.get(&"json"))) .collect::<Result<_, _>>()?; let extrinsics = pg .query( "SELECT json FROM extrinsic_json WHERE CAST(json AS json)->>'section' != 'timestamp' AND CAST(json AS json)->>'success' = 'true' ORDER BY block_number DESC, index LIMIT 20", &[], )? .into_iter() .map(|row| serde_json::from_str(row.get(&"json")).map(|e: Extrinsic| e.without_json)) .collect::<Result<_, _>>()?; Ok(HomeData { blocks, extrinsics }) }
use actix_web::{error::*, *}; use block_pool::Pool; use ramhorns::{Content, Ramhorns}; use std::collections::BTreeMap; use crate::data::*; pub fn resources() -> Vec<Resource> { vec![ web::resource("/").to(home), web::resource("/metrics/identities").to(metrics_identities), ] } pub fn templates() -> anyhow::Result<Ramhorns> { let mod_file = std::path::PathBuf::from(file!()); let pages = mod_file.parent().unwrap(); Ok(Ramhorns::from_folder(pages)?) } #[derive(Content)] struct Page { page: String, } fn html_page( templates: web::Data<Ramhorns>, content: impl ToString, ) -> actix_web::Result<HttpResponse> { let page = Page { page: content.to_string(), }; Ok(HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body( templates .get("root.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&page), )) } #[derive(Content)] struct IdentityCounts { points: Vec<Point>, latest: Latest, deltas: Vec<Delta>, } #[derive(Content)] struct Point { x: f32, y: f32, } #[derive(Content, Default)] struct Latest { block: u64, count: u64, } #[derive(Content)] struct Delta { name: String, amount: u64, percent: f32, } impl Delta { fn from_diff_values(block_diff: u64, name: &str, values: &BTreeMap<u64, u64>) -> Option<Self> { let (max_block, max_count) = values.range(..).next_back()?; let prev_block = max_block.checked_sub(block_diff)?; let (_, prev_count) = values.range(..=prev_block).next_back()?; if *prev_count == 0 { return None; } Some(Delta { name: name.to_string(), amount: max_count - prev_count, percent: ((*max_count as f32 / *prev_count as f32) - 1.) * 100., }) } } async fn metrics_identities( templates: web::Data<Ramhorns>, pg: web::Data<Pool<postgres::Client>>, ) -> actix_web::Result<HttpResponse> { let deltas = { const DAY: u64 = 14400; let mut map = BTreeMap::new(); map.insert(DAY, "Day"); map.insert(DAY * 7, "Week"); map.insert(DAY * 91, "Quarter"); map.insert(DAY * 365, "Year"); map }; let include_block_deltas = deltas.keys().cloned().collect::<Vec<_>>(); let values = retry_blocking(move || { let mut pg = pg.take(); let include = include_block_deltas.clone(); crate::indexing::identities::get_counts(1000, include, &mut pg) }) .await .map_err(ErrorInternalServerError)?; let deltas = deltas .into_iter() .filter_map(|(diff, name)| Delta::from_diff_values(diff, name, &values)) .collect(); let latest = values .range(..) .next_back() .map(|(&block, &count)| Latest { block, count }) .unwrap_or_default(); let counts = IdentityCounts { points: values .into_iter() .map(|(x, y)| Point { x: x as f32, y: y as f32, }) .collect(), latest, deltas, }; let page = templates .get("metrics/identities.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&counts); Ok(html_page(templates, page)?) } async fn retry_blocking<R, E, F>(f: F) -> Result<R, E> where F: FnMut() -> Result<R, E> + Send + 'static, R: Send + 'static, E: Send + core::fmt::Debug + 'static, { let mut tries = 3; let f = std::sync::Arc::new(std::sync::Mutex::new(f)); loop { let f = std::sync::Arc::clone(&f); let result = web::block(move || { let mut f = f.lock().unwrap(); f() }) .await; match result { Ok(v) => return Ok(v), Err(BlockingError::Error(e)) => return Err(e), Err(BlockingError::Canceled) => { tries -= 1; if tries == 0 { panic!("Blocking call cancelled."); } else { log::warn!("Blocking call cancelled."); } } } } } pub async fn not_found() -> actix_web::Result<String> { Err(error::ErrorNotFound("Not Found")) } #[derive(Content)] struct HomeData { blocks: Vec<Block>, extrinsics: Vec<ExtrinsicNoJson>, } async fn home( templates: web::Data<Ramhorns>, pg: web::Data<Pool<postgres::Client>>, ) -> actix_web::Result<HttpResponse> { let home_data = retry_blocking(move || get_home_data(&mut pg.take())) .await .map_err(ErrorInternalServerError)?; let page = templates .get("home.html") .ok_or_else(|| ErrorInternalServerError("Could not find template"))? .render(&home_data); Ok(html_page(templates, page)?) }
fn get_home_data(pg: &mut postgres::Client) -> anyhow::Result<HomeData> { let blocks = pg .query( "SELECT json FROM block_json ORDER BY number DESC LIMIT 20", &[], )? .into_iter() .map(|row| serde_json::from_str(row.get(&"json"))) .collect::<Result<_, _>>()?; let extrinsics = pg .query( "SELECT json FROM extrinsic_json WHERE CAST(json AS json)->>'section' != 'timestamp' AND CAST(json AS json)->>'success' = 'true' ORDER BY block_number DESC, index LIMIT 20", &[], )? .into_iter() .map(|row| serde_json::from_str(row.get(&"json")).map(|e: Extrinsic| e.without_json)) .collect::<Result<_, _>>()?; Ok(HomeData { blocks, extrinsics }) }
function_block-full_function
[ { "content": "fn get_key(key: impl AsRef<str>, pg: &mut Client) -> anyhow::Result<Option<String>> {\n\n Ok(pg\n\n .query_opt(\n\n \"SELECT value FROM key_values WHERE key = $1\",\n\n &[&key.as_ref()],\n\n )?\n\n .map(|row| row.get::<_, &str>(&\"value\").to_string())...
Rust
core/src/parse/error.rs
bharadwaj1098/yatima
639e17d9644b89d27fd75be98ecb7dac91bb9e3b
use crate::{ name::Name, parse::{ base, span::Span, }, term::{ LitType, Literal, }, }; use nom::{ error::ErrorKind, AsBytes, Err, IResult, InputLength, }; #[cfg(feature = "std")] use std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; #[cfg(not(feature = "std"))] use sp_std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; use sp_im::conslist::ConsList; use alloc::string::String; #[derive(PartialEq, Debug, Clone)] pub enum ParseErrorKind { UndefinedReference(Name, ConsList<Name>), TopLevelRedefinition(Name), UnknownLiteralType(String), InvalidBaseEncoding(base::LitBase), UnknownBaseCode, ExpectedSingleChar(Vec<char>), InvalidBase16EscapeSequence(String), MultibaseError(multibase::Error), CidError, ParseIntErr(ParseIntError), ReservedKeyword(String), NumericSyntax(String), ReservedSyntax(String), LiteralLacksWhitespaceTermination(Literal), LitTypeLacksWhitespaceTermination(LitType), UnknownNatOp(Name), UnknownIntOp(Name), UnknownBitsOp(Name), UnknownBytesOp(Name), UnknownBoolOp(Name), UnknownTextOp(Name), UnknownCharOp(Name), UnknownU8Op(Name), UnknownU16Op(Name), UnknownU32Op(Name), UnknownU64Op(Name), UnknownU128Op(Name), UnknownI8Op(Name), UnknownI16Op(Name), UnknownI32Op(Name), UnknownI64Op(Name), UnknownI128Op(Name), TypeDefConstructorMustReturnItsType, InvalidSymbol(String), Nom(ErrorKind), } impl<'a> fmt::Display for ParseErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::UndefinedReference(name, _) => { write!(f, "Undefined reference {}", name) } Self::TopLevelRedefinition(name) => { write!( f, "Overlapping definition names, \"{}\" already defined or imported", name ) } Self::ExpectedSingleChar(chrs) => { write!( f, "Character literal syntax must contain one and only one character, \ but parsed {:?}", chrs ) } Self::InvalidBase16EscapeSequence(seq) => { write!(f, "Unknown base 16 string escape sequence {}.", seq) } Self::ParseIntErr(e) => { write!(f, "Error parsing number: {}", e) } Self::ReservedKeyword(name) => { write!(f, "{}` is a reserved language keyword", name) } Self::ReservedSyntax(_) => { write!(f, "Symbols beginning with '#' are reserved") } Self::NumericSyntax(_) => { write!(f, "Symbols beginning with digits are reserved") } Self::InvalidSymbol(name) => { write!( f, "The symbol {} contains a reserved character ':', '(', ')', ',', or \ whitespace or control character.", name ) } Self::LiteralLacksWhitespaceTermination(x) => { write!(f, "Literal {} must be terminated by whitespace or eof", x) } Self::LitTypeLacksWhitespaceTermination(x) => { write!(f, "Literal type {} must be terminated by whitespace or eof", x) } Self::UnknownNatOp(x) => { write!(f, "Unknown primitive Nat operation #Nat.{}", x) } Self::UnknownIntOp(x) => { write!(f, "Unknown primitive Int operation #Int.{}", x) } Self::UnknownBytesOp(x) => { write!(f, "Unknown primitive Bytes operation #Bytes.{}", x) } Self::UnknownTextOp(x) => { write!(f, "Unknown primitive Nat operation #Text.{}", x) } _ => write!(f, "internal parser error"), } } } impl ParseErrorKind { pub fn is_nom_err(&self) -> bool { matches!(self, Self::Nom(_)) } } #[derive(PartialEq, Debug, Clone)] pub struct ParseError<I: AsBytes> { pub input: I, pub expected: Option<&'static str>, pub errors: Vec<ParseErrorKind>, } impl<I: AsBytes> ParseError<I> { pub fn new(input: I, error: ParseErrorKind) -> Self { ParseError { input, expected: None, errors: vec![error] } } } impl<'a> fmt::Display for ParseError<Span<'a>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut res = String::new(); writeln!( &mut res, "at line {}:{}", self.input.location_line(), self.input.get_column() )?; let line = String::from_utf8_lossy(self.input.get_line_beginning()); writeln!(&mut res, "{} | {}", self.input.location_line(), line)?; let cols = format!("{} | ", self.input.location_line()).len() + self.input.get_column(); for _ in 0..(cols - 1) { write!(&mut res, " ")?; } writeln!(&mut res, "^")?; if let Some(exp) = self.expected { writeln!(&mut res, "Expected {}", exp)?; } let mut errs = self.errors.iter().filter(|x| !x.is_nom_err()).peekable(); if errs.peek() == None { writeln!(&mut res, "Internal parser error")?; } else { writeln!(&mut res, "Reported errors:")?; for kind in errs { writeln!(&mut res, "- {}", kind)?; } } write!(f, "{}", res) } } impl<I: AsBytes> nom::error::ParseError<I> for ParseError<I> where I: InputLength, I: Clone, { fn from_error_kind(input: I, kind: ErrorKind) -> Self { ParseError::new(input, ParseErrorKind::Nom(kind)) } fn append(input: I, kind: ErrorKind, mut other: Self) -> Self { match input.input_len().cmp(&other.input.input_len()) { Ordering::Less => ParseError::new(input, ParseErrorKind::Nom(kind)), Ordering::Equal => { other.errors.push(ParseErrorKind::Nom(kind)); other } Ordering::Greater => other, } } fn or(self, mut other: Self) -> Self { match self.input.input_len().cmp(&other.input.input_len()) { Ordering::Less => self, Ordering::Equal => { for x in self.errors { other.errors.push(x); } other } Ordering::Greater => other, } } } impl<I: AsBytes> nom::error::ContextError<I> for ParseError<I> where I: InputLength, I: Clone, { fn add_context(input: I, ctx: &'static str, other: Self) -> Self { match input.input_len().cmp(&other.input.input_len()) { Ordering::Less => { ParseError { input, expected: Some(ctx), errors: vec![] } } Ordering::Equal => match other.expected { None => ParseError { input, expected: Some(ctx), errors: other.errors }, _ => other, }, Ordering::Greater => other, } } } pub fn throw_err<I: AsBytes, A, F: Fn(ParseError<I>) -> ParseError<I>>( x: IResult<I, A, ParseError<I>>, f: F, ) -> IResult<I, A, ParseError<I>> { match x { Ok(res) => Ok(res), Err(Err::Incomplete(n)) => Err(Err::Incomplete(n)), Err(Err::Error(e)) => Err(Err::Error(f(e))), Err(Err::Failure(e)) => Err(Err::Failure(f(e))), } }
use crate::{ name::Name, parse::{ base, span::Span, }, term::{ LitType, Literal, }, }; use nom::{ error::ErrorKind, AsBytes, Err, IResult, InputLength, }; #[cfg(feature = "std")] use std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; #[cfg(not(feature = "std"))] use sp_std::{ cmp::Ordering, fmt, fmt::Write, num::ParseIntError, vec::Vec, }; use sp_im::conslist::ConsList; use alloc::string::String; #[derive(PartialEq, Debug, Clone)] pub enum ParseErrorKind { UndefinedReference(Name, ConsList<Name>), TopLevelRedefinition(Name), UnknownLiteralType(String), InvalidBaseEncoding(base::LitBase), UnknownBaseCode, ExpectedSingleChar(Vec<char>), InvalidBase16EscapeSequence(String), MultibaseError(multibase::Error), CidError, ParseIntErr(ParseIntError), ReservedKeyword(String), NumericSyntax(String), ReservedSyntax(String), LiteralLacksWhitespaceTermination(Literal), LitTypeLacksWhitespaceTermination(LitType), UnknownNatOp(Name), UnknownIntOp(Name), UnknownBitsOp(Name), UnknownBytesOp(Name), UnknownBoolOp(Name), UnknownTextOp(Name), UnknownCharOp(Name), UnknownU8Op(Name), UnknownU16Op(Name), UnknownU32Op(Name), UnknownU64Op(Name), UnknownU128Op(Name), UnknownI8Op(Name), UnknownI16Op(Name), UnknownI32Op(Name), UnknownI64Op(Name), UnknownI128Op(Name), TypeDefConstructorMustReturnItsType, InvalidSymbol(String), Nom(ErrorKind), } impl<'a> fmt::Display for ParseErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::UndefinedReference(name, _) => { write!(f, "Undefined reference {}", name) } Self::TopLevelRedefinition(name) => { write!( f, "Overlapping definition names, \"{}\" already defined or imported", name ) } Self::ExpectedSingleChar(chrs) => { write!( f, "Character literal syntax must contain one and only one character, \ but parsed {:?}", chrs ) } Self::InvalidBase16EscapeSequence(seq) => { write!(f, "Unknown base 16 string escape sequence {}.", seq) } Self::ParseIntErr(e) => { write!(f, "Error parsing number: {}", e) } Self::ReservedKeyword(name) => { write!(f, "{}` is a reserved language keyword", name) } Self::ReservedSyntax(_) => { write!(f, "Symbols beginning with '#' are reserved") } Self::NumericSyntax(_) => { write!(f, "Symbols beginning with digits are reserved") } Self::InvalidSymbol(name) => { write!( f, "The symbol {} contains a reserved character ':', '(', ')', ',', or \ whitespace or control character.", name ) } Self::LiteralLacksWhitespaceTermination(x) => { write!(f, "Literal {} must be terminated by whitespace or eof", x) } Self::LitTypeLacksWhitespaceTermination(x) => { write!(f, "Literal type {} must be terminated by whitespace or eof", x) } Self::UnknownNatOp(x) => { write!(f, "Unknown primitive Nat operation #Nat.{}", x) } Self::UnknownIntOp(x) => { write!(f, "Unknown primitive Int operation #Int.{}", x) } Self::UnknownBytesOp(x) => { write!(f, "Unknown primitive Bytes operation #Bytes.{}", x) } Self::UnknownTextOp(x) => { write!(f, "Unknown primitive Nat operation #Text.{}", x) } _ => write!(f, "internal parser error"), } } } impl ParseErrorKind { pub fn is_nom_err(&self) -> bool { matches!(self, Self::Nom(_)) } } #[derive(PartialEq, Debug, Clone)] pub struct ParseError<I: AsBytes> { pub input: I, pub expected: Option<&'static str>, pub errors: Vec<ParseErrorKind>, } impl<I: AsBytes> ParseError<I> { pub fn new(input: I, error: ParseErrorKind) -> Self { ParseError { input, expected: None, errors: vec![error] } } } impl<'a> fmt::Display for ParseError<Span<'a>> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut res = String::new(); writeln!( &mut res, "at line {}:{}", self.input.location_line(), self.input.get_column() )?; let line = String::from_utf8_lossy(self.input.get_line_beginning()); writeln!(&mut res, "{} | {}", self.input.location_line(), line)?; let cols = format!("{} | ", self.input.location_line()).len() + self.input.get_column(); for _ in 0..(cols - 1) { write!(&mut res, " ")?; } writeln!(&mut res, "^")?; if let Some(exp) = self.expected { writeln!(&mut res, "Expected {}", exp)?; } let mut errs = self.errors.iter().filter(|x| !x.is_nom_err()).peekable(); if errs.peek() == None { writeln!(&mut res, "Internal parser error")?; } else { writeln!(&mut res, "Reported errors:")?; for kind in errs { writeln!(&mut res, "- {}", kind)?; } } write!(f, "{}", res) } } impl<I: AsBytes> nom::error::ParseError<I> for ParseError<I> where I: InputLength, I: Clone, { fn from_error_kind(input: I, kind: ErrorKind) -> Self { ParseError::new(input, ParseErrorKind::Nom(kind)) } fn append(input: I, kind: ErrorKind, mut other: Self) -> Self { match input.input_len().cmp(&other.input.input_len()) { Ordering::Less => ParseError::new(input, ParseErrorKind::Nom(kind)), Ordering::Equal => { other.errors.push(ParseErrorKind::Nom(kind)); other } Ordering::Greater => other, } } fn or(self, mut other: Self) -> Self { match self.input.input_len().cmp(&other.input.input_len()) { Ordering::Less => self, Ordering::Equal => { for x in self.errors { other.errors.push(x); } other } Ordering::Greater => other, } } } impl<I: AsBytes> nom::error::ContextError<I> for ParseError<I> where I: InputLength, I: Clone, { fn add_context(input: I, ctx: &'static str, other: Self) -> Self { match input.input_len().cmp(&other.input.input_len()) { Ordering::Less => { ParseError { input, expected: Some(ctx), errors: vec![] } } Ordering::Equal => match other.expected { None => ParseError { input, expected: Some(ctx), errors: other.errors }, _ => other, }, Ordering::Greater => other, } } } pub fn throw_err<I: AsBytes, A, F: Fn(ParseError<I>) -> ParseError<I>>( x: IResult<I, A, ParseError<I>>, f: F, ) -> IResult<I, A, ParseError<
I>> { match x { Ok(res) => Ok(res), Err(Err::Incomplete(n)) => Err(Err::Incomplete(n)), Err(Err::Error(e)) => Err(Err::Error(f(e))), Err(Err::Failure(e)) => Err(Err::Failure(f(e))), } }
function_block-function_prefixed
[ { "content": "pub fn is_valid_symbol_string(s: &str) -> bool {\n\n let invalid_chars = s.starts_with('\"')\n\n || s.starts_with('\\'')\n\n || s.starts_with('#')\n\n || s.chars().any(|x| !is_valid_symbol_char(x));\n\n !s.is_empty() && !invalid_chars\n\n}\n\n\n", "file_path": "core/src/parse/term.r...
Rust
lib/tracing-metrics/examples/echo.rs
sudharsh/vector
8b61656965f630582187a18e04d0812484ad9196
extern crate futures; extern crate hyper; #[macro_use] extern crate tracing; extern crate tokio; extern crate tracing_fmt; extern crate tracing_futures; use futures::future; use hyper::rt::{Future, Stream}; use hyper::server::conn::Http; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, StatusCode}; use std::str; use tracing::field; use tracing_futures::{Instrument, Instrumented}; type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>; fn echo(req: Request<Body>) -> Instrumented<BoxFut> { trace_span!( "request", method = &field::debug(req.method()), uri = &field::debug(req.uri()), headers = &field::debug(req.headers()) ) .in_scope(|| { info!("received request"); let mut response = Response::new(Body::empty()); let (rsp_span, fut): (_, BoxFut) = match (req.method(), req.uri().path()) { (&Method::GET, "/") => { const BODY: &'static str = "Try POSTing data to /echo"; *response.body_mut() = Body::from(BODY); ( trace_span!("response", body = &field::display(&BODY)), Box::new(future::ok(response)), ) } (&Method::POST, "/echo") => { let body = req.into_body(); let span = trace_span!("response", response_kind = &"echo"); *response.body_mut() = body; (span, Box::new(future::ok(response))) } (&Method::POST, "/echo/uppercase") => { let mapping = req.into_body().map(|chunk| { let upper = chunk .iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>(); debug!( { chunk = field::debug(str::from_utf8(&chunk[..])), uppercased = field::debug(str::from_utf8(&upper[..])) }, "uppercased request body" ); upper }); *response.body_mut() = Body::wrap_stream(mapping); ( trace_span!("response", response_kind = "uppercase"), Box::new(future::ok(response)), ) } (&Method::POST, "/echo/reversed") => { let span = trace_span!("response", response_kind = "reversed"); let reversed = span.in_scope(|| { req.into_body().concat2().map(move |chunk| { let body = chunk.iter().rev().cloned().collect::<Vec<u8>>(); debug!( { chunk = field::debug(str::from_utf8(&chunk[..])), body = field::debug(str::from_utf8(&body[..])) }, "reversed request body"); *response.body_mut() = Body::from(body); response }) }); (span, Box::new(reversed)) } _ => { *response.status_mut() = StatusCode::NOT_FOUND; ( trace_span!( "response", body = &field::debug(()), status = &field::debug(&StatusCode::NOT_FOUND) ), Box::new(future::ok(response)), ) } }; fut.instrument(rsp_span) }) } fn main() { use hotmic::Receiver; let mut receiver = Receiver::builder().build(); let sink = receiver.get_sink(); let controller = receiver.get_controller(); std::thread::spawn(move || { receiver.run(); }); std::thread::spawn(move || loop { std::thread::sleep(std::time::Duration::from_secs(2)); let _snapshot = controller.get_snapshot().unwrap(); }); let subscriber = tracing_fmt::FmtSubscriber::builder().finish(); tracing_env_logger::try_init().expect("init log adapter"); let subscriber = tracing_metrics::MetricsSubscriber::new(subscriber, sink); tracing::subscriber::with_default(subscriber, || { let addr: ::std::net::SocketAddr = ([127, 0, 0, 1], 3000).into(); let server_span = trace_span!("server", local = &field::debug(addr)); let server = tokio::net::TcpListener::bind(&addr) .expect("bind") .incoming() .fold(Http::new(), move |http, sock| { let span = trace_span!( "connection", remote = &field::debug(&sock.peer_addr().unwrap()) ); hyper::rt::spawn( http.serve_connection(sock, service_fn(echo)) .and_then(|_| { println!("Connection is done!"); Ok(()) }) .map_err(|e| { error!({ error = field::display(e) }, "serve error"); }) .instrument(span), ); Ok::<_, ::std::io::Error>(http) }) .map(|_| ()) .map_err(|e| { error!({ error = field::display(e) }, "server error"); }) .instrument(server_span.clone()); server_span.in_scope(|| { info!("listening..."); hyper::rt::run(server); }); }) }
extern crate futures; extern crate hyper; #[macro_use] extern crate tracing; extern crate tokio; extern crate tracing_fmt; extern crate tracing_futures; use futures::future; use hyper::rt::{Future, Stream}; use hyper::server::conn::Http; use hyper::service::service_fn; use hyper::{Body, Method, Request, Response, StatusCode}; use std::str; use tracing::field; use tracing_futures::{Instrument, Instrumented}; type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>;
fn main() { use hotmic::Receiver; let mut receiver = Receiver::builder().build(); let sink = receiver.get_sink(); let controller = receiver.get_controller(); std::thread::spawn(move || { receiver.run(); }); std::thread::spawn(move || loop { std::thread::sleep(std::time::Duration::from_secs(2)); let _snapshot = controller.get_snapshot().unwrap(); }); let subscriber = tracing_fmt::FmtSubscriber::builder().finish(); tracing_env_logger::try_init().expect("init log adapter"); let subscriber = tracing_metrics::MetricsSubscriber::new(subscriber, sink); tracing::subscriber::with_default(subscriber, || { let addr: ::std::net::SocketAddr = ([127, 0, 0, 1], 3000).into(); let server_span = trace_span!("server", local = &field::debug(addr)); let server = tokio::net::TcpListener::bind(&addr) .expect("bind") .incoming() .fold(Http::new(), move |http, sock| { let span = trace_span!( "connection", remote = &field::debug(&sock.peer_addr().unwrap()) ); hyper::rt::spawn( http.serve_connection(sock, service_fn(echo)) .and_then(|_| { println!("Connection is done!"); Ok(()) }) .map_err(|e| { error!({ error = field::display(e) }, "serve error"); }) .instrument(span), ); Ok::<_, ::std::io::Error>(http) }) .map(|_| ()) .map_err(|e| { error!({ error = field::display(e) }, "server error"); }) .instrument(server_span.clone()); server_span.in_scope(|| { info!("listening..."); hyper::rt::run(server); }); }) }
fn echo(req: Request<Body>) -> Instrumented<BoxFut> { trace_span!( "request", method = &field::debug(req.method()), uri = &field::debug(req.uri()), headers = &field::debug(req.headers()) ) .in_scope(|| { info!("received request"); let mut response = Response::new(Body::empty()); let (rsp_span, fut): (_, BoxFut) = match (req.method(), req.uri().path()) { (&Method::GET, "/") => { const BODY: &'static str = "Try POSTing data to /echo"; *response.body_mut() = Body::from(BODY); ( trace_span!("response", body = &field::display(&BODY)), Box::new(future::ok(response)), ) } (&Method::POST, "/echo") => { let body = req.into_body(); let span = trace_span!("response", response_kind = &"echo"); *response.body_mut() = body; (span, Box::new(future::ok(response))) } (&Method::POST, "/echo/uppercase") => { let mapping = req.into_body().map(|chunk| { let upper = chunk .iter() .map(|byte| byte.to_ascii_uppercase()) .collect::<Vec<u8>>(); debug!( { chunk = field::debug(str::from_utf8(&chunk[..])), uppercased = field::debug(str::from_utf8(&upper[..])) }, "uppercased request body" ); upper }); *response.body_mut() = Body::wrap_stream(mapping); ( trace_span!("response", response_kind = "uppercase"), Box::new(future::ok(response)), ) } (&Method::POST, "/echo/reversed") => { let span = trace_span!("response", response_kind = "reversed"); let reversed = span.in_scope(|| { req.into_body().concat2().map(move |chunk| { let body = chunk.iter().rev().cloned().collect::<Vec<u8>>(); debug!( { chunk = field::debug(str::from_utf8(&chunk[..])), body = field::debug(str::from_utf8(&body[..])) }, "reversed request body"); *response.body_mut() = Body::from(body); response }) }); (span, Box::new(reversed)) } _ => { *response.status_mut() = StatusCode::NOT_FOUND; ( trace_span!( "response", body = &field::debug(()), status = &field::debug(&StatusCode::NOT_FOUND) ), Box::new(future::ok(response)), ) } }; fut.instrument(rsp_span) }) }
function_block-full_function
[ { "content": "type Error = Box<std::error::Error + 'static + Send + Sync>;\n\n\n\nimpl<T, S, B> Sink for BatchServiceSink<T, S, B>\n\nwhere\n\n S: Service<T>,\n\n S::Error: Into<Error>,\n\n S::Response: std::fmt::Debug,\n\n B: Batch<Output = T>,\n\n{\n\n type SinkItem = B;\n\n type SinkError =...
Rust
aorist_core/src/driver/python.rs
scie-nz/aorist
ac1e31251af7d851c4491a310b417de880b79d09
use abi_stable::std_types::ROption; use aorist_primitives::AOption; use crate::constraint::TConstraintEnum; use crate::constraint::{OuterConstraint, TBuilder}; use crate::constraint_state::ConstraintState; use aorist_primitives::Dialect; use crate::driver::{ConstraintsBlockMap, Driver}; use crate::flow::{ETLFlow, FlowBuilderBase, PythonBasedFlowBuilder}; use crate::program::TOuterProgram; use crate::python::{PythonBasedConstraintBlock, PythonImport, PythonPreamble}; use abi_stable::external_types::parking_lot::rw_lock::RRwLock; use abi_stable::std_types::RArc; use anyhow::Result; use aorist_ast::AncestorRecord; use aorist_primitives::AUuid; use aorist_primitives::{AString, AVec, Ancestry, AoristConcept, AoristUniverse, ToplineConcept}; use linked_hash_map::LinkedHashMap; use linked_hash_set::LinkedHashSet; use std::collections::{BTreeSet, HashMap}; use std::marker::PhantomData; pub struct PythonBasedDriver<'a, B, D, U, C, A, P> where U: AoristConcept + AoristUniverse, B: TBuilder<'a, TEnum = C, TAncestry = A>, D: FlowBuilderBase<U> + PythonBasedFlowBuilder<U>, <D as FlowBuilderBase<U>>::T: 'a, <D as FlowBuilderBase<U>>::T: ETLFlow<U, ImportType = PythonImport, PreambleType = PythonPreamble> + 'a, A: Ancestry, C: ToplineConcept<TUniverse = U>, <B as TBuilder<'a>>::OuterType: OuterConstraint<'a, TAncestry = A>, <<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry: Ancestry<TConcept = C>, <<<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry as Ancestry>::TConcept: ToplineConcept<TUniverse = U>, P: TOuterProgram<TAncestry = A>, { pub concepts: RArc<RRwLock<HashMap<(AUuid, AString), C>>>, constraints: LinkedHashMap<(AUuid, AString), RArc<RRwLock<B::OuterType>>>, satisfied_constraints: HashMap<(AUuid, AString), RArc<RRwLock<ConstraintState<'a, B::OuterType, P>>>>, blocks: AVec<PythonBasedConstraintBlock<'a, D::T, B::OuterType, U, P>>, ancestry: A, dag_type: PhantomData<D>, endpoints: <U as AoristUniverse>::TEndpoints, constraint_explanations: HashMap<AString, (AOption<AString>, AOption<AString>)>, ancestors: HashMap<(AUuid, AString), AVec<AncestorRecord>>, topline_constraint_names: LinkedHashSet<AString>, programs: LinkedHashMap<AString, AVec<P>>, preferences: AVec<Dialect>, render_dependencies: bool, } impl<'a, B, D, U, C, A, P> Driver<'a, B, D, U, C, A, P> for PythonBasedDriver<'a, B, D, U, C, A, P> where U: AoristConcept + AoristUniverse, B: TBuilder<'a, TEnum = C, TAncestry = A>, D: FlowBuilderBase<U> + PythonBasedFlowBuilder<U>, <D as FlowBuilderBase<U>>::T: 'a, <D as FlowBuilderBase<U>>::T: ETLFlow<U, ImportType = PythonImport, PreambleType = PythonPreamble> + 'a, A: Ancestry, C: ToplineConcept<TUniverse = U>, <B as TBuilder<'a>>::OuterType: OuterConstraint<'a, TAncestry = A>, <<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry: Ancestry<TConcept = C>, <<<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry as Ancestry>::TConcept: ToplineConcept<TUniverse = U>, P: TOuterProgram<TAncestry = A>, { type CB = PythonBasedConstraintBlock<'a, <D as FlowBuilderBase<U>>::T, B::OuterType, U, P>; fn get_programs_for(&self, constraint_name: &AString) -> AVec<P> { match self.programs.get(constraint_name) { Some(ref programs) => programs.iter().map(|x| (*x).clone()).collect(), None => AVec::new(), } } fn get_preferences(&self) -> AVec<Dialect> { self.preferences.clone() } fn get_constraint_rwlock(&self, uuid: &(AUuid, AString)) -> RArc<RRwLock<B::OuterType>> { self.constraints.get(uuid).unwrap().clone() } fn get_endpoints(&self) -> <U as AoristUniverse>::TEndpoints { self.endpoints.clone() } fn get_ancestry(&self) -> &A { &self.ancestry } fn mark_constraint_state_as_satisfied( &mut self, id: (AUuid, AString), state: RArc<RRwLock<ConstraintState<'a, B::OuterType, P>>>, ) { self.satisfied_constraints.insert(id, state.clone()); } fn init_unsatisfied_constraints(&self) -> Result<ConstraintsBlockMap<'a, B::OuterType, P>> { Self::get_unsatisfied_constraints( &self.constraints, self.concepts.clone(), &self.ancestors, self.topline_constraint_names.clone(), ) } fn add_block( &mut self, constraint_block: PythonBasedConstraintBlock< 'a, <D as FlowBuilderBase<U>>::T, B::OuterType, U, P, >, ) { self.blocks.push(constraint_block); } fn get_constraint_explanation( &self, constraint_name: &AString, ) -> (AOption<AString>, AOption<AString>) { self.constraint_explanations .get(constraint_name) .unwrap() .clone() } fn get_blocks(&self) -> &AVec<Self::CB> { &self.blocks } fn get_dependencies(&self) -> AVec<AString> { self.satisfied_constraints .values() .map(|x| match x.read().get_dialect() { AOption(ROption::RSome(Dialect::Python(x))) => { AOption(ROption::RSome(x.get_pip_requirements())) } _ => AOption(ROption::RNone), }) .filter(|x| x.is_some()) .map(|x| x.unwrap().into_iter()) .flatten() .collect::<BTreeSet<AString>>() .into_iter() .collect() } fn _new( concepts: RArc<RRwLock<HashMap<(AUuid, AString), C>>>, constraints: LinkedHashMap<(AUuid, AString), RArc<RRwLock<B::OuterType>>>, ancestry: A, endpoints: U::TEndpoints, ancestors: HashMap<(AUuid, AString), AVec<AncestorRecord>>, topline_constraint_names: LinkedHashSet<AString>, programs: LinkedHashMap<AString, AVec<P>>, preferences: AVec<Dialect>, render_dependencies: bool, ) -> Self { Self { concepts, constraints, satisfied_constraints: HashMap::new(), blocks: AVec::new(), ancestry, dag_type: PhantomData, endpoints, constraint_explanations: <<B::OuterType as OuterConstraint<'a>>::TEnum as TConstraintEnum< 'a, >>::get_explanations(), ancestors, topline_constraint_names, programs, preferences, render_dependencies } } fn get_render_dependencies(&self) -> bool { self.render_dependencies } }
use abi_stable::std_types::ROption; use aorist_primitives::AOption; use crate::constraint::TConstraintEnum; use crate::constraint::{OuterConstraint, TBuilder}; use crate::constraint_state::ConstraintState; use aorist_primitives::Dialect; use crate::driver::{ConstraintsBlockMap, Driver}; use crate::flow::{ETLFlow, FlowBuilderBase, PythonBasedFlowBuilder}; use crate::program::TOuterProgram; use crate::python::{PythonBasedConstraintBlock, PythonImport, PythonPreamble}; use abi_stable::external_types::parking_lot::rw_lock::RRwLock; use abi_stable::std_types::RArc; use anyhow::Result; use aorist_ast::AncestorRecord; use aorist_primitives::AUuid; use aorist_primitives::{AString, AVec, Ancestry, AoristConcept, AoristUniverse, ToplineConcept}; use linked_hash_map::LinkedHashMap; use linked_hash_set::LinkedHashSet; use std::collections::{BTreeSet, HashMap}; use std::marker::PhantomData; pub struct PythonBasedDriver<'a, B, D, U, C, A, P> where U: AoristConcept + AoristUniverse, B: TBuilder<'a, TEnum = C, TAncestry = A>, D: FlowBuilderBase<U> + PythonBasedFlowBuilder<U>, <D as FlowBuilderBase<U>>::T: 'a, <D as FlowBuilderBase<U>>::T: ETLFlow<U, ImportType = PythonImport, PreambleType = PythonPreamble> + 'a, A: Ancestry, C: ToplineConcept<TUniverse = U>, <B as TBuilder<'a>>::OuterType: OuterConstraint<'a, TAncestry = A>, <<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry: Ancestry<TConcept = C>, <<<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry as Ancestry>::TConcept: ToplineConcept<TUniverse = U>, P: TOuterProgram<TAncestry = A>, { pub concepts: RArc<RRwLock<HashMap<(AUuid, AString), C>>>, constraints: LinkedHashMap<(AUuid, AString), RArc<RRwLock<B::OuterType>>>, satisfied_constraints: HashMap<(AUuid, AString), RArc<RRwLock<ConstraintState<'a, B::OuterType, P>>>>, blocks: AVec<PythonBasedConstraintBlock<'a, D::T, B::OuterType, U, P>>, ancestry: A, dag_type: PhantomData<D>, endpoints: <U as AoristUniverse>::TEndpoints, constraint_explanations: HashMap<AString, (AOption<AString>, AOption<AString>)>, ancestors: HashMap<(AUuid, AString), AVec<AncestorRecord>>, topline_constraint_names: LinkedHashSet<AString>, programs: LinkedHashMap<AString, AVec<P>>, preferences: AVec<Dialect>, render_dependencies: bool, } impl<'a, B, D, U, C, A, P> Driver<'a, B, D, U, C, A, P> for PythonBasedDriver<'a, B, D, U, C, A, P> where U: AoristConcept + AoristUniverse, B: TBuilder<'a, TEnum = C, TAncestry = A>, D: FlowBuilderBase<U> + PythonBasedFlowBuilder<U>, <D as FlowBuilderBase<U>>::T: 'a, <D as FlowBuilderBase<U>>::T: ETLFlow<U, ImportType = PythonImport, PreambleType = PythonPreamble> + 'a, A: Ancestry, C: ToplineConcept<TUniverse = U>, <B as TBuilder<'a>>::OuterType: OuterConstraint<'a, TAncestry = A>, <<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry: Ancestry<TConcept = C>, <<<B as TBuilder<'a>>::OuterType as OuterConstraint<'a>>::TAncestry as Ancestry>::TConcept: ToplineConcept<TUniverse = U>, P: TOuterProgram<TAncestry = A>, { type CB = PythonBasedConstraintBlock<'a, <D as FlowBuilderBase<U>>::T, B::OuterType, U, P>; fn get_programs_for(&self, constraint_name: &AString) -> AVec<P> { match self.programs.get(constraint_name) { Some(ref programs) => programs.iter().map(|x| (*x).clone()).collect(), None => AVec::new(), } } fn get_preferences(&self) -> AVec<Dialect> { self.preferences.clone() } fn get_constraint_rwlock(&self, uuid: &(AUuid, AString)) -> RArc<RRwLock<B::OuterType>> { self.constraints.get(uuid).unwrap().clone() } fn get_endpoints(&self) -> <U as AoristUniverse>::TEndpoints { self.endpoints.clone() } fn get_ancestry(&self) -> &A { &self.ancestry } fn mark_constraint_state_as_satisfied( &mut self, id: (AUuid, AString), state: RArc<RRwLock<ConstraintState<'a, B::OuterType, P>>>, ) { self.satisfied_constraints.insert(id, state.clone()); } fn init_unsatisfied_constraints(&self) -> Result<ConstraintsBlockMap<'a, B::OuterType, P>> { Self::get_unsatisfied_constraints( &self.constraints, self.concepts.clone(), &self.ancestors, self.topline_constraint_names.clone(), ) } fn add_block( &mut self, constraint_block: PythonBasedConstraintBlock< 'a, <D as FlowBuilderBase<U>>::T, B::OuterType, U, P, >, ) { self.blocks.push(constraint_block); } fn get_constraint_explanation( &self, constraint_name: &AString, ) -> (AOption<AString>, AOption<AString>) { self.constraint_explanations .get(constraint_name) .unwrap() .clone() } fn get_blocks(&self) -> &AVec<Self::CB> { &self.blocks } fn get_dependencies(&self) -> AVec<AString> { self.satisfied_constraints .values() .map(|x|
) .filter(|x| x.is_some()) .map(|x| x.unwrap().into_iter()) .flatten() .collect::<BTreeSet<AString>>() .into_iter() .collect() } fn _new( concepts: RArc<RRwLock<HashMap<(AUuid, AString), C>>>, constraints: LinkedHashMap<(AUuid, AString), RArc<RRwLock<B::OuterType>>>, ancestry: A, endpoints: U::TEndpoints, ancestors: HashMap<(AUuid, AString), AVec<AncestorRecord>>, topline_constraint_names: LinkedHashSet<AString>, programs: LinkedHashMap<AString, AVec<P>>, preferences: AVec<Dialect>, render_dependencies: bool, ) -> Self { Self { concepts, constraints, satisfied_constraints: HashMap::new(), blocks: AVec::new(), ancestry, dag_type: PhantomData, endpoints, constraint_explanations: <<B::OuterType as OuterConstraint<'a>>::TEnum as TConstraintEnum< 'a, >>::get_explanations(), ancestors, topline_constraint_names, programs, preferences, render_dependencies } } fn get_render_dependencies(&self) -> bool { self.render_dependencies } }
match x.read().get_dialect() { AOption(ROption::RSome(Dialect::Python(x))) => { AOption(ROption::RSome(x.get_pip_requirements())) } _ => AOption(ROption::RNone), }
if_condition
[ { "content": "pub trait Driver<'a, B, D, U, C, A, P>\n\nwhere\n\n U: AoristConcept + AoristUniverse,\n\n B: TBuilder<'a, TEnum = C, TAncestry = A>,\n\n D: FlowBuilderBase<U>,\n\n D: FlowBuilderMaterialize<\n\n U,\n\n BuilderInputType = <Self::CB as ConstraintBlock<\n\n 'a,\n...
Rust
examples/modbus-rtu.rs
slowtec/truebner-smt100
d74864043564c907ba581f8e8d1bc6878f955203
#[cfg(feature = "modbus-rtu")] pub fn main() { use chrono::{DateTime, Utc}; use env_logger::Builder as LoggerBuilder; use futures::{future::Either, Future, Stream}; use std::{cell::RefCell, env, io::Error, rc::Rc, time::Duration}; use stream_cancel::{StreamExt, Tripwire}; use tokio::timer::Interval; use tokio_core::reactor::{Core, Handle}; use tokio_modbus::prelude::{*, client::util::*}; use truebner_smt100::{modbus, *}; let mut logger_builder = LoggerBuilder::new(); logger_builder.filter_level(log::LevelFilter::Info); if env::var("RUST_LOG").is_ok() { let rust_log_var = &env::var("RUST_LOG").unwrap(); println!("Parsing RUST_LOG={}", rust_log_var); logger_builder.parse_filters(rust_log_var); } logger_builder.init(); let mut core = Core::new().unwrap(); #[derive(Debug, Clone)] struct ContextConfig { handle: Handle, tty_path: String, }; impl NewContext for ContextConfig { fn new_context(&self) -> Box<dyn Future<Item = client::Context, Error = Error>> { Box::new(modbus::rtu::connect_path(&self.handle, &self.tty_path)) } } #[derive(Debug, Clone)] struct SlaveConfig { slave: Slave, cycle_time: Duration, timeout: Duration, }; let context_config = ContextConfig { handle: core.handle(), tty_path: "/dev/ttyUSB0".to_owned(), }; let slave_config = SlaveConfig { slave: Slave::min_device(), cycle_time: Duration::from_millis(1000), timeout: Duration::from_millis(500), }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Measurement<T> { ts: DateTime<Utc>, val: T, } impl<T> Measurement<T> { pub fn new(val: T) -> Self { Self { ts: Utc::now(), val, } } } #[derive(Debug, Default, Clone, Copy, PartialEq)] struct Measurements { temperature: Option<Measurement<Temperature>>, water_content: Option<Measurement<VolumetricWaterContent>>, permittivity: Option<Measurement<RelativePermittivity>>, } struct ControlLoop { _shared_context: Rc<RefCell<SharedContext>>, config: SlaveConfig, proxy: modbus::SlaveProxy, measurements: Measurements, }; impl ControlLoop { pub fn new(config: SlaveConfig, new_context: Box<dyn NewContext>) -> Self { let shared_context = Rc::new(RefCell::new(SharedContext::new(None, new_context))); let proxy = modbus::SlaveProxy::new(config.slave, Rc::clone(&shared_context)); Self { _shared_context: shared_context, config, proxy, measurements: Default::default(), } } fn reconnect(&self) -> impl Future<Item = (), Error = Error> { self.proxy.reconnect() } pub fn measure_temperature(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_temperature(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.temperature = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) } pub fn measure_water_content(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_water_content(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.water_content = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) } pub fn measure_permittivity(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_permittivity(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.permittivity = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) } pub fn recover_after_error(&self, err: &Error) -> impl Future<Item = (), Error = ()> { log::warn!( "Reconnecting after error: {}", err ); self.reconnect().or_else(|err| { log::error!( "Failed to reconnect: {}", err ); Ok(()) }) } pub fn broadcast_slave(&self) -> impl Future<Item = (), Error = Error> { self.proxy.broadcast_slave() } } log::info!("Connecting: {:?}", context_config); let ctrl_loop = ControlLoop::new(slave_config, Box::new(context_config)); core.run(ctrl_loop.reconnect()).unwrap(); let broadcast_slave = false; if broadcast_slave { log::info!( "Resetting Modbus slave address to {:?}", ctrl_loop.proxy.slave() ); core.run(ctrl_loop.broadcast_slave()).unwrap(); } let (_trigger, tripwire) = Tripwire::new(); let cycle_interval = Interval::new_interval(ctrl_loop.config.cycle_time); let ctrl_loop_task = cycle_interval .map_err(|err| { log::error!("Aborting control loop after timer error: {:?}", err); }) .take_until(tripwire) .fold(ctrl_loop, |ctrl_loop, _event| { futures::future::ok(ctrl_loop) .and_then(ControlLoop::measure_temperature) .and_then(ControlLoop::measure_water_content) .and_then(ControlLoop::measure_permittivity) .then(|res| match res { Ok(ctrl_loop) => { log::info!("{:?}", ctrl_loop.measurements); Either::A(futures::future::ok(ctrl_loop)) } Err((err, ctrl_loop)) => { log::info!("{:?}", ctrl_loop.measurements); Either::B(ctrl_loop.recover_after_error(&err).map(|()| ctrl_loop)) } }) }); core.run(ctrl_loop_task).unwrap(); } #[cfg(not(feature = "modbus-rtu"))] pub fn main() { println!("feature `modbus-rtu` is required to run this example"); std::process::exit(1); }
#[cfg(feature = "modbus-rtu")] pub fn main() { use chrono::{DateTime, Utc}; use env_logger::Builder as LoggerBuilder; use futures::{future::Either, Future, Stream}; use std::{cell::RefCell, env, io::Error, rc::Rc, time::Duration}; use stream_cancel::{StreamExt, Tripwire}; use tokio::timer::Interval; use tokio_core::reactor::{Core, Handle}; use tokio_modbus::prelude::{*, client::util::*}; use truebner_smt100::{modbus, *}; let mut logger_builder = LoggerBuilder::new(); logger_builder.filter_level(log::LevelFilter::Info); if env::var("RUST_LOG").is_ok() { let rust_log_var = &env::var("RUST_LOG").unwrap(); println!("Parsing RUST_LOG={}", rust_log_var); logger_builder.parse_filters(rust_log_var); } logger_builder.init(); let mut core = Core::new().unwrap(); #[derive(Debug, Clone)] struct ContextConfig { handle: Handle, tty_path: String, }; impl NewContext for ContextConfig { fn new_context(&self) -> Box<dyn Future<Item = client::Context, Error = Error>> { Box::new(modbus::rtu::connect_path(&self.handle, &self.tty_path)) } } #[derive(Debug, Clone)] struct SlaveConfig { slave: Slave, cycle_time: Duration, timeout: Duration, }; let context_config = ContextConfig { handle: core.handle(), tty_path: "/dev/ttyUSB0".to_owned(), }; let slave_config = SlaveConfig { slave: Slave::min_device(), cycle_time: Duration::from_millis(1000), timeout: Duration::from_millis(500), }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] struct Measurement<T> { ts: DateTime<Utc>, val: T, } impl<T> Measurement<T> { pub fn new(val: T) -> Self { Self { ts: Utc::now(), val, } } } #[derive(Debug, Default, Clone, Copy, PartialEq)] struct Measurements { temperature: Option<Measurement<Temperature>>, water_content: Option<Measurement<VolumetricWaterContent>>, permittivity: Option<Measurement<RelativePermittivity>>, } struct ControlLoop { _shared_context: Rc<RefCell<SharedContext>>, config: SlaveConfig, proxy: modbus::SlaveProxy, measurements: Measurements, }; impl ControlLoop { pub fn new(config: SlaveConfig, new_context: Box<dyn NewContext>) -> Self { let shared_context = Rc::new(RefCell::new(SharedContext::new(None, new_context))); let proxy = modbus::SlaveProxy::new(config.slave, Rc::clone(&shared_context)); Self { _shared_context: shared_context, config, proxy, measurements: Default::default(), } } fn reconnect(&self) -> impl Future<Item = (), Error = Error> { self.proxy.reconnect() } pub fn measure_temperature(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_temperature(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.temperature = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) } pub fn measure_water_content(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_water_content(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.water_content = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) } pub fn measure_permittivity(mut self) -> impl Future<Item = Self, Error = (Error, Self)> { self .proxy .read_permittivity(self.config.timeout) .then(move |res| match res { Ok(val) => { self.measurements.permittivity = Some(Measurement::new(val)); Ok(self) } Err(err) => Err((err, self)), }) }
pub fn broadcast_slave(&self) -> impl Future<Item = (), Error = Error> { self.proxy.broadcast_slave() } } log::info!("Connecting: {:?}", context_config); let ctrl_loop = ControlLoop::new(slave_config, Box::new(context_config)); core.run(ctrl_loop.reconnect()).unwrap(); let broadcast_slave = false; if broadcast_slave { log::info!( "Resetting Modbus slave address to {:?}", ctrl_loop.proxy.slave() ); core.run(ctrl_loop.broadcast_slave()).unwrap(); } let (_trigger, tripwire) = Tripwire::new(); let cycle_interval = Interval::new_interval(ctrl_loop.config.cycle_time); let ctrl_loop_task = cycle_interval .map_err(|err| { log::error!("Aborting control loop after timer error: {:?}", err); }) .take_until(tripwire) .fold(ctrl_loop, |ctrl_loop, _event| { futures::future::ok(ctrl_loop) .and_then(ControlLoop::measure_temperature) .and_then(ControlLoop::measure_water_content) .and_then(ControlLoop::measure_permittivity) .then(|res| match res { Ok(ctrl_loop) => { log::info!("{:?}", ctrl_loop.measurements); Either::A(futures::future::ok(ctrl_loop)) } Err((err, ctrl_loop)) => { log::info!("{:?}", ctrl_loop.measurements); Either::B(ctrl_loop.recover_after_error(&err).map(|()| ctrl_loop)) } }) }); core.run(ctrl_loop_task).unwrap(); } #[cfg(not(feature = "modbus-rtu"))] pub fn main() { println!("feature `modbus-rtu` is required to run this example"); std::process::exit(1); }
pub fn recover_after_error(&self, err: &Error) -> impl Future<Item = (), Error = ()> { log::warn!( "Reconnecting after error: {}", err ); self.reconnect().or_else(|err| { log::error!( "Failed to reconnect: {}", err ); Ok(()) }) }
function_block-function_prefix_line
[ { "content": "pub fn read_permittivity_with_timeout(\n\n context: &mut client::Context,\n\n timeout: Duration,\n\n) -> impl Future<Item = RelativePermittivity, Error = Error> {\n\n read_permittivity(context)\n\n .timeout(timeout)\n\n .map_err(move |err| {\n\n err.into_inner().u...
Rust
src/mutable_linked_list.rs
marcianx/data-structures-rs
767cdc5827bbb91b6e225e292d8ac17dbc9c1f56
use std::iter::IntoIterator; pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { self.head = Some(Box::new(Node { elem: elem, next: self.head.take() })); } pub fn pop(&mut self) -> Option<T> { self.head.take().map(|node| { let node = *node; self.head = node.next; node.elem }) } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| { &node.elem }) } pub fn peek_mut(&mut self) -> Option<&mut T> { self.head.as_mut().map(|node| { &mut node.elem }) } pub fn iter(&self) -> Iter<T> { Iter { link: &self.head } } pub fn iter_mut(&mut self) -> IterMut<T> { IterMut { next: Some(&mut self.head) } } } pub struct Iter<'a, T: 'a> { link: &'a Link<T>, } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.link.as_ref().map(|node| { self.link = &node.next; &node.elem }) } } pub struct IterMut<'a, T: 'a> { next: Option<&'a mut Link<T>>, } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.next.take().and_then(|link| { link.as_mut().map(|node| { let node = &mut **node; self.next = Some(&mut node.next); &mut node.elem }) }) } } pub struct ListIntoIterator<T> { list: List<T>, } impl<T> Iterator for ListIntoIterator<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.list.pop() } } impl<T> IntoIterator for List<T> { type Item = T; type IntoIter = ListIntoIterator<T>; fn into_iter(self) -> ListIntoIterator<T> { ListIntoIterator { list: self } } } impl<'a, T> IntoIterator for &'a List<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl<'a, T> IntoIterator for &'a mut List<T> { type Item = &'a mut T; type IntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { self.iter_mut() } } #[cfg(test)] mod test { use super::List; #[test] fn test_push_pop() { let mut list = List::new(); list.push(1); assert_eq!(Some(&1), list.peek()); list.push(2); assert_eq!(Some(&2), list.peek()); list.push(3); assert_eq!(Some(&3), list.peek()); assert_eq!(Some(3), list.pop()); assert_eq!(Some(2), list.pop()); assert_eq!(Some(1), list.pop()); assert_eq!(None, list.pop()); } #[test] fn test_into_iter() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut i = 3; for val in list { assert_eq!(i, val); i -= 1; } } #[test] fn test_iter() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut iter = list.iter(); assert_eq!(Some(&3), iter.next()); assert_eq!(Some(&2), iter.next()); assert_eq!(Some(&1), iter.next()); assert_eq!(None, iter.next()); let mut i = 3; for val in &list { assert_eq!(i, *val); i -= 1; } } #[test] fn test_iter_mut() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut i = 3; for val in list.iter_mut() { assert_eq!(i, *val); *val = 3 - i; i -= 1; } let mut i = 0; for val in &mut list { assert_eq!(i, *val); *val = 3 - i; i += 1; } let mut i = 3; for val in &list { assert_eq!(i, *val); i -= 1; } } }
use std::iter::IntoIterator; pub struct List<T> { head: Link<T>, } type Link<T> = Option<Box<Node<T>>>; struct Node<T> { elem: T, next: Link<T>, } impl<T> List<T> { pub fn new() -> Self { List { head: None } } pub fn push(&mut self, elem: T) { self.head = Some(Box::new(Node { elem: elem, next: self.head.take() })); } pub fn pop(&mut self) -> Option<T> { self.head.take().map(|node| { let node = *node; self.head = node.next; node.elem }) } pub fn peek(&self) -> Option<&T> { self.head.as_ref().map(|node| { &node.elem }) } pub fn peek_mut(&mut self) -> Option<&mut T> { self.head.as_mut().map(|node| { &mut node.elem }) } pub fn iter(&self) -> Iter<T> { Iter { link: &self.head } } pub fn iter_mut(&mut self) -> IterMut<T> { IterMut { next: Some(&mut self.head) } } } pub struct Iter<'a, T: 'a> { link: &'a Link<T>, } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.link.as_ref().map(|node| { self.link = &node.next; &node.elem }) } } pub struct IterMut<'a, T: 'a> { next: Option<&'a mut Link<T>>, } impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.next.take().and_then(|link| { link.as_mut().map(|node| { let node = &mut **node; self.next = Some(&mut node.next); &mut node.elem }) }) } } pub struct ListIntoIterator<T> { list: List<T>, } impl<T> Iterator for ListIntoIterator<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { self.list.pop() } } impl<T> IntoIterator for List<T> { type Item = T; type IntoIter = ListIntoIterator<T>; fn into_iter(self) -> ListIntoIterator<T
ntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { self.iter_mut() } } #[cfg(test)] mod test { use super::List; #[test] fn test_push_pop() { let mut list = List::new(); list.push(1); assert_eq!(Some(&1), list.peek()); list.push(2); assert_eq!(Some(&2), list.peek()); list.push(3); assert_eq!(Some(&3), list.peek()); assert_eq!(Some(3), list.pop()); assert_eq!(Some(2), list.pop()); assert_eq!(Some(1), list.pop()); assert_eq!(None, list.pop()); } #[test] fn test_into_iter() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut i = 3; for val in list { assert_eq!(i, val); i -= 1; } } #[test] fn test_iter() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut iter = list.iter(); assert_eq!(Some(&3), iter.next()); assert_eq!(Some(&2), iter.next()); assert_eq!(Some(&1), iter.next()); assert_eq!(None, iter.next()); let mut i = 3; for val in &list { assert_eq!(i, *val); i -= 1; } } #[test] fn test_iter_mut() { let mut list = List::new(); list.push(1); list.push(2); list.push(3); let mut i = 3; for val in list.iter_mut() { assert_eq!(i, *val); *val = 3 - i; i -= 1; } let mut i = 0; for val in &mut list { assert_eq!(i, *val); *val = 3 - i; i += 1; } let mut i = 3; for val in &list { assert_eq!(i, *val); i -= 1; } } }
> { ListIntoIterator { list: self } } } impl<'a, T> IntoIterator for &'a List<T> { type Item = &'a T; type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl<'a, T> IntoIterator for &'a mut List<T> { type Item = &'a mut T; type I
random
[ { "content": "struct Node<T> {\n\n elem: T,\n\n next: Link<T>,\n\n}\n\n\n\nimpl<T> List<T> {\n\n pub fn new() -> Self {\n\n List { head: None }\n\n }\n\n\n\n pub fn prepend(&self, elem: T) -> List<T> {\n\n List { head: Some(Rc::new(Node { elem: elem, next: self.head.clone() })) }\n\...
Rust
crates/core_text/src/rasterizer.rs
ericrobolson/realtime-cpu-raytracer
3d759f2b8a00bf876ab24d2375716c63f5ed0134
use core_img::Rgba8Image; use core_fs::load; use rusttype::{point, Font, Scale, VMetrics}; use std::{borrow::Borrow, collections::HashMap}; pub struct TextRasterizer<'a> { fonts: HashMap<(&'static str, u32), FontRecord<'a>>, debug_save_rasters: bool, } struct FontRecord<'a> { font: Font<'a>, font_size: u32, scale: Scale, metrics: VMetrics, glyph_height: u32, } #[derive(Copy, Clone, PartialEq)] pub struct CharacterRecord { pub c: char, pub width: u32, pub height: u32, } impl<'a> TextRasterizer<'a> { pub fn new(debug_save_rasters: bool) -> Self { Self { debug_save_rasters, fonts: HashMap::new(), } } pub fn load_font(&mut self, font_size: u32, font: &'static str) { let data = core_fs::load(font); let font_data = Font::try_from_vec(data).unwrap_or_else(|| { panic!(format!("error constructing a Font from data at {:?}", font)); }); let scale = Scale::uniform(font_size as f32); let metrics = font_data.v_metrics(scale); let glyph_height = (metrics.ascent - metrics.descent).ceil() as u32; self.fonts.insert( (font, font_size), FontRecord { font: font_data, font_size, scale, metrics, glyph_height, }, ); } pub fn raster_character( &mut self, c: char, font: &'static str, font_size: u32, ) -> (CharacterRecord, Rgba8Image) { let font_record = match self.fonts.get(&(font, font_size)) { Some(f) => f, None => { self.load_font(font_size, font); self.fonts.get(&(font, font_size)).unwrap() } }; let glyph = font_record .font .glyph(c) .scaled(font_record.scale) .positioned(point(0.0, 0.0 + font_record.metrics.ascent)); let height = font_record.glyph_height; let mut min_x = u32::MAX; let mut max_x = 0; let mut min_y = u32::MAX; let mut max_y = 0; let (img_width, img_height) = (font_size, height); let is_whitespace = c.is_whitespace() || match glyph.pixel_bounding_box() { Some(bb) => false, None => true, }; if is_whitespace { let character_record = CharacterRecord { c, width: img_width, height: img_height, }; return (character_record, Rgba8Image::new(img_width, img_height)); } let mut img = { let mut img = Rgba8Image::new(img_width, img_height); let color = (255, 255, 255); if let Some(bounding_box) = glyph.pixel_bounding_box() { glyph.draw(|x, y, v| { let px = x + glyph.position().x as u32; let py = y + { let y = bounding_box.min.y; if y < 0 { 0 } else { bounding_box.min.y as u32 } }; if v > 0. { if px < min_x { min_x = px; } if px > max_x { max_x = px; } if py < min_y { min_y = py; } if py > max_y { max_y = py; } } img.put_pixel(px, py, color.0, color.1, color.2, output_alpha(v)); }); } img }; let img_width = max_x - min_x + 1; let img_height = img_height; img.crop(min_x, 0, img_width, img_height); if !c.is_whitespace() && self.debug_save_rasters { println!("{:?}", c); img.save(format!("_test/_test_img{}.png", c as u32)) .unwrap(); } let character_record = CharacterRecord { c, width: img_width, height: img_height, }; (character_record, img) } } fn output_alpha(v: f32) -> u8 { let a = v * 255.0; return a as u8; }
use core_img::Rgba8Image; use core_fs::load; use rusttype::{point, Font, Scale, VMetrics}; use std::{borrow::Borrow, collections::HashMap}; pub struct TextRasterizer<'a> { fonts: HashMap<(&'static str, u32), FontRecord<'a>>, debug_save_rasters: bool, } struct FontRecord<'a> { font: Font<'a>, font_size: u32, scale: Scale, metrics: VMetrics, glyph_height: u32, } #[derive(Copy, Clone,
.ascent)); let height = font_record.glyph_height; let mut min_x = u32::MAX; let mut max_x = 0; let mut min_y = u32::MAX; let mut max_y = 0; let (img_width, img_height) = (font_size, height); let is_whitespace = c.is_whitespace() || match glyph.pixel_bounding_box() { Some(bb) => false, None => true, }; if is_whitespace { let character_record = CharacterRecord { c, width: img_width, height: img_height, }; return (character_record, Rgba8Image::new(img_width, img_height)); } let mut img = { let mut img = Rgba8Image::new(img_width, img_height); let color = (255, 255, 255); if let Some(bounding_box) = glyph.pixel_bounding_box() { glyph.draw(|x, y, v| { let px = x + glyph.position().x as u32; let py = y + { let y = bounding_box.min.y; if y < 0 { 0 } else { bounding_box.min.y as u32 } }; if v > 0. { if px < min_x { min_x = px; } if px > max_x { max_x = px; } if py < min_y { min_y = py; } if py > max_y { max_y = py; } } img.put_pixel(px, py, color.0, color.1, color.2, output_alpha(v)); }); } img }; let img_width = max_x - min_x + 1; let img_height = img_height; img.crop(min_x, 0, img_width, img_height); if !c.is_whitespace() && self.debug_save_rasters { println!("{:?}", c); img.save(format!("_test/_test_img{}.png", c as u32)) .unwrap(); } let character_record = CharacterRecord { c, width: img_width, height: img_height, }; (character_record, img) } } fn output_alpha(v: f32) -> u8 { let a = v * 255.0; return a as u8; }
PartialEq)] pub struct CharacterRecord { pub c: char, pub width: u32, pub height: u32, } impl<'a> TextRasterizer<'a> { pub fn new(debug_save_rasters: bool) -> Self { Self { debug_save_rasters, fonts: HashMap::new(), } } pub fn load_font(&mut self, font_size: u32, font: &'static str) { let data = core_fs::load(font); let font_data = Font::try_from_vec(data).unwrap_or_else(|| { panic!(format!("error constructing a Font from data at {:?}", font)); }); let scale = Scale::uniform(font_size as f32); let metrics = font_data.v_metrics(scale); let glyph_height = (metrics.ascent - metrics.descent).ceil() as u32; self.fonts.insert( (font, font_size), FontRecord { font: font_data, font_size, scale, metrics, glyph_height, }, ); } pub fn raster_character( &mut self, c: char, font: &'static str, font_size: u32, ) -> (CharacterRecord, Rgba8Image) { let font_record = match self.fonts.get(&(font, font_size)) { Some(f) => f, None => { self.load_font(font_size, font); self.fonts.get(&(font, font_size)).unwrap() } }; let glyph = font_record .font .glyph(c) .scaled(font_record.scale) .positioned(point(0.0, 0.0 + font_record.metrics
random
[ { "content": "pub fn build<Sim, Cfg, Msg>(title: &'static str, w: u32, h: u32) -> impl WinGfx<Sim, Cfg, Msg>\n\nwhere\n\n Sim: Simulation<Cfg, Msg> + 'static,\n\n Cfg: 'static,\n\n Msg: 'static,\n\n{\n\n OpenGlWindow::new(title, w, h)\n\n}\n", "file_path": "crates/core_wingfx/src/wingfx.rs", ...
Rust
src/spriteanimationloader.rs
neosam/sprite-game
5d261eb538824ebb133833a4f4fe4f162aa3445c
use amethyst::{ assets::{AssetStorage, Loader}, config::Config, prelude::*, renderer::{ImageFormat, Sprite, SpriteSheet, /*SpriteSheetHandle,*/ Texture, /*TextureMetadata*/ sprite::SpriteSheetHandle, SpriteRender, }, }; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Debug, Serialize, Deserialize)] pub struct SpriteDefinition { pub name: String, pub x: u32, pub y: u32, pub width: u32, pub height: u32, pub offset: Option<(f32, f32)>, } #[derive(Debug, Serialize, Deserialize)] pub struct AnimationData { pub texture_path: String, pub texture_width: u32, pub texture_height: u32, pub sprites: Vec<SpriteDefinition>, pub animations: BTreeMap<String, Vec<usize>>, pub images: BTreeMap<String, usize>, } impl Default for AnimationData { fn default() -> Self { AnimationData { texture_path: String::new(), texture_width: 0, texture_height: 0, sprites: Vec::new(), animations: BTreeMap::new(), images: BTreeMap::new(), } } } pub struct SpriteAnimationStore { pub sprite_sheet_handle: SpriteSheetHandle, pub animations: BTreeMap<String, Vec<usize>>, pub images: BTreeMap<String, usize>, } impl SpriteAnimationStore { pub fn get_sprite_render(&self, name: &str) -> Option<SpriteRender> { self.images.get(name) .map(|index| SpriteRender { sprite_sheet: self.sprite_sheet_handle.clone(), sprite_number: *index }) } } pub fn manually_assign_animations(animation_data: &mut AnimationData) { let mut animations: BTreeMap<String, Vec<usize>> = BTreeMap::new(); let mut images: BTreeMap<String, usize> = BTreeMap::new(); let ends_with_number_pattern = Regex::new(r"_\d+$").unwrap(); for (i, sprite) in (0..).zip(&animation_data.sprites) { if let Some(_) = ends_with_number_pattern.find(&sprite.name) { let animation_name = ends_with_number_pattern.replace_all(&sprite.name, ""); println!("Animation name: {}", animation_name); let entry = animations .entry(animation_name.to_string()) .or_insert_with(|| Vec::new()); entry.push(i); } else { images.insert(sprite.name.to_string(), i); } } animation_data.animations = animations; animation_data.images = images; } pub fn load_sprites( world: &mut World, directory: impl ToString, filename: impl ToString, ) -> SpriteAnimationStore { info!("Loading animations"); let directory = directory.to_string(); let filename = filename.to_string(); let ron_path = format!("{}/{}", directory, filename); let mut animations = AnimationData::load(ron_path).expect("Animation data should load"); manually_assign_animations(&mut animations); let texture_path = format!("{}/{}", directory, animations.texture_path); let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( texture_path, ImageFormat::default(), (), &texture_storage, ) }; let mut sprites = Vec::with_capacity(animations.sprites.len()); for sprite in animations.sprites { let offset = if let Some((offset_x, offset_y)) = sprite.offset { [offset_x, offset_y] } else { [0.5; 2] }; sprites.push(Sprite::from_pixel_values( animations.texture_width, animations.texture_height, sprite.width, sprite.height, sprite.x, sprite.y, offset, false, false )); } let sprite_sheet = SpriteSheet { texture: texture_handle, sprites, }; let sprite_sheet_handle = { let loader = world.read_resource::<Loader>(); loader.load_from_data( sprite_sheet, (), &world.read_resource::<AssetStorage<SpriteSheet>>(), ) }; SpriteAnimationStore { sprite_sheet_handle, animations: animations.animations.clone(), images: animations.images.clone(), } }
use amethyst::{ assets::{AssetStorage, Loader}, config::Config, prelude::*, renderer::{ImageFormat, Sprite, SpriteSheet, /*SpriteSheetHandle,*/ Texture, /*TextureMetadata*/ sprite::SpriteSheetHandle, SpriteRender, }, }; use regex::Regex; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; #[derive(Debug, Serialize, Deserialize)] pub struct SpriteDefinition { pub name: String, pub x: u32, pub y: u32, pub width: u32, pub height: u32, pub offset: Option<(f32, f32)>, } #[derive(Debug, Serialize, Deserialize)] pub struct AnimationData { pub texture_path: String, pub texture_width: u32, pub texture_height: u32, pub sprites: Vec<SpriteDefinition>, pub animations: BTreeMap<String, Vec<usize>>, pub images: BTreeMap<String, usize>, } impl Default for AnimationData { fn default() -> Self { AnimationData { text
} pub struct SpriteAnimationStore { pub sprite_sheet_handle: SpriteSheetHandle, pub animations: BTreeMap<String, Vec<usize>>, pub images: BTreeMap<String, usize>, } impl SpriteAnimationStore { pub fn get_sprite_render(&self, name: &str) -> Option<SpriteRender> { self.images.get(name) .map(|index| SpriteRender { sprite_sheet: self.sprite_sheet_handle.clone(), sprite_number: *index }) } } pub fn manually_assign_animations(animation_data: &mut AnimationData) { let mut animations: BTreeMap<String, Vec<usize>> = BTreeMap::new(); let mut images: BTreeMap<String, usize> = BTreeMap::new(); let ends_with_number_pattern = Regex::new(r"_\d+$").unwrap(); for (i, sprite) in (0..).zip(&animation_data.sprites) { if let Some(_) = ends_with_number_pattern.find(&sprite.name) { let animation_name = ends_with_number_pattern.replace_all(&sprite.name, ""); println!("Animation name: {}", animation_name); let entry = animations .entry(animation_name.to_string()) .or_insert_with(|| Vec::new()); entry.push(i); } else { images.insert(sprite.name.to_string(), i); } } animation_data.animations = animations; animation_data.images = images; } pub fn load_sprites( world: &mut World, directory: impl ToString, filename: impl ToString, ) -> SpriteAnimationStore { info!("Loading animations"); let directory = directory.to_string(); let filename = filename.to_string(); let ron_path = format!("{}/{}", directory, filename); let mut animations = AnimationData::load(ron_path).expect("Animation data should load"); manually_assign_animations(&mut animations); let texture_path = format!("{}/{}", directory, animations.texture_path); let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( texture_path, ImageFormat::default(), (), &texture_storage, ) }; let mut sprites = Vec::with_capacity(animations.sprites.len()); for sprite in animations.sprites { let offset = if let Some((offset_x, offset_y)) = sprite.offset { [offset_x, offset_y] } else { [0.5; 2] }; sprites.push(Sprite::from_pixel_values( animations.texture_width, animations.texture_height, sprite.width, sprite.height, sprite.x, sprite.y, offset, false, false )); } let sprite_sheet = SpriteSheet { texture: texture_handle, sprites, }; let sprite_sheet_handle = { let loader = world.read_resource::<Loader>(); loader.load_from_data( sprite_sheet, (), &world.read_resource::<AssetStorage<SpriteSheet>>(), ) }; SpriteAnimationStore { sprite_sheet_handle, animations: animations.animations.clone(), images: animations.images.clone(), } }
ure_path: String::new(), texture_width: 0, texture_height: 0, sprites: Vec::new(), animations: BTreeMap::new(), images: BTreeMap::new(), } }
function_block-function_prefixed
[ { "content": "fn build_map(width: usize, height: usize) -> map::Map<room::Room> {\n\n /*let mut map = map::Map::new();\n\n\n\n let mut room_generation1 = room::RoomGeneration::default();\n\n room_generation1.width = width;\n\n room_generation1.height = height;\n\n room_generation1.exit_east = tru...
Rust
memeroute-gui/src/pcb/pcb_view.rs
Edgeworth/memeroute
97e3443ab8e450150bcd84d6af96d70d224ba12c
use std::lazy::SyncLazy; use eframe::egui::epaint::{Mesh, TessellationOptions, Tessellator}; use eframe::egui::{epaint, Color32, Context, PointerButton, Response, Sense, Ui, Widget}; use memegeom::primitive::point::Pt; use memegeom::primitive::rect::Rt; use memegeom::primitive::shape::Shape; use memegeom::primitive::{path, pt, ShapeOps}; use memegeom::tf::Tf; use memeroute::model::pcb::{ Component, Keepout, LayerId, LayerSet, LayerShape, Padstack, Pcb, Pin, }; use crate::pcb::primitives::{fill_circle, fill_polygon, fill_rt, stroke_path}; use crate::pcb::{to_pos2, to_pt, to_rt}; static KEEPOUT: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(155, 27, 0, 180)); static OUTLINE: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(89, 113, 193, 180), Color32::from_rgba_unmultiplied(168, 0, 186, 180), ] }); static BOUNDARY: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(255, 199, 46, 180)); static PIN: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(0, 27, 161, 180), Color32::from_rgba_unmultiplied(0, 27, 161, 180), ] }); static WIRE: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(252, 3, 182, 180), Color32::from_rgba_unmultiplied(0, 166, 52, 180), ] }); static VIA: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(100, 100, 100, 180)); static DEBUG: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(123, 0, 255, 180)); #[derive(Debug, Clone)] pub struct PcbView { pcb: Pcb, screen_area: Rt, local_area: Rt, offset: Pt, zoom: f64, dirty: bool, mesh: Mesh, } impl Widget for &mut PcbView { fn ui(self, ui: &mut Ui) -> Response { let (response, painter) = ui.allocate_painter(ui.available_size_before_wrap(), Sense::click_and_drag()); if response.dragged_by(PointerButton::Middle) { let p = response.drag_delta(); self.offset += pt(p.x as f64, p.y as f64); } if ui.rect_contains_pointer(response.rect) { let pos = to_pt(ui.ctx().input().pointer.interact_pos().unwrap()); let delta = ui.ctx().input().scroll_delta.y as f64; let fac = 10.0 * delta / response.rect.height() as f64; self.offset = self.offset + (self.offset - pos) * fac; self.zoom *= 1.0 + fac; } self.set_screen_area(to_rt(response.rect)); let mesh = self.render(ui.ctx()); painter.rect_filled(response.rect, 0.0, Color32::WHITE); painter.add(epaint::Shape::Mesh(mesh)); response } } impl PcbView { pub fn new(pcb: Pcb, local_area: Rt) -> Self { Self { pcb, local_area, dirty: true, offset: Pt::zero(), zoom: 1.0, screen_area: Rt::default(), mesh: Mesh::default(), } } pub fn set_pcb(&mut self, pcb: Pcb) { self.pcb = pcb; self.dirty = true; self.mesh.clear(); } fn set_screen_area(&mut self, screen_area: Rt) { self.screen_area = screen_area; self.local_area = self.local_area.match_aspect(&self.screen_area); self.dirty = true; } fn layer_id_to_color_idx(id: LayerId) -> usize { id as usize } fn draw_shape(tf: &Tf, v: &LayerShape, col: Color32) -> Vec<epaint::Shape> { let mut shapes = Vec::new(); match &v.shape { Shape::Rect(s) => shapes.push(fill_rt(tf, s, col)), Shape::Circle(s) => shapes.push(fill_circle(tf, s.p(), s.r(), col)), Shape::Polygon(s) => shapes.push(fill_polygon(tf, s.pts(), s.tri_idx(), col)), Shape::Path(s) => { let r = if s.r() == 0.0 { 0.1 } else { s.r() }; shapes.extend(stroke_path(tf, s.pts(), r, col)); } _ => todo!(), } shapes } fn draw_keepout(tf: &Tf, v: &Keepout, col: Color32) -> Vec<epaint::Shape> { Self::draw_shape(tf, &v.shape, col) } fn draw_padstack(tf: &Tf, v: &Padstack, col: Color32) -> Vec<epaint::Shape> { let mut shapes = Vec::new(); for shape in &v.shapes { shapes.extend(Self::draw_shape(tf, shape, col)); } shapes } fn draw_pin(tf: &Tf, v: &Pin, col: Color32) -> Vec<epaint::Shape> { Self::draw_padstack(&(tf * v.tf()), &v.padstack, col) } fn draw_component(tf: &Tf, v: &Component) -> Vec<epaint::Shape> { let mut shapes = Vec::new(); let tf = tf * v.tf(); for outline in &v.outlines { let idx = outline.layers.first().unwrap(); shapes.extend(Self::draw_shape(&tf, outline, OUTLINE[idx])); } for keepout in &v.keepouts { shapes.extend(Self::draw_keepout(&tf, keepout, *KEEPOUT)); } for pin in v.pins() { let idx = pin.padstack.layers().first().unwrap(); shapes.extend(Self::draw_pin(&tf, pin, PIN[idx])); } shapes } fn tessellate(tess: &mut Tessellator, mesh: &mut Mesh, shapes: Vec<epaint::Shape>) { for s in shapes { tess.tessellate_shape(s, mesh); } } fn render(&mut self, ctx: &Context) -> Mesh { if self.mesh.is_empty() { let mut mesh = Mesh::default(); let tf = Tf::new(); let mut tess = Tessellator::new( ctx.pixels_per_point(), TessellationOptions { feathering: false, ..Default::default() }, ctx.fonts().font_image_size(), ); for boundary in self.pcb.boundaries() { let shapes = Self::draw_shape(&tf, boundary, *BOUNDARY); Self::tessellate(&mut tess, &mut mesh, shapes); } for keepout in self.pcb.keepouts() { let shapes = Self::draw_keepout(&tf, keepout, *KEEPOUT); Self::tessellate(&mut tess, &mut mesh, shapes); } for component in self.pcb.components() { let shapes = Self::draw_component(&tf, component); Self::tessellate(&mut tess, &mut mesh, shapes); } for wire in self.pcb.wires() { let col = WIRE[Self::layer_id_to_color_idx(wire.shape.layers.id().unwrap())]; let shapes = Self::draw_shape(&tf, &wire.shape, col); Self::tessellate(&mut tess, &mut mesh, shapes); } for via in self.pcb.vias() { let shapes = Self::draw_padstack(&via.tf(), &via.padstack, *VIA); Self::tessellate(&mut tess, &mut mesh, shapes); } for rt in self.pcb.debug_rts() { let mut pts = rt.pts().to_vec(); pts.push(rt.pts()[0]); let shape = path(&pts, 0.05).shape(); let shapes = Self::draw_shape(&tf, &LayerShape { shape, layers: LayerSet::empty() }, *DEBUG); Self::tessellate(&mut tess, &mut mesh, shapes); } self.mesh = mesh; } let mut mesh = self.mesh.clone(); if self.dirty { let inv = Tf::scale(pt(1.0, -1.0)); let local_area = inv.rt(&self.local_area).bounds(); let tf = Tf::translate(self.offset) * Tf::scale(pt(self.zoom, self.zoom)) * Tf::affine(&local_area, &self.screen_area) * inv; for vert in &mut mesh.vertices { vert.pos = to_pos2(tf.pt(to_pt(vert.pos))); } self.dirty = false; } mesh } }
use std::lazy::SyncLazy; use eframe::egui::epaint::{Mesh, TessellationOptions, Tessellator}; use eframe::egui::{epaint, Color32, Context, PointerButton, Response, Sense, Ui, Widget}; use memegeom::primitive::point::Pt; use memegeom::primitive::rect::Rt; use memegeom::primitive::shape::Shape; use memegeom::primitive::{path, pt, ShapeOps}; use memegeom::tf::Tf; use memeroute::model::pcb::{ Component, Keepout, LayerId, LayerSet, LayerShape, Padstack, Pcb, Pin, }; use crate::pcb::primitives::{fill_circle, fill_polygon, fill_rt, stroke_path}; use crate::pcb::{to_pos2, to_pt, to_rt}; static KEEPOUT: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(155, 27, 0, 180)); static OUTLINE: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(89, 113, 193, 180), Color32::from_rgba_unmultiplied(168, 0, 186, 180), ] }); static BOUNDARY: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(255, 199, 46, 180)); static PIN: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(0, 27, 161, 180), Color32::from_rgba_unmultiplied(0, 27, 161, 180), ] }); static WIRE: SyncLazy<[Color32; 2]> = SyncLazy::new(|| { [ Color32::from_rgba_unmultiplied(252, 3, 182, 180), Color32::from_rgba_unmultiplied(0, 166, 52, 180), ] }); static VIA: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(100, 100, 100, 180)); static DEBUG: SyncLazy<Color32> = SyncLazy::new(|| Color32::from_rgba_unmultiplied(123, 0, 255, 180)); #[derive(Debug, Clone)] pub struct PcbView { pcb: Pcb, screen_area
let tf = tf * v.tf(); for outline in &v.outlines { let idx = outline.layers.first().unwrap(); shapes.extend(Self::draw_shape(&tf, outline, OUTLINE[idx])); } for keepout in &v.keepouts { shapes.extend(Self::draw_keepout(&tf, keepout, *KEEPOUT)); } for pin in v.pins() { let idx = pin.padstack.layers().first().unwrap(); shapes.extend(Self::draw_pin(&tf, pin, PIN[idx])); } shapes } fn tessellate(tess: &mut Tessellator, mesh: &mut Mesh, shapes: Vec<epaint::Shape>) { for s in shapes { tess.tessellate_shape(s, mesh); } } fn render(&mut self, ctx: &Context) -> Mesh { if self.mesh.is_empty() { let mut mesh = Mesh::default(); let tf = Tf::new(); let mut tess = Tessellator::new( ctx.pixels_per_point(), TessellationOptions { feathering: false, ..Default::default() }, ctx.fonts().font_image_size(), ); for boundary in self.pcb.boundaries() { let shapes = Self::draw_shape(&tf, boundary, *BOUNDARY); Self::tessellate(&mut tess, &mut mesh, shapes); } for keepout in self.pcb.keepouts() { let shapes = Self::draw_keepout(&tf, keepout, *KEEPOUT); Self::tessellate(&mut tess, &mut mesh, shapes); } for component in self.pcb.components() { let shapes = Self::draw_component(&tf, component); Self::tessellate(&mut tess, &mut mesh, shapes); } for wire in self.pcb.wires() { let col = WIRE[Self::layer_id_to_color_idx(wire.shape.layers.id().unwrap())]; let shapes = Self::draw_shape(&tf, &wire.shape, col); Self::tessellate(&mut tess, &mut mesh, shapes); } for via in self.pcb.vias() { let shapes = Self::draw_padstack(&via.tf(), &via.padstack, *VIA); Self::tessellate(&mut tess, &mut mesh, shapes); } for rt in self.pcb.debug_rts() { let mut pts = rt.pts().to_vec(); pts.push(rt.pts()[0]); let shape = path(&pts, 0.05).shape(); let shapes = Self::draw_shape(&tf, &LayerShape { shape, layers: LayerSet::empty() }, *DEBUG); Self::tessellate(&mut tess, &mut mesh, shapes); } self.mesh = mesh; } let mut mesh = self.mesh.clone(); if self.dirty { let inv = Tf::scale(pt(1.0, -1.0)); let local_area = inv.rt(&self.local_area).bounds(); let tf = Tf::translate(self.offset) * Tf::scale(pt(self.zoom, self.zoom)) * Tf::affine(&local_area, &self.screen_area) * inv; for vert in &mut mesh.vertices { vert.pos = to_pos2(tf.pt(to_pt(vert.pos))); } self.dirty = false; } mesh } }
: Rt, local_area: Rt, offset: Pt, zoom: f64, dirty: bool, mesh: Mesh, } impl Widget for &mut PcbView { fn ui(self, ui: &mut Ui) -> Response { let (response, painter) = ui.allocate_painter(ui.available_size_before_wrap(), Sense::click_and_drag()); if response.dragged_by(PointerButton::Middle) { let p = response.drag_delta(); self.offset += pt(p.x as f64, p.y as f64); } if ui.rect_contains_pointer(response.rect) { let pos = to_pt(ui.ctx().input().pointer.interact_pos().unwrap()); let delta = ui.ctx().input().scroll_delta.y as f64; let fac = 10.0 * delta / response.rect.height() as f64; self.offset = self.offset + (self.offset - pos) * fac; self.zoom *= 1.0 + fac; } self.set_screen_area(to_rt(response.rect)); let mesh = self.render(ui.ctx()); painter.rect_filled(response.rect, 0.0, Color32::WHITE); painter.add(epaint::Shape::Mesh(mesh)); response } } impl PcbView { pub fn new(pcb: Pcb, local_area: Rt) -> Self { Self { pcb, local_area, dirty: true, offset: Pt::zero(), zoom: 1.0, screen_area: Rt::default(), mesh: Mesh::default(), } } pub fn set_pcb(&mut self, pcb: Pcb) { self.pcb = pcb; self.dirty = true; self.mesh.clear(); } fn set_screen_area(&mut self, screen_area: Rt) { self.screen_area = screen_area; self.local_area = self.local_area.match_aspect(&self.screen_area); self.dirty = true; } fn layer_id_to_color_idx(id: LayerId) -> usize { id as usize } fn draw_shape(tf: &Tf, v: &LayerShape, col: Color32) -> Vec<epaint::Shape> { let mut shapes = Vec::new(); match &v.shape { Shape::Rect(s) => shapes.push(fill_rt(tf, s, col)), Shape::Circle(s) => shapes.push(fill_circle(tf, s.p(), s.r(), col)), Shape::Polygon(s) => shapes.push(fill_polygon(tf, s.pts(), s.tri_idx(), col)), Shape::Path(s) => { let r = if s.r() == 0.0 { 0.1 } else { s.r() }; shapes.extend(stroke_path(tf, s.pts(), r, col)); } _ => todo!(), } shapes } fn draw_keepout(tf: &Tf, v: &Keepout, col: Color32) -> Vec<epaint::Shape> { Self::draw_shape(tf, &v.shape, col) } fn draw_padstack(tf: &Tf, v: &Padstack, col: Color32) -> Vec<epaint::Shape> { let mut shapes = Vec::new(); for shape in &v.shapes { shapes.extend(Self::draw_shape(tf, shape, col)); } shapes } fn draw_pin(tf: &Tf, v: &Pin, col: Color32) -> Vec<epaint::Shape> { Self::draw_padstack(&(tf * v.tf()), &v.padstack, col) } fn draw_component(tf: &Tf, v: &Component) -> Vec<epaint::Shape> { let mut shapes = Vec::new();
random
[ { "content": "#[must_use]\n\npub fn to_pt(p: Pos2) -> Pt {\n\n pt(p.x as f64, p.y as f64)\n\n}\n\n\n", "file_path": "memeroute-gui/src/pcb/mod.rs", "rank": 0, "score": 104123.93811878798 }, { "content": "pub fn fill_polygon(tf: &Tf, pts: &[Pt], tris: &[u32], col: Color32) -> epaint::Shape...
Rust
spotify_player/src/state/ui.rs
aome510/spotify-player
15a8e2d88d06c0f96f54cec864ccfd9a4f889b06
use super::model::*; use crate::{config, key, utils}; use tui::widgets::*; pub type UIStateGuard<'a> = parking_lot::MutexGuard<'a, UIState>; #[derive(Debug)] pub struct UIState { pub is_running: bool, pub theme: config::Theme, pub input_key_sequence: key::KeySequence, pub history: Vec<PageState>, pub popup: Option<PopupState>, pub window: WindowState, pub progress_bar_rect: tui::layout::Rect, } #[derive(Clone, Debug)] pub enum PageState { Library, Context(Option<ContextId>, ContextPageType), Searching { input: String, current_query: String, }, Recommendations(SeedItem), } #[derive(Clone, Debug)] pub enum ContextPageType { CurrentPlaying, Browsing(ContextId), } #[derive(Debug)] pub enum WindowState { Unknown, Library { playlist_list: ListState, saved_album_list: ListState, followed_artist_list: ListState, focus: LibraryFocusState, }, Playlist { track_table: TableState, }, Album { track_table: TableState, }, Artist { top_track_table: TableState, album_list: ListState, related_artist_list: ListState, focus: ArtistFocusState, }, Search { track_list: ListState, album_list: ListState, artist_list: ListState, playlist_list: ListState, focus: SearchFocusState, }, Recommendations { track_table: TableState, }, } #[derive(Debug)] pub enum PopupState { CommandHelp { offset: usize }, Search { query: String }, UserPlaylistList(PlaylistPopupAction, ListState), UserFollowedArtistList(ListState), UserSavedAlbumList(ListState), DeviceList(ListState), ArtistList(Vec<Artist>, ListState), ThemeList(Vec<config::Theme>, ListState), ActionList(Item, ListState), } #[derive(Debug)] pub enum PlaylistPopupAction { Browse, AddTrack(TrackId), } pub trait Focusable { fn next(&mut self); fn previous(&mut self); } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum LibraryFocusState { Playlists, SavedAlbums, FollowedArtists, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ArtistFocusState { TopTracks, Albums, RelatedArtists, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum SearchFocusState { Input, Tracks, Albums, Artists, Playlists, } impl UIState { pub fn current_page(&self) -> &PageState { self.history.last().expect("History must not be empty") } pub fn current_page_mut(&mut self) -> &mut PageState { self.history.last_mut().expect("History must not be empty") } pub fn create_new_page(&mut self, page: PageState) { self.history.push(page); self.popup = None; } } impl Default for UIState { fn default() -> Self { Self { is_running: true, theme: config::Theme::default(), input_key_sequence: key::KeySequence { keys: vec![] }, history: vec![PageState::Library], popup: None, window: WindowState::Unknown, progress_bar_rect: tui::layout::Rect::default(), } } } impl PageState { pub fn context_uri(&self) -> Option<String> { match self { Self::Context(context_id, _) => context_id.as_ref().map(|id| id.uri()), _ => None, } } } impl WindowState { pub fn new_search_state() -> Self { Self::Search { track_list: utils::new_list_state(), album_list: utils::new_list_state(), artist_list: utils::new_list_state(), playlist_list: utils::new_list_state(), focus: SearchFocusState::Input, } } } impl PopupState { pub fn list_state(&self) -> Option<&ListState> { match self { Self::DeviceList(list_state) => Some(list_state), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::UserSavedAlbumList(list_state) => Some(list_state), Self::ArtistList(.., list_state) => Some(list_state), Self::ThemeList(.., list_state) => Some(list_state), Self::ActionList(.., list_state) => Some(list_state), Self::CommandHelp { .. } | Self::Search { .. } => None, } } pub fn list_state_mut(&mut self) -> Option<&mut ListState> { match self { Self::DeviceList(list_state) => Some(list_state), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::UserSavedAlbumList(list_state) => Some(list_state), Self::ArtistList(.., list_state) => Some(list_state), Self::ThemeList(.., list_state) => Some(list_state), Self::ActionList(.., list_state) => Some(list_state), Self::CommandHelp { .. } | Self::Search { .. } => None, } } pub fn list_selected(&self) -> Option<usize> { match self.list_state() { None => None, Some(state) => state.selected(), } } pub fn list_select(&mut self, id: Option<usize>) { match self.list_state_mut() { None => {} Some(state) => state.select(id), } } } impl WindowState { pub fn track_table_state(&mut self) -> Option<&mut TableState> { match self { Self::Playlist { track_table } => Some(track_table), Self::Album { track_table } => Some(track_table), Self::Artist { top_track_table, .. } => Some(top_track_table), Self::Recommendations { track_table } => Some(track_table), _ => None, } } pub fn select(&mut self, id: Option<usize>) { match self { Self::Unknown => {} Self::Library { playlist_list, saved_album_list, followed_artist_list, focus, } => match focus { LibraryFocusState::Playlists => playlist_list.select(id), LibraryFocusState::SavedAlbums => saved_album_list.select(id), LibraryFocusState::FollowedArtists => followed_artist_list.select(id), }, Self::Search { track_list, album_list, artist_list, playlist_list, focus, } => match focus { SearchFocusState::Input => {} SearchFocusState::Tracks => track_list.select(id), SearchFocusState::Albums => album_list.select(id), SearchFocusState::Artists => artist_list.select(id), SearchFocusState::Playlists => playlist_list.select(id), }, Self::Playlist { track_table } => track_table.select(id), Self::Album { track_table } => track_table.select(id), Self::Artist { top_track_table, album_list, related_artist_list, focus, } => match focus { ArtistFocusState::TopTracks => top_track_table.select(id), ArtistFocusState::Albums => album_list.select(id), ArtistFocusState::RelatedArtists => related_artist_list.select(id), }, Self::Recommendations { track_table } => track_table.select(id), } } pub fn selected(&self) -> Option<usize> { match self { Self::Unknown => None, Self::Library { playlist_list, saved_album_list, followed_artist_list, focus, } => match focus { LibraryFocusState::Playlists => playlist_list.selected(), LibraryFocusState::SavedAlbums => saved_album_list.selected(), LibraryFocusState::FollowedArtists => followed_artist_list.selected(), }, Self::Search { track_list, album_list, artist_list, playlist_list, focus, } => match focus { SearchFocusState::Input => None, SearchFocusState::Tracks => track_list.selected(), SearchFocusState::Albums => album_list.selected(), SearchFocusState::Artists => artist_list.selected(), SearchFocusState::Playlists => playlist_list.selected(), }, Self::Playlist { track_table } => track_table.selected(), Self::Album { track_table } => track_table.selected(), Self::Artist { top_track_table, album_list, related_artist_list, focus, } => match focus { ArtistFocusState::TopTracks => top_track_table.selected(), ArtistFocusState::Albums => album_list.selected(), ArtistFocusState::RelatedArtists => related_artist_list.selected(), }, Self::Recommendations { track_table } => track_table.selected(), } } } impl Focusable for WindowState { fn next(&mut self) { match self { Self::Artist { focus, .. } => focus.next(), Self::Search { focus, .. } => focus.next(), Self::Library { focus, .. } => focus.next(), _ => {} } self.select(Some(0)); } fn previous(&mut self) { match self { Self::Artist { focus, .. } => focus.previous(), Self::Search { focus, .. } => focus.previous(), Self::Library { focus, .. } => focus.previous(), _ => {} } self.select(Some(0)); } } macro_rules! impl_focusable { ($struct:ty, $([$field:ident, $next_field:ident]),+) => { impl Focusable for $struct { fn next(&mut self) { *self = match self { $( Self::$field => Self::$next_field, )+ }; } fn previous(&mut self) { *self = match self { $( Self::$next_field => Self::$field, )+ }; } } }; } impl_focusable!( LibraryFocusState, [Playlists, SavedAlbums], [SavedAlbums, FollowedArtists], [FollowedArtists, Playlists] ); impl_focusable!( ArtistFocusState, [TopTracks, Albums], [Albums, RelatedArtists], [RelatedArtists, TopTracks] ); impl_focusable!( SearchFocusState, [Input, Tracks], [Tracks, Albums], [Albums, Artists], [Artists, Playlists], [Playlists, Input] );
use super::model::*; use crate::{config, key, utils}; use tui::widgets::*; pub type UIStateGuard<'a> = parking_lot::MutexGuard<'a, UIState>; #[derive(Debug)] pub struct UIState { pub is_running: bool, pub theme: config::Theme, pub input_key_sequence: key::KeySequence, pub history: Vec<PageState>, pub popup: Option<PopupState>, pub window: WindowState, pub progress_bar_rect: tui::layout::Rect, } #[derive(Clone, Debug)] pub enum PageState { Library, Context(Option<ContextId>, ContextPageType), Searching { input: String, current_query: String, }, Recommendations(SeedItem), } #[derive(Clone, Debug)] pub enum ContextPageType { CurrentPlaying, Browsing(ContextId), } #[derive(Debug)] pub enum WindowState { Unknown, Library { playlist_list: ListState, saved_album_list: ListState, followed_artist_list: ListState, focus: LibraryFocusState, }, Playlist { track_table: TableState, }, Album { track_table: TableState, }, Artist { top_track_table: TableState, album_list: ListState, related_artist_list: ListState, focus: ArtistFocusState, }, Search { track_list: ListState, album_list: ListState, artist_list: ListState, playlist_list: ListState, focus: SearchFocusState, }, Recommendations { track_table: TableState, }, } #[derive(Debug)] pub enum PopupState { CommandHelp { offset: usize }, Search { query: String }, UserPlaylistList(PlaylistPopupAction, ListState), UserFollowedArtistList(ListState), UserSavedAlbumList(ListState), DeviceList(ListState), ArtistList(Vec<Artist>, ListState), ThemeList(Vec<config::Theme>, ListState), ActionList(Item, ListState), } #[derive(Debug)] pub enum PlaylistPopupAction { Browse, AddTrack(TrackId), } pub trait Focusable { fn next(&mut self); fn previous(&mut self); } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum LibraryFocusState { Playlists, SavedAlbums, FollowedArtists, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ArtistFocusState { TopTracks, Albums, RelatedArtists, } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum SearchFocusState { Input, Tracks, Albums, Artists, Playlists, } impl UIState { pub fn current_page(&self) -> &PageState { self.history.last().expect("History must not be empty") } pub fn current_page_mut(&mut self) -> &mut PageState { self.history.last_mut().expect("History must not be empty") } pub fn create_new_page(&mut self, page: PageState) { self.history.push(page); self.popup = None; } } impl Default for UIState { fn default() -> Self { Self { is_running: true, theme: config::Theme::default(), input_key_sequence: key::KeySequence { keys: vec![] }, history: vec![PageState::Library], popup: None, window: WindowState::Unknown, progress_bar_rect: tui::layout::Rect::default(), } } } impl PageState { pub fn context_uri(&self) -> Option<String> { match self { Self::Context(context_id, _) => context_id.as_ref().map(|id| id.uri()), _ => None, } } } impl WindowState { pub fn new_search_state() -> Self { Self::Search { track_list: utils::new_list_state(), album_list: utils::new_list_state(), artist_list: utils::new_list_state(), playlist_list: utils::new_list_state(), focus: SearchFocusState::Input, } } } impl PopupState { pub fn list_state(&self) -> Option<&ListState> { match self { Self::DeviceList(list_state) => Some(list_stat
pub fn list_state_mut(&mut self) -> Option<&mut ListState> { match self { Self::DeviceList(list_state) => Some(list_state), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::UserSavedAlbumList(list_state) => Some(list_state), Self::ArtistList(.., list_state) => Some(list_state), Self::ThemeList(.., list_state) => Some(list_state), Self::ActionList(.., list_state) => Some(list_state), Self::CommandHelp { .. } | Self::Search { .. } => None, } } pub fn list_selected(&self) -> Option<usize> { match self.list_state() { None => None, Some(state) => state.selected(), } } pub fn list_select(&mut self, id: Option<usize>) { match self.list_state_mut() { None => {} Some(state) => state.select(id), } } } impl WindowState { pub fn track_table_state(&mut self) -> Option<&mut TableState> { match self { Self::Playlist { track_table } => Some(track_table), Self::Album { track_table } => Some(track_table), Self::Artist { top_track_table, .. } => Some(top_track_table), Self::Recommendations { track_table } => Some(track_table), _ => None, } } pub fn select(&mut self, id: Option<usize>) { match self { Self::Unknown => {} Self::Library { playlist_list, saved_album_list, followed_artist_list, focus, } => match focus { LibraryFocusState::Playlists => playlist_list.select(id), LibraryFocusState::SavedAlbums => saved_album_list.select(id), LibraryFocusState::FollowedArtists => followed_artist_list.select(id), }, Self::Search { track_list, album_list, artist_list, playlist_list, focus, } => match focus { SearchFocusState::Input => {} SearchFocusState::Tracks => track_list.select(id), SearchFocusState::Albums => album_list.select(id), SearchFocusState::Artists => artist_list.select(id), SearchFocusState::Playlists => playlist_list.select(id), }, Self::Playlist { track_table } => track_table.select(id), Self::Album { track_table } => track_table.select(id), Self::Artist { top_track_table, album_list, related_artist_list, focus, } => match focus { ArtistFocusState::TopTracks => top_track_table.select(id), ArtistFocusState::Albums => album_list.select(id), ArtistFocusState::RelatedArtists => related_artist_list.select(id), }, Self::Recommendations { track_table } => track_table.select(id), } } pub fn selected(&self) -> Option<usize> { match self { Self::Unknown => None, Self::Library { playlist_list, saved_album_list, followed_artist_list, focus, } => match focus { LibraryFocusState::Playlists => playlist_list.selected(), LibraryFocusState::SavedAlbums => saved_album_list.selected(), LibraryFocusState::FollowedArtists => followed_artist_list.selected(), }, Self::Search { track_list, album_list, artist_list, playlist_list, focus, } => match focus { SearchFocusState::Input => None, SearchFocusState::Tracks => track_list.selected(), SearchFocusState::Albums => album_list.selected(), SearchFocusState::Artists => artist_list.selected(), SearchFocusState::Playlists => playlist_list.selected(), }, Self::Playlist { track_table } => track_table.selected(), Self::Album { track_table } => track_table.selected(), Self::Artist { top_track_table, album_list, related_artist_list, focus, } => match focus { ArtistFocusState::TopTracks => top_track_table.selected(), ArtistFocusState::Albums => album_list.selected(), ArtistFocusState::RelatedArtists => related_artist_list.selected(), }, Self::Recommendations { track_table } => track_table.selected(), } } } impl Focusable for WindowState { fn next(&mut self) { match self { Self::Artist { focus, .. } => focus.next(), Self::Search { focus, .. } => focus.next(), Self::Library { focus, .. } => focus.next(), _ => {} } self.select(Some(0)); } fn previous(&mut self) { match self { Self::Artist { focus, .. } => focus.previous(), Self::Search { focus, .. } => focus.previous(), Self::Library { focus, .. } => focus.previous(), _ => {} } self.select(Some(0)); } } macro_rules! impl_focusable { ($struct:ty, $([$field:ident, $next_field:ident]),+) => { impl Focusable for $struct { fn next(&mut self) { *self = match self { $( Self::$field => Self::$next_field, )+ }; } fn previous(&mut self) { *self = match self { $( Self::$next_field => Self::$field, )+ }; } } }; } impl_focusable!( LibraryFocusState, [Playlists, SavedAlbums], [SavedAlbums, FollowedArtists], [FollowedArtists, Playlists] ); impl_focusable!( ArtistFocusState, [TopTracks, Albums], [Albums, RelatedArtists], [RelatedArtists, TopTracks] ); impl_focusable!( SearchFocusState, [Input, Tracks], [Tracks, Albums], [Albums, Artists], [Artists, Playlists], [Playlists, Input] );
e), Self::UserPlaylistList(.., list_state) => Some(list_state), Self::UserFollowedArtistList(list_state) => Some(list_state), Self::UserSavedAlbumList(list_state) => Some(list_state), Self::ArtistList(.., list_state) => Some(list_state), Self::ThemeList(.., list_state) => Some(list_state), Self::ActionList(.., list_state) => Some(list_state), Self::CommandHelp { .. } | Self::Search { .. } => None, } }
function_block-function_prefixed
[ { "content": "/// truncates a string whose length exceeds a given `max_len` length.\n\n/// Such string will be appended with `...` at the end.\n\npub fn truncate_string(s: String, max_len: usize) -> String {\n\n let len = UnicodeWidthStr::width(s.as_str());\n\n if len > max_len {\n\n // get the lon...
Rust
src/main.rs
sambuc/mercator_data_generator
67d20946525542eba29ad4eca36dc808b7363ce8
#![forbid(unsafe_code)] use std::fs::File; use std::io::BufWriter; use mercator_db::storage::model::v1::Shape; use mercator_db::storage::model::*; use rand::distributions::Distribution; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use serde::Serialize; use structopt::StructOpt; const POSITIONS_PER_SHAPE: usize = 1000; fn get_axis( unit_vector: Vec<f64>, minimum: f64, maximum: f64, steps: u64, measurement_unit: &str, set: &str, ) -> Axis { Axis { measurement_unit: measurement_unit.to_string(), graduation: Graduation { set: set.to_string(), minimum, maximum, steps, }, unit_vector, } } fn get_reference_space() -> Vec<Space> { vec![Space { name: "std".to_string(), origin: vec![0.0, 0.0, 0.0], axes: vec![ get_axis(vec![1.0, 0.0, 0.0], 0.0, 1.0, 1_000_000_000, "m", "R"), get_axis(vec![0.0, 1.0, 0.0], 0.0, 1.0, 1_000_000_000, "m", "R"), get_axis(vec![0.0, 0.0, 1.0], 0.0, 1.0, 1_000_000_000, "m", "R"), ], }] } fn store<T>(basename: &str, data: T) where T: Serialize, { let to = format!("{}.json", basename); let file_out = File::create(&to).unwrap_or_else(|e| panic!("Unable to create file '{}': {}", to, e)); let writer = BufWriter::new(&file_out); serde_json::to_writer(writer, &data) .unwrap_or_else(|e| panic!("Unable to serialize to '{}': {}", to, e)); } fn generate_points( factor: usize, space_name: &str, rng: &mut ThreadRng, die: &Uniform<f64>, ) -> Vec<SpatialObject> { let mut shapes = Vec::with_capacity(POSITIONS_PER_SHAPE); let mut v = Vec::with_capacity(factor); for _ in 0..POSITIONS_PER_SHAPE { shapes.push(Shape { type_name: "Point".to_string(), vertices: vec![vec![die.sample(rng), die.sample(rng), die.sample(rng)]], reference_space: space_name.to_string(), }); } for _ in 0..(factor - 1) { v.push(SpatialObject { properties: Properties { type_name: "Feature".to_string(), id: format!("oid{}", die.sample(rng)), }, shapes: shapes.clone(), }); } v.push(SpatialObject { properties: Properties { type_name: "Feature".to_string(), id: format!("oid{}", die.sample(rng)), }, shapes, }); v } fn generate_data(nb_points: usize, factor: usize, rng: &mut ThreadRng, die: &Uniform<f64>) { let space_name = "std"; let mut objects = Vec::with_capacity(nb_points); store( format!("{}k.spaces", nb_points).as_str(), get_reference_space(), ); for _ in 0..nb_points { objects.append(&mut generate_points(factor, &space_name, rng, &die)); } store(format!("{}k.objects", nb_points).as_str(), objects); } #[derive(StructOpt, Debug)] struct Opt { #[structopt(long, short)] factor: Option<usize>, datasets: Vec<usize>, } fn main() { let opt = Opt::from_args(); let factor = match opt.factor { None => 1, Some(val) => val, }; let mut rng = rand::thread_rng(); let die = Uniform::from(0.0..1.0); for dataset in opt.datasets { generate_data(dataset, factor, &mut rng, &die); } }
#![forbid(unsafe_code)] use std::fs::File; use std::io::BufWriter; use mercator_db::storage::model::v1::Shape; use mercator_db::storage::model::*; use rand::distributions::Distribution; use rand::distributions::Uniform; use rand::prelude::ThreadRng; use serde::Serialize; use structopt::StructOpt; const POSITIONS_PER_SHAPE: usize = 1000; fn get_axis( unit_vector: Vec<f64>, minimum: f64, maximum: f64, steps: u64, measurement_unit: &str, set: &str, ) -> Axis { Axis { measurement_unit: measurement_unit.to_string(), graduation: Graduation { set: set.to_string(), minimum, maximum, steps, }, unit_vector, } } fn get_reference_space() -> Vec<Space> { vec![Space { name: "std".to_string(), origin: vec![0.0, 0.0, 0.0], axes: vec![ get_axis(vec![1.0, 0.0, 0.0], 0.0, 1.0, 1_000_000_000, "m", "R"), get_axis(vec![0.0, 1.0, 0.0], 0.0, 1.0, 1_000_000_000, "m", "R"), get_axis(vec![0.0, 0.0, 1.0], 0.0, 1.0, 1_000_000_000, "m", "R"), ], }] } fn store<T>(basename: &str, data: T) where T: Serialize, { let to = format!("{}.json", basename); let file_out = File::create(&to).unwrap_or_else(|e| panic!("Unable to create file '{}': {}", to, e)); let writer = BufWriter::new(&file_out); serde_json::to_writer(writer, &data) .unwrap_or_else(|e| panic!("Unable to serialize to '{}': {}", to, e)); } fn generate_points( factor: usize, space_name: &str, rng: &mut ThreadRng, die: &Uniform<f64>, ) -> Vec<SpatialObject> { let mut shapes = Vec::with_capacity(POSITIONS_PER_SHAPE); let mut v = Vec::with_capacity(factor); for _ in 0..POSITIONS_PER_SHAPE { shapes.push(Shape { type_name: "Point".to_string(), vertices: vec![vec![die.sample(rng), die.sample(rng), die.sample(rng)]], reference_space: space_name.to_string(), }); } for _ in 0..(factor - 1) { v.push(SpatialObject { properties: Properties { type_name: "Feature".to_string(), id: format!("oid{}", die.sample(rng)), }, shapes: shapes.clone(), }); } v.push(SpatialObject { properties: Properties { type_name: "Feature".to_string(), id: format!("oid{}", die.sample(rng)), }, shapes, }); v } fn generate_data(nb_points: usize, factor: usize, rng: &mut ThreadRng, die: &Uniform<f64>) { let space_name = "std"; let mut objects = Vec::with_capacity(nb_points); store( format!("{}k.spaces", nb_points).as_str(), get_reference_spac
#[derive(StructOpt, Debug)] struct Opt { #[structopt(long, short)] factor: Option<usize>, datasets: Vec<usize>, } fn main() { let opt = Opt::from_args(); let factor = match opt.factor { None => 1, Some(val) => val, }; let mut rng = rand::thread_rng(); let die = Uniform::from(0.0..1.0); for dataset in opt.datasets { generate_data(dataset, factor, &mut rng, &die); } }
e(), ); for _ in 0..nb_points { objects.append(&mut generate_points(factor, &space_name, rng, &die)); } store(format!("{}k.objects", nb_points).as_str(), objects); }
function_block-function_prefixed
[ { "content": "# Mercator Test data generator\n\n\n\nTool to generate test data for Mercator, a spatial index.\n\n\n\n## Mercator: Spatial Index\n\n\n\n**Mercator** is a spatial *volumetric* index for the [Human Brain Project](http://www.humanbrainproject.eu). It is a component of the [Knowledge Graph](http://ww...
Rust
src/ws.rs
jnicholls/binance-api
0093f8dd053c91de988c33597e485093f70d3db2
use std::collections::BTreeMap; use std::marker::{PhantomData, Unpin}; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use std::time::Duration; use async_tungstenite::{ tokio::{connect_async, ConnectStream}, tungstenite::Message, WebSocketStream, }; use futures::{ future::{self, Either, FutureExt}, sink::SinkExt, stream::{SplitSink, SplitStream, Stream, StreamExt}, }; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ sync::{mpsc, oneshot}, time, }; use crate::{error::*, extensions::*, models::*}; const WS_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); const WSSAPI_HOST: &str = "wss://stream.binance.com:9443/ws/"; const WSFAPI_HOST: &str = "wss://fstream.binance.com/ws/"; pub type WSFClient = WSClient<WSFApi>; pub type WSSClient = WSClient<WSSApi>; #[derive(Debug)] struct ClientState { is_closed: bool, next_id: u64, requests: BTreeMap<u64, oneshot::Sender<Result<WSResponse, WSApiCode>>>, } struct EventDispatcher<OrderType> { close_rx: oneshot::Receiver<()>, event_tx: mpsc::Sender<Result<WSEvent<OrderType>, WSApiCode>>, request_tx: mpsc::Sender<WSMessage<OrderType>>, state: Arc<Mutex<ClientState>>, stream: SplitStream<WebSocketStream<ConnectStream>>, } impl<OrderType> EventDispatcher<OrderType> where OrderType: DeserializeOwned, { async fn dispatch_events(mut self) { loop { let either = future::select(self.stream.next(), self.close_rx).await; match either { Either::Left((next, close_rx)) => { self.close_rx = close_rx; if let Some(msg) = next { match msg { Ok(msg) => match msg { Message::Text(t) => match serde_json::from_str(&t) { Ok(msg) => match msg { WSMessage::Event(event) => { let _ = self.event_tx.send(Ok(event)).await; } WSMessage::Response(resp) => { let tx = { let mut state = self.state.lock().unwrap(); state.requests.remove(&resp.id) }; if let Some(tx) = tx { let _ = tx.send(Ok(resp)); } } _ => (), }, Err(e) => { let _ = self.event_tx.send(Err(e.into())).await; break; } }, Message::Ping(p) => { let _ = self.request_tx.send(WSMessage::Pong(p)).await; } Message::Close(_) => break, _ => (), }, Err(e) => { let _ = self.event_tx.send(Err(e.into())).await; break; } } } else { break; } } Either::Right(_) => break, } } let mut state = self.state.lock().unwrap(); state.is_closed = true; } } struct RequestDispatcher<OrderType> { state: Arc<Mutex<ClientState>>, request_rx: mpsc::Receiver<WSMessage<OrderType>>, sink: SplitSink<WebSocketStream<ConnectStream>, Message>, } impl<OrderType> RequestDispatcher<OrderType> where OrderType: DeserializeOwned, { async fn dispatch_requests(mut self) { while let Some(msg) = self.request_rx.recv().await { match msg { WSMessage::Pong(p) => { let _ = self.sink.send(Message::Pong(p)).await; } WSMessage::Request(req) => match self.dispatch_request(&req).await { Err(e) => self.return_error(e, req.id.as_ref().unwrap()).await, _ => (), }, _ => (), } } } async fn return_error(&self, e: Error<WSApiCode>, id: &u64) { let tx = { let mut state = self.state.lock().unwrap(); state.requests.remove(id) }; if let Some(tx) = tx { let _ = tx.send(Err(e)); } } async fn dispatch_request(&mut self, req: &WSRequest) -> Result<(), WSApiCode> { let msg = Message::Text(serde_json::to_string(req)?); self.sink.send(msg).await?; Ok(()) } } pub struct WSClient<A: WSApi> { close_tx: oneshot::Sender<()>, request_tx: mpsc::Sender<WSMessage<A::OrderType>>, state: Arc<Mutex<ClientState>>, _marker: PhantomData<A>, } impl<A> WSClient<A> where A: WSApi, { async fn connect<S>(stream: Option<WSStream<S>>) -> Result<(Self, WSClientStream<A>), WSApiCode> where S: AsRef<str>, { let path = match stream.as_ref() { Some(s) => format!("{}{}", A::host(), s), None => A::host().to_string(), }; let (ws_stream, _) = connect_async(path).await?; let (sink, stream) = ws_stream.split(); let (event_tx, event_rx) = mpsc::channel(100); let (request_tx, request_rx) = mpsc::channel(1); let (close_tx, close_rx) = oneshot::channel(); let state = Arc::new(Mutex::new(ClientState { is_closed: false, next_id: 1, requests: BTreeMap::new(), })); { let state = state.clone(); let request_dispatcher = RequestDispatcher::<A::OrderType> { state, request_rx, sink, }; tokio::spawn(request_dispatcher.dispatch_requests()); } { let request_tx = request_tx.clone(); let state = state.clone(); let event_dispatcher = EventDispatcher::<A::OrderType> { close_rx, event_tx, request_tx, state, stream, }; tokio::spawn(event_dispatcher.dispatch_events()); } Ok(( Self { close_tx, request_tx, state, _marker: PhantomData, }, WSClientStream(event_rx), )) } async fn send_request(&self, mut req: WSRequest) -> Result<WSResponse, WSApiCode> { let timeout = req.timeout; let (tx, rx) = oneshot::channel(); { let mut state = self.state.lock().unwrap(); if state.is_closed { return Err(Error::WebsocketClosed); } let id = state.next_id; req.id = Some(id); state.requests.insert(id, tx); state.next_id += 1; } let _ = self.request_tx.send(WSMessage::Request(req)).await; let wait_for_result = rx.map(|r| r.map_err(|_| Error::WebsocketRequestCancelled).x_flatten()); let wait_for_timeout = match timeout { Some(timeout) => Either::Left(time::sleep(timeout)), None => Either::Right(future::pending::<()>()), } .map(|_| Err(Error::WebsocketRequestTimeout)); futures::pin_mut!(wait_for_timeout); match future::select(wait_for_result, wait_for_timeout).await { Either::Left((result, _)) => result, Either::Right((timeout, _)) => timeout, } } pub async fn market() -> Result<(Self, WSClientStream<A>), WSApiCode> { let stream: Option<WSStream<&str>> = None; Self::connect(stream).await } pub async fn user_data<S>(listen_key: S) -> Result<(Self, WSClientStream<A>), WSApiCode> where S: AsRef<str>, { Self::connect(Some(WSStream::UserData(listen_key))).await } pub fn close(self) { let _ = self.close_tx.send(()); } pub fn is_closed(&self) -> bool { let state = self.state.lock().unwrap(); state.is_closed } pub async fn subscribe<S>(&self, stream: WSStream<S>) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::Subscribe) .stream(stream) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn unsubscribe<S>(&self, stream: WSStream<S>) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::Unsubscribe) .stream(stream) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn list_subscriptions(&self) -> Result<WSResponse, WSApiCode> { self.send_request( WSRequest::new(WSRequestMethod::ListSubscriptions).timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn get_property<S>(&self, property: S) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::GetProperty) .get_property(property) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn set_property<S, T>(&self, property: S, value: T) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, T: Serialize, { self.send_request( WSRequest::new(WSRequestMethod::SetProperty) .set_property(property, value) .timeout(WS_REQUEST_TIMEOUT), ) .await } } pub struct WSClientStream<A: WSApi>(mpsc::Receiver<Result<WSEvent<A::OrderType>, WSApiCode>>); impl<A> Stream for WSClientStream<A> where A: WSApi, { type Item = Result<WSEvent<A::OrderType>, WSApiCode>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.0.poll_recv(cx) } } pub trait WSApi: Send + Sync + Unpin + 'static { type OrderType: DeserializeOwned + Send; fn host() -> &'static str; } pub struct WSFApi; impl WSApi for WSFApi { type OrderType = FOrderType; fn host() -> &'static str { WSFAPI_HOST } } pub struct WSSApi; impl WSApi for WSSApi { type OrderType = SOrderType; fn host() -> &'static str { WSSAPI_HOST } }
use std::collections::BTreeMap; use std::marker::{PhantomData, Unpin}; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; use std::time::Duration; use async_tungstenite::{ tokio::{connect_async, ConnectStream}, tungstenite::Message, WebSocketStream, }; use futures::{ future::{self, Either, FutureExt}, sink::SinkExt, stream::{SplitSink, SplitStream, Stream, StreamExt}, }; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ sync::{mpsc, oneshot}, time, }; use crate::{error::*, extensions::*, models::*}; const WS_REQUEST_TIMEOUT: Duration = Duration::from_secs(10); const WSSAPI_HOST: &str = "wss://stream.binance.com:9443/ws/"; const WSFAPI_HOST: &str = "wss://fstream.binance.com/ws/"; pub type WSFClient = WSClient<WSFApi>; pub type WSSClient = WSClient<WSSApi>; #[derive(Debug)] struct ClientState { is_closed: bool, next_id: u64, requests: BTreeMap<u64, oneshot::Sender<Result<WSResponse, WSApiCode>>>, } struct EventDispatcher<OrderType> { close_rx: oneshot::Receiver<()>, event_tx: mpsc::Sender<Result<WSEvent<OrderType>, WSApiCode>>, request_tx: mpsc::Sender<WSMessage<OrderType>>, state: Arc<Mutex<ClientState>>, stream: SplitStream<WebSocketStream<ConnectStream>>, } impl<OrderType> EventDispatcher<OrderType> where OrderType: DeserializeOwned, { async fn dispatch_events(mut self) { loop { let either = future::select(self.stream.next(), self.close_rx).await; match either { Either::Left((next, close_rx)) => { self.close_rx = close_rx; if let Some(msg) = next { match msg { Ok(msg) => match msg { Message::Text(t) => match serde_json::from_str(&t) { Ok(msg) => match msg { WSMessage::Event(event) => { let _ = self.event_tx.send(Ok(event)).await; } WSMessage::Response(resp) => { let tx = { let mut state = self.state.lock().unwrap(); state.requests.remove(&resp.id) }; if let Some(tx) = tx { let _ = tx.send(Ok(resp)); } } _ => (), }, Err(e) => { let _ = self.event_tx.send(Err(e.into())).await; break; } }, Message::Ping(p) => { let _ = self.request_tx.send(WSMessage::Pong(p)).await; } Message::Close(_) => break, _ => (), }, Err(e) => { let _ = self.event_tx.send(Err(e.into())).await; break; } } } else { break; } } Either::Right(_) => break, } } let mut state = self.state.lock().unwrap(); state.is_closed = true; } } struct RequestDispatcher<OrderType> { state: Arc<Mutex<ClientState>>, request_rx: mpsc::Receiver<WSMessage<OrderType>>, sink: SplitSink<WebSocketStream<ConnectStream>, Message>, } impl<OrderType> RequestDispatcher<OrderType> where OrderType: DeserializeOwned, { async fn dispatch_requests(mut self) { while let Some(msg) = self.request_rx.recv().await { match msg { WSMessage::Pong(p) => { let _ = self.sink.send(Message::Pong(p)).await; } WSMessage::Request(req) => match self.dispatch_request(&req).await { Err(e) => self.return_error(e, req.id.as_ref().unwrap()).await, _ => (), }, _ => (), } } } async fn return_error(&self, e: Error<WSApiCode>, id: &u64) { let tx = { let mut state = self.state.lock().unwrap(); state.requests.remove(id) }; if let Some(tx) = tx { let _ = tx.send(Err(e)); } } async fn dispatch_request(&mut self, req: &WSRequest) -> Result<(), WSApiCode> { let msg = Message::Text(serde_json::to_string(req)?); self.sink.send(msg).await?; Ok(()) } } pub struct WSClient<A: WSApi> { close_tx: oneshot::Sender<()>, request_tx: mpsc::Sender<WSMessage<A::OrderType>>, state: Arc<Mutex<ClientState>>, _marker: PhantomData<A>, } impl<A> WSClient<A> where A: WSApi, { async fn connect<S>(stream: Option<WSStream<S>>) -> Result<(Self, WSClientStream<A>), WSApiCode> where S: AsRef<str>, { let path = match stream.as_ref() { Some(s) => format!("{}{}", A::host(), s), None => A::host().to_string(), }; let (ws_stream, _) = connect_async(path).await?; let (sink, stream) = ws_stream.split(); let (event_tx, event_rx) = mpsc::channel(100); let (request_tx, request_rx) = mpsc::channel(1); let (close_tx, close_rx) = oneshot::channel(); let state = Arc::new(Mutex::new(ClientState { is_closed: false, next_id: 1, requests: BTreeMap::new(), })); { let state = state.clone(); let request_dispatcher = RequestDispatcher::<A::OrderType> { state, request_rx, sink, }; tokio::spawn(request_dispatcher.dispatch_requests()); } { let request_tx = request_tx.clone(); let state = state.clone(); let event_dispatcher = EventDispatcher::<A::OrderType> { close_rx, event_tx, request_tx, state, stream, }; tokio::spawn(event_dispatcher.dispatch_events()); }
} async fn send_request(&self, mut req: WSRequest) -> Result<WSResponse, WSApiCode> { let timeout = req.timeout; let (tx, rx) = oneshot::channel(); { let mut state = self.state.lock().unwrap(); if state.is_closed { return Err(Error::WebsocketClosed); } let id = state.next_id; req.id = Some(id); state.requests.insert(id, tx); state.next_id += 1; } let _ = self.request_tx.send(WSMessage::Request(req)).await; let wait_for_result = rx.map(|r| r.map_err(|_| Error::WebsocketRequestCancelled).x_flatten()); let wait_for_timeout = match timeout { Some(timeout) => Either::Left(time::sleep(timeout)), None => Either::Right(future::pending::<()>()), } .map(|_| Err(Error::WebsocketRequestTimeout)); futures::pin_mut!(wait_for_timeout); match future::select(wait_for_result, wait_for_timeout).await { Either::Left((result, _)) => result, Either::Right((timeout, _)) => timeout, } } pub async fn market() -> Result<(Self, WSClientStream<A>), WSApiCode> { let stream: Option<WSStream<&str>> = None; Self::connect(stream).await } pub async fn user_data<S>(listen_key: S) -> Result<(Self, WSClientStream<A>), WSApiCode> where S: AsRef<str>, { Self::connect(Some(WSStream::UserData(listen_key))).await } pub fn close(self) { let _ = self.close_tx.send(()); } pub fn is_closed(&self) -> bool { let state = self.state.lock().unwrap(); state.is_closed } pub async fn subscribe<S>(&self, stream: WSStream<S>) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::Subscribe) .stream(stream) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn unsubscribe<S>(&self, stream: WSStream<S>) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::Unsubscribe) .stream(stream) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn list_subscriptions(&self) -> Result<WSResponse, WSApiCode> { self.send_request( WSRequest::new(WSRequestMethod::ListSubscriptions).timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn get_property<S>(&self, property: S) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, { self.send_request( WSRequest::new(WSRequestMethod::GetProperty) .get_property(property) .timeout(WS_REQUEST_TIMEOUT), ) .await } pub async fn set_property<S, T>(&self, property: S, value: T) -> Result<WSResponse, WSApiCode> where S: AsRef<str>, T: Serialize, { self.send_request( WSRequest::new(WSRequestMethod::SetProperty) .set_property(property, value) .timeout(WS_REQUEST_TIMEOUT), ) .await } } pub struct WSClientStream<A: WSApi>(mpsc::Receiver<Result<WSEvent<A::OrderType>, WSApiCode>>); impl<A> Stream for WSClientStream<A> where A: WSApi, { type Item = Result<WSEvent<A::OrderType>, WSApiCode>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.0.poll_recv(cx) } } pub trait WSApi: Send + Sync + Unpin + 'static { type OrderType: DeserializeOwned + Send; fn host() -> &'static str; } pub struct WSFApi; impl WSApi for WSFApi { type OrderType = FOrderType; fn host() -> &'static str { WSFAPI_HOST } } pub struct WSSApi; impl WSApi for WSSApi { type OrderType = SOrderType; fn host() -> &'static str { WSSAPI_HOST } }
Ok(( Self { close_tx, request_tx, state, _marker: PhantomData, }, WSClientStream(event_rx), ))
call_expression
[ { "content": "pub trait TradeApi {\n\n type OrderRequestDetails: Serialize;\n\n type OrderDetails: DeserializeOwned;\n\n type OrderType: DeserializeOwned + Serialize;\n\n\n\n fn all_orders() -> &'static str;\n\n fn all_open_orders() -> &'static str;\n\n fn auto_cancel_all() -> &'static str;\n\...
Rust
src/days/aoc_2022.rs
Measter/AdventOfCode2020
e5c3f7f368b5df9f536a5c8740be0ea004b8ee7e
use std::{ collections::{HashSet, VecDeque}, num::ParseIntError, }; use aoc_lib::{day, parsers::split_pair, Bench, BenchResult, UserError}; use color_eyre::{eyre::Result, Report}; day! { day 22: "Crab Combat" 1: run_part1 2: run_part2 } fn run_part1(input: &str, b: Bench) -> BenchResult { let (p1_deck, p2_deck) = parse_input(input).map_err(UserError)?; b.bench(|| play_part1(p1_deck.clone(), p2_deck.clone())) } fn run_part2(input: &str, b: Bench) -> BenchResult { let (p1_deck, p2_deck) = parse_input(input).map_err(UserError)?; b.bench(|| Ok::<_, Report>(play_part2(p1_deck.clone(), p2_deck.clone())?.1)) } #[derive(Debug, Clone, Copy, PartialEq)] enum Winner { Player1, Player2, } fn parse_input(input: &str) -> Result<(VecDeque<u32>, VecDeque<u32>)> { let (player1_input, player2_input) = split_pair( input.trim_start().trim_start_matches("Player 1:"), "Player 2:", )?; let player1_deck = player1_input .trim() .lines() .map(str::trim) .map(str::parse) .collect::<Result<_, ParseIntError>>()?; let player2_deck = player2_input .trim() .lines() .map(str::trim) .map(str::parse) .collect::<Result<_, ParseIntError>>()?; Ok((player1_deck, player2_deck)) } fn play_part1(mut p1_deck: VecDeque<u32>, mut p2_deck: VecDeque<u32>) -> Result<u32> { let mut counter: u32 = 100_000; let mut winner = loop { counter = counter.saturating_sub(1); if p1_deck.is_empty() { break p2_deck; } else if p2_deck.is_empty() { break p1_deck; } else if counter == 0 { panic!("Maybe infinite loop?") } let p1_card = p1_deck.pop_front().unwrap(); let p2_card = p2_deck.pop_front().unwrap(); if p1_card > p2_card { p1_deck.push_back(p1_card); p1_deck.push_back(p2_card); } else { p2_deck.push_back(p2_card); p2_deck.push_back(p1_card); } }; let score = winner .drain(..) .rev() .zip(1..) .map(|(mul, card)| mul * card) .sum(); Ok(score) } fn play_part2(mut p1_deck: VecDeque<u32>, mut p2_deck: VecDeque<u32>) -> Result<(Winner, u32)> { let mut seen_decks: HashSet<(u32, u32)> = HashSet::new(); let mut round: u32 = 1; let (winner, mut winner_deck) = loop { let seen = seen_decks.insert(( p1_deck .iter() .rev() .copied() .zip(1..) .map(|(a, b)| a * b) .sum(), p2_deck .iter() .rev() .copied() .zip(1..) .map(|(a, b)| a * b) .sum(), )); if !seen { break (Winner::Player1, p1_deck); } round += 1; if p1_deck.is_empty() { break (Winner::Player2, p2_deck); } else if p2_deck.is_empty() { break (Winner::Player1, p1_deck); } else if round == 20_000 { panic!("Maybe infinite loop?") } let p1_card = p1_deck.pop_front().unwrap(); let p2_card = p2_deck.pop_front().unwrap(); let winner = if p1_card as usize <= p1_deck.len() && p2_card as usize <= p2_deck.len() { let p1_new_deck = p1_deck.iter().copied().take(p1_card as usize).collect(); let p2_new_deck = p2_deck.iter().copied().take(p2_card as usize).collect(); play_part2(p1_new_deck, p2_new_deck)?.0 } else if p1_card >= p2_card { Winner::Player1 } else { Winner::Player2 }; if winner == Winner::Player1 { p1_deck.push_back(p1_card); p1_deck.push_back(p2_card); } else { p2_deck.push_back(p2_card); p2_deck.push_back(p1_card); } }; let score = winner_deck .drain(..) .rev() .zip(1..) .map(|(mul, card)| mul * card) .sum(); Ok((winner, score)) } #[cfg(test)] mod tests_2022 { use aoc_lib::Example; use super::*; #[test] fn part1_example() { let input = aoc_lib::input(2020, 22) .example(Example::Part1, 1) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); let expected = 306; let actual = play_part1(player1, player2).unwrap(); assert_eq!(expected, actual); } #[test] fn part2_example_infinite_loop_test() { let input = aoc_lib::input(2020, 22) .example(Example::Part2, 1) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); play_part2(player1, player2).unwrap(); } #[test] fn part2_example2() { let input = aoc_lib::input(2020, 22) .example(Example::Part2, 2) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); let expected = (Winner::Player2, 291); let actual = play_part2(player1, player2).unwrap(); assert_eq!(expected, actual); } }
use std::{ collections::{HashSet, VecDeque}, num::ParseIntError, }; use aoc_lib::{day, parsers::split_pair, Bench, BenchResult, UserError}; use color_eyre::{eyre::Result, Report}; day! { day 22: "Crab Combat" 1: run_part1 2: run_part2 } fn run_part1(input: &str, b: Bench) -> BenchResult { let (p1_deck, p2_deck) = parse_input(input).map_err(UserError)?; b.bench(|| play_part1(p1_deck.clone(), p2_deck.clone())) } fn run_part2(input: &str, b: Bench) -> BenchResult { let (p1_deck, p2_deck) = parse_input(input).map_err(UserError)?; b.bench(|| Ok::<_, Report>(play_part2(p1_deck.clone(), p2_deck.clone())?.1)) } #[derive(Debug, Clone, Copy, PartialEq)] enum Winner { Player1, Player2, } fn parse_input(input: &str) -> Result<(VecDeque<u32>, VecDeque<u32>)> { let (player1_input, player2_input) = split_pair( input.trim_start().trim_start_matches("Player 1:"), "Player 2:", )?; let player1_deck = player1_input .trim() .lines() .map(str::trim) .map(str::parse) .collect::<Result<_, ParseIntError>>()?; let player2_deck = player2_input .trim() .lines() .map(str::trim) .map(str::parse) .collect::<Result<_, ParseIntError>>()?; Ok((player1_deck, player2_deck)) } fn play_part1(mut p1_deck: VecDeque<u32>, mut p2_deck: VecDeque<u32>) -> Result<u32> { let mut counter: u32 = 100_000; let mut winner = loop { counter = counter.saturating_sub(1); if p1_deck.is_empty() { break p2_deck; } else if p2_deck.is_empty() { break p1_deck; } else if counter == 0 { panic!("Maybe infinite loop?") } let p1_card = p1_deck.pop_front().unwrap(); let p2_card = p2_deck.pop_front().unwrap(); if p1_card > p2_card { p1_deck.push_back(p1_card); p1_deck.push_back(p2_card); } else { p2_deck.push_back(p2_card); p2_deck.push_back(p1_card); } }; let score = winner .drain(..) .rev() .zip(1..) .map(|(mul, card)| mul * card) .sum(); Ok(score) } fn play_part2(mut p1_deck: VecDeque<u32>, mut p2_deck: VecDeque<u32>) -> Result<(Winner, u32)> { let mut seen_decks: HashSet<(u32, u32)> = HashSet::new(); let mut round: u32 = 1; let (winner, mut winner_deck) = loop { let seen = seen_decks.insert(( p1_deck .iter() .rev() .copied() .zip(1..) .map(|(a, b)| a * b) .sum(), p2_deck .iter() .rev() .copied() .zip(1..) .map(|(a, b)| a * b) .sum(), )); if !seen { break (Winner::Player1, p1_deck); } round += 1; if p1_deck.is_empty() { break (Winner::Player2, p2_deck); } else if p2_deck.is_empty() { break (Winner::Player1, p1_deck); } else if round == 20_000 { panic!("Maybe infinite loop?") } let p1_card = p1_deck.pop_front().unwrap(); let p2_card = p2_deck.pop_front().unwrap(); let winner = if p1_card as usize <= p1_
#[cfg(test)] mod tests_2022 { use aoc_lib::Example; use super::*; #[test] fn part1_example() { let input = aoc_lib::input(2020, 22) .example(Example::Part1, 1) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); let expected = 306; let actual = play_part1(player1, player2).unwrap(); assert_eq!(expected, actual); } #[test] fn part2_example_infinite_loop_test() { let input = aoc_lib::input(2020, 22) .example(Example::Part2, 1) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); play_part2(player1, player2).unwrap(); } #[test] fn part2_example2() { let input = aoc_lib::input(2020, 22) .example(Example::Part2, 2) .open() .unwrap(); let (player1, player2) = parse_input(&input).unwrap(); let expected = (Winner::Player2, 291); let actual = play_part2(player1, player2).unwrap(); assert_eq!(expected, actual); } }
deck.len() && p2_card as usize <= p2_deck.len() { let p1_new_deck = p1_deck.iter().copied().take(p1_card as usize).collect(); let p2_new_deck = p2_deck.iter().copied().take(p2_card as usize).collect(); play_part2(p1_new_deck, p2_new_deck)?.0 } else if p1_card >= p2_card { Winner::Player1 } else { Winner::Player2 }; if winner == Winner::Player1 { p1_deck.push_back(p1_card); p1_deck.push_back(p2_card); } else { p2_deck.push_back(p2_card); p2_deck.push_back(p1_card); } }; let score = winner_deck .drain(..) .rev() .zip(1..) .map(|(mul, card)| mul * card) .sum(); Ok((winner, score)) }
function_block-function_prefixed
[ { "content": "fn run_part2(input: &str, b: Bench) -> BenchResult {\n\n let floor = WaitingArea::parse(input).map_err(UserError)?;\n\n\n\n b.bench(|| {\n\n let mut floor = floor.clone();\n\n floor.run(WaitingArea::count_neighbours_part2, 5);\n\n Ok::<_, NoError>(floor.occupied_seats())...
Rust
src/day_7.rs
jacobguenther/advent_of_code_2020
c1e4ea46e106b9845b9a30ec9240c7527ec5fd11
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use super::common::ChallengeT; pub struct Challenge { parsed_input: HashMap<&'static str, Vec<(&'static str, u32)>>, } impl ChallengeT for Challenge { type Output1 = u32; type Output2 = u32; fn day() -> u8 { 7 } fn new() -> Self { let parsed_input = include_str!("../inputs/day_7.txt") .lines() .map(|line| parse_line(line)) .collect::<HashMap<&str, Vec<(&str, u32)>>>(); Self { parsed_input } } fn part_1(&self) -> Self::Output1 { let mut bags_that_contain_gold_bag = 0; let mut cache = HashMap::new(); for (bag, _) in self.parsed_input.clone() { if contains_gold(&bag, &self.parsed_input, &mut cache) { bags_that_contain_gold_bag += 1; } } bags_that_contain_gold_bag } fn part_2(&self) -> Self::Output2 { count_bags_in("shiny gold", &self.parsed_input) } } fn parse_line(line: &str) -> (&str, Vec<(&str, u32)>) { let mut iter = line.split(" bags "); let color = iter.next().unwrap(); let rest = iter.next().unwrap(); let mut rules = Vec::new(); if !rest.starts_with("contain no") { for rule in rest[8..].split(", ") { let mut numbers_digits = 0; for c in rule.chars() { if c.is_ascii_digit() { numbers_digits += 1; } else { break; } } let bag_count = rule[..(numbers_digits)].parse::<u32>().unwrap(); let rule_color = if rule.ends_with('.') { rule[(numbers_digits + 1)..(rule.len() - 5)] .trim() } else { rule[(numbers_digits + 1)..(rule.len() - 4)] .trim() }; rules.push((rule_color, bag_count)); } } (color, rules) } fn contains_gold( current: &str, bags: &HashMap<&'static str, Vec<(&'static str, u32)>>, cache: &mut HashMap<&str, bool>, ) -> bool { if let Some(val) = cache.get(current) { return *val; } let current_info = bags.get(current).unwrap(); let current_contains_gold = current_info.iter().any(|(name, _)| *name == "shiny gold"); if current_contains_gold { true } else { for (bag, _) in current_info { if contains_gold(*bag, bags, cache) { cache.insert(*bag, true); return true; } else { cache.insert(*bag, false); } } false } } fn count_bags_in(current: &str, bags: &HashMap<&str, Vec<(&str, u32)>>) -> u32 { let mut count = 0; for (bag_color, bags_in_bag) in bags.get(current).unwrap() { count += bags_in_bag + bags_in_bag * count_bags_in(&bag_color, bags); } count } #[cfg(test)] mod tests { use super::Challenge; use crate::common::ChallengeT; use test::Bencher; #[test] fn part_1_test() { assert_eq!(Challenge::new().part_1(), 151); } #[test] fn part_2_test() { assert_eq!(Challenge::new().part_2(), 41559); } #[bench] fn part_1_bench(b: &mut Bencher) { b.iter(|| Challenge::new().part_1()) } #[bench] fn part_2_bench(b: &mut Bencher) { b.iter(|| Challenge::new().part_2()) } #[bench] fn both(b: &mut Bencher) { b.iter(|| { let challenge = Challenge::new(); challenge.part_1(); challenge.part_2(); }) } }
/* Copyright 2020 Jacob Guenther Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use std::collections::HashMap; use super::common::ChallengeT; pub struct Challenge { parsed_input: HashMap<&'static str, Vec<(&'static str, u32)>>, } impl ChallengeT for Challenge { type Output1 = u32; type Output2 = u32; fn day() -> u8 { 7 } fn new() -> Self { let parsed_input = include_str!("../inputs/day_7.txt") .lines() .map(|line| parse_line(line)) .collect::<HashMap<&str, Vec<(&str, u32)>>>(); Self { parsed_input } } fn part_1(&self) -> Self::Output1 { let mut bags_that_contain_gold_bag = 0; let mut cache = HashMap::new(); for (bag, _) in self.parsed_input.clone() { if contains_gold(&bag, &self.parsed_input, &mut cache) { bags_that_contain_gold_bag += 1; } } bags_that_contain_gold_bag } fn part_2(&self) -> Self::Output2 { count_bags_in("shiny gold", &self.parsed_input) } } fn parse_line(line: &str) -> (&str, Vec<(&str, u32)>) { let mut iter = line.split(" bags "); let color = iter.next().unwrap(); let rest = iter.next().unwrap(); let mut rules = Vec::new(); if !rest.starts_with("contain no") { for rule in rest[8..].split(", ") { let mut numbers_digits = 0; for c in rule.chars() { if c.is_ascii_digit() { numbers_digits += 1; } else { break; } } let bag_count = rule[..(numbers_digits)].parse::<u32>().unwrap(); let rule_color = if rule.ends_with('.') { rule[(numbers_digits + 1)..(rule.len() - 5)] .trim() } else { rule[(numbers_digits + 1)..(rule.len() - 4)] .trim() }; rules.push((rule_color, bag_count)); } } (color, rules) } fn contains_gold( current: &str, bags: &HashMap<&'static str, Vec<(&'static str, u32)>>, cache: &mut HashMap<&str, bool>, ) -> bool { if let Some(val) = cache.get(current) { return *val; } let current_info = bags.get(current).unwrap(); let current_contains_gold = current_info.iter().any(|(name, _)| *nam
fn count_bags_in(current: &str, bags: &HashMap<&str, Vec<(&str, u32)>>) -> u32 { let mut count = 0; for (bag_color, bags_in_bag) in bags.get(current).unwrap() { count += bags_in_bag + bags_in_bag * count_bags_in(&bag_color, bags); } count } #[cfg(test)] mod tests { use super::Challenge; use crate::common::ChallengeT; use test::Bencher; #[test] fn part_1_test() { assert_eq!(Challenge::new().part_1(), 151); } #[test] fn part_2_test() { assert_eq!(Challenge::new().part_2(), 41559); } #[bench] fn part_1_bench(b: &mut Bencher) { b.iter(|| Challenge::new().part_1()) } #[bench] fn part_2_bench(b: &mut Bencher) { b.iter(|| Challenge::new().part_2()) } #[bench] fn both(b: &mut Bencher) { b.iter(|| { let challenge = Challenge::new(); challenge.part_1(); challenge.part_2(); }) } }
e == "shiny gold"); if current_contains_gold { true } else { for (bag, _) in current_info { if contains_gold(*bag, bags, cache) { cache.insert(*bag, true); return true; } else { cache.insert(*bag, false); } } false } }
function_block-function_prefixed
[ { "content": "fn parse_line(line: &str) -> (u16, u16, u8, &str) {\n\n\tlet mut min: u16 = 0;\n\n\tlet mut max: u16 = 0;\n\n\tlet mut letter = b' ';\n\n\tlet mut password = \"\";\n\n\tline.split(&['-', ' '][..])\n\n\t\t.enumerate()\n\n\t\t.for_each(|(i, s)| match i {\n\n\t\t\t0 => min = s.parse().unwrap(),\n\n\t...
Rust
crates/stun-types/src/parse.rs
kbalt/ezk
6886981a5d13954fb8536cf69d83b147551fd55c
use crate::attributes::{Attribute, Fingerprint, MessageIntegrity, MessageIntegritySha256}; use crate::header::{Class, MessageHead, MessageId, Method}; use crate::{padding_usize, Error, COOKIE, NE}; use byteorder::ReadBytesExt; use bytes::Buf; use std::convert::TryFrom; use std::io::Cursor; #[derive(Debug, Clone, Copy)] pub struct ParsedAttr { pub begin: usize, pub end: usize, pub padding_end: usize, pub typ: u16, } impl ParsedAttr { pub fn get_value<'b>(&self, buf: &'b [u8]) -> &'b [u8] { &buf[self.begin..self.end] } } pub struct ParsedMessage { buffer: Vec<u8>, head: MessageHead, id: MessageId, pub class: Class, pub method: Method, pub tsx_id: u128, pub attributes: Vec<ParsedAttr>, } impl ParsedMessage { pub fn parse(buffer: Vec<u8>) -> Result<ParsedMessage, Error> { let mut cursor = Cursor::new(buffer); let head = cursor.read_u32::<NE>()?; let head = MessageHead(head); if head.z() != 0 { return Err(Error::InvalidData("not a stun message")); } let id = cursor.read_u128::<NE>()?; let id = MessageId(id); if id.cookie() != COOKIE { return Err(Error::InvalidData("not a stun message")); } let class = Class::try_from(head.typ())?; let method = Method::try_from(head.typ())?; let mut attributes = vec![]; while cursor.has_remaining() { let attr_typ = cursor.read_u16::<NE>()?; let attr_len = usize::from(cursor.read_u16::<NE>()?); let padding = padding_usize(attr_len); let value_begin = usize::try_from(cursor.position())?; let mut value_end = value_begin + attr_len; let padding_end = value_end + padding; if padding_end > cursor.get_ref().len() { return Err(Error::InvalidData( "Invalid attribute length in STUN message", )); } if padding == 0 { let value = &cursor.get_ref()[value_begin..value_end]; let counted_padding = value.iter().rev().take_while(|&&b| b == 0).count(); value_end -= counted_padding; } let attr = ParsedAttr { begin: value_begin, end: value_end, padding_end, typ: attr_typ, }; attributes.push(attr); cursor.set_position(u64::try_from(padding_end)?); } let tsx_id = id.tsx_id(); Ok(ParsedMessage { buffer: cursor.into_inner(), head, id, class, method, tsx_id, attributes, }) } pub fn get_attr<'a, A>(&'a mut self) -> Option<Result<A, Error>> where A: Attribute<'a, Context = ()> + 'a, { self.get_attr_with(()) } pub fn get_attr_with<'a, A>(&'a mut self, ctx: A::Context) -> Option<Result<A, Error>> where A: Attribute<'a> + 'a, { let mut after_integrity = false; for attr in self.attributes.iter().copied() { if after_integrity && !matches!(attr.typ, MessageIntegritySha256::TYPE | Fingerprint::TYPE) { return None; } if attr.typ == A::TYPE { return Some(A::decode(ctx, self, attr)); } else if matches!( attr.typ, MessageIntegrity::TYPE | MessageIntegritySha256::TYPE ) { after_integrity = true; } } None } fn set_msg_len(&mut self, len: u16) { self.head.set_len(len); let [b0, b1, b2, b3] = u32::to_ne_bytes(self.head.0); self.buffer[0] = b3; self.buffer[1] = b2; self.buffer[2] = b1; self.buffer[3] = b0; } pub fn with_msg_len<F, R>(&mut self, len: u16, f: F) -> R where F: FnOnce(&mut Self) -> R, { let old_len = self.head.len(); self.set_msg_len(len); let result = f(self); self.set_msg_len(old_len); result } pub fn buffer(&self) -> &[u8] { &self.buffer } pub fn head(&self) -> &MessageHead { &self.head } pub fn id(&self) -> &MessageId { &self.id } }
use crate::attributes::{Attribute, Fingerprint, MessageIntegrity, MessageIntegritySha256}; use crate::header::{Class, MessageHead, MessageId, Method}; use crate::{padding_usize, Error, COOKIE, NE}; use byteorder::ReadBytesExt; use bytes::Buf; use std::convert::TryFrom; use std::io::Cursor; #[derive(Debug, Clone, Copy)] pub struct ParsedAttr { pub begin: usize, pub end: usize, pub padding_end: usize, pub typ: u16, } impl ParsedAttr { pub fn get_value<'b>(&self, buf: &'b [u8]) -> &'b [u8] { &buf[self.begin..self.end] } } pub struct ParsedMessage { buffer: Vec<u8>, head: MessageHead, id: MessageId, pub class: Class, pub method: Method, pub tsx_id: u128, pub attributes: Vec<ParsedAttr>, } impl ParsedMessage { pub fn parse(buffer: Vec<u8>) -> Result<ParsedMessage, Error> { let mut cursor = Cursor::new(buffer); let head = cursor.read_u32::<NE>()?; let head = MessageHead(head); if head.z() != 0 { return Err(Error::InvalidData("not a stun message")); } let id = cursor.read_u128::<NE>()?; let id = MessageId(id); if id.cookie() != COOKIE { return Err(Error::InvalidData("not a stun message")); } let class = Class::try_from(head.typ())?; let method = Method::try_from(head.typ())?; let mut attributes = vec![]; while cursor.has_remaining() { let attr_typ = cursor.read_u16::<NE>()?; let attr_len = usize::from(cursor.read_u16::<NE>()?); let padding = padding_usize(attr_len); let value_begin = usize::try_from(cursor.position())?; let mut value_end = value_begin + attr_len; let padding_end = value_end + padding; if padding_end > cursor.get_ref().len() { return Err(Error::InvalidData( "Invalid attribute length in STUN message", )); } if padding == 0 { let value = &cursor.get_ref()[value_begin..value_end]; let counted_padding = value.iter().rev().take_while(|&&b| b == 0).count(); value_end -= counted_padding; } let attr = ParsedAttr { begin: value_begin, end: value_end, padding_end, typ: attr_typ, }; attributes.push(attr); cursor.set_position(u64::try_from(padding_end)?); } let tsx_id = id.tsx_id(); Ok(ParsedMessage { buffer: cursor.into_inner(), head, id, class, method, tsx_id, attributes, }) } pub fn get_attr<'a, A>(&'a mut self) -> Option<Result<A, Error>> where A: Attribute<'a, Context = ()> + 'a, { self.get_attr_with(()) } pub fn get_attr_with<'a, A>(&'a mut self, ctx: A::Context) -> Option<Result<A, Error>> where A: Attribute<'a> + 'a, { let mut after_integrity = false; for attr in self.attributes.iter().copied() { if after_integrity && !matches!(attr.typ, MessageIntegrityS
fn set_msg_len(&mut self, len: u16) { self.head.set_len(len); let [b0, b1, b2, b3] = u32::to_ne_bytes(self.head.0); self.buffer[0] = b3; self.buffer[1] = b2; self.buffer[2] = b1; self.buffer[3] = b0; } pub fn with_msg_len<F, R>(&mut self, len: u16, f: F) -> R where F: FnOnce(&mut Self) -> R, { let old_len = self.head.len(); self.set_msg_len(len); let result = f(self); self.set_msg_len(old_len); result } pub fn buffer(&self) -> &[u8] { &self.buffer } pub fn head(&self) -> &MessageHead { &self.head } pub fn id(&self) -> &MessageId { &self.id } }
ha256::TYPE | Fingerprint::TYPE) { return None; } if attr.typ == A::TYPE { return Some(A::decode(ctx, self, attr)); } else if matches!( attr.typ, MessageIntegrity::TYPE | MessageIntegritySha256::TYPE ) { after_integrity = true; } } None }
function_block-function_prefixed
[ { "content": "fn encode_addr(addr: SocketAddr, buf: &mut Vec<u8>, xor16: u16, xor32: u32, xor128: u128) {\n\n buf.put_u8(0);\n\n\n\n match addr {\n\n SocketAddr::V4(addr) => {\n\n buf.put_u8(1);\n\n buf.put_u16(addr.port() ^ xor16);\n\n\n\n let ip = u32::from_ne_byt...
Rust
src/components/axis.rs
HaKr/rustplotlib
09d907976a5930b44ba2cc9cc941500c088d765c
use svg::node::element::{Group, Line}; use svg::node::Text as TextNode; use svg::node::element::Text; use svg::Node; use format_num::NumberFormat; use crate::axis::AxisPosition; pub(crate) struct AxisLine { x1: f32, y1: f32, x2: f32, y2: f32, } impl AxisLine { pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self { Self { x1, y1, x2, y2 } } pub fn to_svg(&self) -> Result<Line, String> { let line = Line::new() .set("x1", self.x1) .set("y1", self.y1) .set("x2", self.x2) .set("y2", self.y2) .set("shape-rendering", "crispEdges") .set("stroke-width", 1) .set("stroke", "#bbbbbb"); Ok(line) } } pub struct AxisTick { axis_position: AxisPosition, label_offset: usize, label_rotation: isize, tick_offset: f32, label: String, label_format: Option<String> } impl AxisTick { pub fn new(tick_offset: f32, label_offset: usize, label_rotation: isize, label: String, axis_position: AxisPosition) -> Self { Self { label_offset, tick_offset, label_rotation, label, axis_position, label_format: None, } } pub fn set_label_rotation(&mut self, rotation: isize) { self.label_rotation = rotation; } pub fn set_label_format(&mut self, format: &str) { self.label_format = Some(format.to_owned()); } pub fn to_svg(&self) -> Result<Group, String> { let formatted_label = if self.label_format.is_some() { let formatter = NumberFormat::new(); formatter.format(self.label_format.as_ref().unwrap(), self.label.parse::<f64>().unwrap()).replace('G', "B") } else { self.label.to_owned() }; let offsets: (f32, f32); let tick_line_p2: (isize, isize); let tick_label_offset: (isize, isize); let tick_label_text_anchor: &str; match self.axis_position { AxisPosition::Left => { offsets = (0_f32, self.tick_offset); tick_line_p2 = (-6, 0); tick_label_offset = (-(self.label_offset as isize), 0); tick_label_text_anchor = "end"; }, AxisPosition::Bottom => { offsets = (self.tick_offset, 0_f32); tick_line_p2 = (0, 6); tick_label_offset = (0, self.label_offset as isize); tick_label_text_anchor = "middle"; }, AxisPosition::Right => { offsets = (0_f32, self.tick_offset); tick_line_p2 = (6, 0); tick_label_offset = (self.label_offset as isize, 0); tick_label_text_anchor = "start"; }, AxisPosition::Top => { offsets = (self.tick_offset, 0_f32); tick_line_p2 = (0, -6); tick_label_offset = (0, -(self.label_offset as isize)); tick_label_text_anchor = "middle"; }, }; let mut group = Group::new() .set("class", "tick") .set("transform", format!("translate({},{})", offsets.0, offsets.1)); let tick_line = Line::new() .set("x1", 0) .set("y1", 0) .set("x2", tick_line_p2.0) .set("y2", tick_line_p2.1) .set("shape-rendering", "crispEdges") .set("stroke", "#bbbbbb") .set("stroke-width", "1px"); let tick_label = Text::new() .set("transform", format!("rotate({},{},{})", self.label_rotation, tick_label_offset.0, tick_label_offset.1)) .set("x", tick_label_offset.0) .set("y", tick_label_offset.1) .set("dy", ".35em") .set("text-anchor", tick_label_text_anchor) .set("font-size", "12px") .set("font-family", "sans-serif") .set("fill", "#777") .add(TextNode::new(formatted_label)); group.append(tick_line); group.append(tick_label); Ok(group) } }
use svg::node::element::{Group, Line}; use svg::node::Text as TextNode; use svg::node::element::Text; use svg::Node; use format_num::NumberFormat; use crate::axis::AxisPosition; pub(crate) struct AxisLine { x1: f32, y1: f32, x2: f32, y2: f32, } impl AxisLine { pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Self { Self { x1, y1, x2, y2 } }
} pub struct AxisTick { axis_position: AxisPosition, label_offset: usize, label_rotation: isize, tick_offset: f32, label: String, label_format: Option<String> } impl AxisTick { pub fn new(tick_offset: f32, label_offset: usize, label_rotation: isize, label: String, axis_position: AxisPosition) -> Self { Self { label_offset, tick_offset, label_rotation, label, axis_position, label_format: None, } } pub fn set_label_rotation(&mut self, rotation: isize) { self.label_rotation = rotation; } pub fn set_label_format(&mut self, format: &str) { self.label_format = Some(format.to_owned()); } pub fn to_svg(&self) -> Result<Group, String> { let formatted_label = if self.label_format.is_some() { let formatter = NumberFormat::new(); formatter.format(self.label_format.as_ref().unwrap(), self.label.parse::<f64>().unwrap()).replace('G', "B") } else { self.label.to_owned() }; let offsets: (f32, f32); let tick_line_p2: (isize, isize); let tick_label_offset: (isize, isize); let tick_label_text_anchor: &str; match self.axis_position { AxisPosition::Left => { offsets = (0_f32, self.tick_offset); tick_line_p2 = (-6, 0); tick_label_offset = (-(self.label_offset as isize), 0); tick_label_text_anchor = "end"; }, AxisPosition::Bottom => { offsets = (self.tick_offset, 0_f32); tick_line_p2 = (0, 6); tick_label_offset = (0, self.label_offset as isize); tick_label_text_anchor = "middle"; }, AxisPosition::Right => { offsets = (0_f32, self.tick_offset); tick_line_p2 = (6, 0); tick_label_offset = (self.label_offset as isize, 0); tick_label_text_anchor = "start"; }, AxisPosition::Top => { offsets = (self.tick_offset, 0_f32); tick_line_p2 = (0, -6); tick_label_offset = (0, -(self.label_offset as isize)); tick_label_text_anchor = "middle"; }, }; let mut group = Group::new() .set("class", "tick") .set("transform", format!("translate({},{})", offsets.0, offsets.1)); let tick_line = Line::new() .set("x1", 0) .set("y1", 0) .set("x2", tick_line_p2.0) .set("y2", tick_line_p2.1) .set("shape-rendering", "crispEdges") .set("stroke", "#bbbbbb") .set("stroke-width", "1px"); let tick_label = Text::new() .set("transform", format!("rotate({},{},{})", self.label_rotation, tick_label_offset.0, tick_label_offset.1)) .set("x", tick_label_offset.0) .set("y", tick_label_offset.1) .set("dy", ".35em") .set("text-anchor", tick_label_text_anchor) .set("font-size", "12px") .set("font-family", "sans-serif") .set("fill", "#777") .add(TextNode::new(formatted_label)); group.append(tick_line); group.append(tick_label); Ok(group) } }
pub fn to_svg(&self) -> Result<Line, String> { let line = Line::new() .set("x1", self.x1) .set("y1", self.y1) .set("x2", self.x2) .set("y2", self.y2) .set("shape-rendering", "crispEdges") .set("stroke-width", 1) .set("stroke", "#bbbbbb"); Ok(line) }
function_block-full_function
[ { "content": "#[derive(Default)]\n\nstruct BarLabel {\n\n key: usize,\n\n label: String,\n\n}\n\n\n\nimpl From<usize> for BarLabel {\n\n fn from(key: usize) -> Self {\n\n BarLabel {\n\n key,\n\n label: format!(\"{}\", key),\n\n }\n\n }\n\n}\n\n\n\nimpl<D: Display>...
Rust
src/simples3/s3.rs
kingli-crypto/sccache
549cfd405b8bc23a128ccb2a0e9df1b3c13a092b
#[allow(unused_imports, deprecated)] use std::ascii::AsciiExt; use std::fmt; use crate::simples3::credential::*; use futures::{Future, Stream}; use hmac::{Hmac, Mac, NewMac}; use hyper::header::HeaderValue; use hyper::Method; use hyperx::header; use reqwest::r#async::{Client, Request}; use sha1::Sha1; use crate::errors::*; use crate::util::{DateTimeExt, HeadersExt}; #[derive(Debug, Copy, Clone)] #[allow(dead_code)] pub enum Ssl { Yes, No, } fn base_url(endpoint: &str, ssl: Ssl) -> String { format!( "{}://{}/", match ssl { Ssl::Yes => "https", Ssl::No => "http", }, endpoint ) } fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha1>::new_varkey(key).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().to_vec() } fn signature(string_to_sign: &str, signing_key: &str) -> String { let s = hmac(signing_key.as_bytes(), string_to_sign.as_bytes()); base64::encode_config(&s, base64::STANDARD) } pub struct Bucket { name: String, base_url: String, client: Client, } impl fmt::Display for Bucket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Bucket(name={}, base_url={})", self.name, self.base_url) } } impl Bucket { pub fn new(name: &str, endpoint: &str, ssl: Ssl) -> Result<Bucket> { let base_url = base_url(endpoint, ssl); Ok(Bucket { name: name.to_owned(), base_url, client: Client::new(), }) } pub fn get(&self, key: &str, creds: Option<&AwsCredentials>) -> SFuture<Vec<u8>> { let url = format!("{}{}", self.base_url, key); debug!("GET {}", url); let url2 = url.clone(); let mut request = Request::new(Method::GET, url.parse().unwrap()); if let Some(creds) = creds { let mut canonical_headers = String::new(); if let Some(token) = creds.token().as_ref().map(|s| s.as_str()) { request.headers_mut().insert( "x-amz-security-token", HeaderValue::from_str(token).expect("Invalid `x-amz-security-token` header"), ); canonical_headers .push_str(format!("{}:{}\n", "x-amz-security-token", token).as_ref()); } let date = chrono::offset::Utc::now().to_rfc7231(); let auth = self.auth("GET", &date, key, "", &canonical_headers, "", creds); request.headers_mut().insert( "Date", HeaderValue::from_str(&date).expect("Invalid date header"), ); request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid authentication"), ); } Box::new( self.client .execute(request) .fwith_context(move || format!("failed GET: {}", url)) .and_then(|res| { if res.status().is_success() { let content_length = res .headers() .get_hyperx::<header::ContentLength>() .map(|header::ContentLength(len)| len); Ok((res.into_body(), content_length)) } else { Err(BadHttpStatusError(res.status()).into()) } }) .and_then(|(body, content_length)| { body.fold(Vec::new(), |mut body, chunk| { body.extend_from_slice(&chunk); Ok::<_, reqwest::Error>(body) }) .fcontext("failed to read HTTP body") .and_then(move |bytes| { if let Some(len) = content_length { if len != bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), url2); } } Ok(bytes) }) }), ) } pub fn put(&self, key: &str, content: Vec<u8>, creds: &AwsCredentials) -> SFuture<()> { let url = format!("{}{}", self.base_url, key); debug!("PUT {}", url); let mut request = Request::new(Method::PUT, url.parse().unwrap()); let content_type = "application/octet-stream"; let date = chrono::offset::Utc::now().to_rfc7231(); let mut canonical_headers = String::new(); let token = creds.token().as_ref().map(|s| s.as_str()); for (header, maybe_value) in &[("x-amz-security-token", token)] { if let Some(ref value) = maybe_value { request.headers_mut().insert( *header, HeaderValue::from_str(value) .unwrap_or_else(|_| panic!("Invalid `{}` header", header)), ); canonical_headers .push_str(format!("{}:{}\n", header.to_ascii_lowercase(), value).as_ref()); } } let auth = self.auth( "PUT", &date, key, "", &canonical_headers, content_type, creds, ); request.headers_mut().insert( "Date", HeaderValue::from_str(&date).expect("Invalid date header"), ); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request.headers_mut().set(header::CacheControl(vec![ header::CacheDirective::MaxAge(1_296_000), ])); request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid authentication"), ); *request.body_mut() = Some(content.into()); Box::new(self.client.execute(request).then(|result| match result { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } })) } #[allow(clippy::too_many_arguments)] fn auth( &self, verb: &str, date: &str, path: &str, md5: &str, headers: &str, content_type: &str, creds: &AwsCredentials, ) -> String { let string = format!( "{verb}\n{md5}\n{ty}\n{date}\n{headers}{resource}", verb = verb, md5 = md5, ty = content_type, date = date, headers = headers, resource = format!("/{}/{}", self.name, path) ); let signature = signature(&string, creds.aws_secret_access_key()); format!("AWS {}:{}", creds.aws_access_key_id(), signature) } } #[cfg(test)] mod test { use super::*; #[test] fn test_signature() { assert_eq!( signature("/foo/bar\nbar", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"), "mwbstmHPMEJjTe2ksXi5H5f0c8U=" ); assert_eq!( signature("/bar/foo\nbaz", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"), "F9gZMso3+P+QTEyRKQ6qhZ1YM6o=" ); } }
#[allow(unused_imports, deprecated)] use std::ascii::AsciiExt; use std::fmt; use crate::simples3::credential::*; use futures::{Future, Stream}; use hmac::{Hmac, Mac, NewMac}; use hyper::header::HeaderValue; use hyper::Method; use hyperx::header; use reqwest::r#async::{Client, Request}; use sha1::Sha1; use crate::errors::*; use crate::util::{DateTimeExt, HeadersExt}; #[derive(Debug, Copy, Clone)] #[allow(dead_code)] pub enum Ssl { Yes, No, } fn base_url(endpoint: &str, ssl: Ssl) -> String { format!( "{}://{}/", match ssl { Ssl::Yes => "https", Ssl::No => "http", }, endpoint ) } fn hmac(key: &[u8], data: &[u8]) -> Vec<u8> { let mut hmac = Hmac::<Sha1>::new_varkey(key).expect("HMAC can take key of any size"); hmac.update(data); hmac.finalize().into_bytes().as_slice().t
now().to_rfc7231(); let auth = self.auth("GET", &date, key, "", &canonical_headers, "", creds); request.headers_mut().insert( "Date", HeaderValue::from_str(&date).expect("Invalid date header"), ); request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid authentication"), ); } Box::new( self.client .execute(request) .fwith_context(move || format!("failed GET: {}", url)) .and_then(|res| { if res.status().is_success() { let content_length = res .headers() .get_hyperx::<header::ContentLength>() .map(|header::ContentLength(len)| len); Ok((res.into_body(), content_length)) } else { Err(BadHttpStatusError(res.status()).into()) } }) .and_then(|(body, content_length)| { body.fold(Vec::new(), |mut body, chunk| { body.extend_from_slice(&chunk); Ok::<_, reqwest::Error>(body) }) .fcontext("failed to read HTTP body") .and_then(move |bytes| { if let Some(len) = content_length { if len != bytes.len() as u64 { bail!(format!( "Bad HTTP body size read: {}, expected {}", bytes.len(), len )); } else { info!("Read {} bytes from {}", bytes.len(), url2); } } Ok(bytes) }) }), ) } pub fn put(&self, key: &str, content: Vec<u8>, creds: &AwsCredentials) -> SFuture<()> { let url = format!("{}{}", self.base_url, key); debug!("PUT {}", url); let mut request = Request::new(Method::PUT, url.parse().unwrap()); let content_type = "application/octet-stream"; let date = chrono::offset::Utc::now().to_rfc7231(); let mut canonical_headers = String::new(); let token = creds.token().as_ref().map(|s| s.as_str()); for (header, maybe_value) in &[("x-amz-security-token", token)] { if let Some(ref value) = maybe_value { request.headers_mut().insert( *header, HeaderValue::from_str(value) .unwrap_or_else(|_| panic!("Invalid `{}` header", header)), ); canonical_headers .push_str(format!("{}:{}\n", header.to_ascii_lowercase(), value).as_ref()); } } let auth = self.auth( "PUT", &date, key, "", &canonical_headers, content_type, creds, ); request.headers_mut().insert( "Date", HeaderValue::from_str(&date).expect("Invalid date header"), ); request .headers_mut() .set(header::ContentType(content_type.parse().unwrap())); request .headers_mut() .set(header::ContentLength(content.len() as u64)); request.headers_mut().set(header::CacheControl(vec![ header::CacheDirective::MaxAge(1_296_000), ])); request.headers_mut().insert( "Authorization", HeaderValue::from_str(&auth).expect("Invalid authentication"), ); *request.body_mut() = Some(content.into()); Box::new(self.client.execute(request).then(|result| match result { Ok(res) => { if res.status().is_success() { trace!("PUT succeeded"); Ok(()) } else { trace!("PUT failed with HTTP status: {}", res.status()); Err(BadHttpStatusError(res.status()).into()) } } Err(e) => { trace!("PUT failed with error: {:?}", e); Err(e.into()) } })) } #[allow(clippy::too_many_arguments)] fn auth( &self, verb: &str, date: &str, path: &str, md5: &str, headers: &str, content_type: &str, creds: &AwsCredentials, ) -> String { let string = format!( "{verb}\n{md5}\n{ty}\n{date}\n{headers}{resource}", verb = verb, md5 = md5, ty = content_type, date = date, headers = headers, resource = format!("/{}/{}", self.name, path) ); let signature = signature(&string, creds.aws_secret_access_key()); format!("AWS {}:{}", creds.aws_access_key_id(), signature) } } #[cfg(test)] mod test { use super::*; #[test] fn test_signature() { assert_eq!( signature("/foo/bar\nbar", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"), "mwbstmHPMEJjTe2ksXi5H5f0c8U=" ); assert_eq!( signature("/bar/foo\nbaz", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"), "F9gZMso3+P+QTEyRKQ6qhZ1YM6o=" ); } }
o_vec() } fn signature(string_to_sign: &str, signing_key: &str) -> String { let s = hmac(signing_key.as_bytes(), string_to_sign.as_bytes()); base64::encode_config(&s, base64::STANDARD) } pub struct Bucket { name: String, base_url: String, client: Client, } impl fmt::Display for Bucket { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Bucket(name={}, base_url={})", self.name, self.base_url) } } impl Bucket { pub fn new(name: &str, endpoint: &str, ssl: Ssl) -> Result<Bucket> { let base_url = base_url(endpoint, ssl); Ok(Bucket { name: name.to_owned(), base_url, client: Client::new(), }) } pub fn get(&self, key: &str, creds: Option<&AwsCredentials>) -> SFuture<Vec<u8>> { let url = format!("{}{}", self.base_url, key); debug!("GET {}", url); let url2 = url.clone(); let mut request = Request::new(Method::GET, url.parse().unwrap()); if let Some(creds) = creds { let mut canonical_headers = String::new(); if let Some(token) = creds.token().as_ref().map(|s| s.as_str()) { request.headers_mut().insert( "x-amz-security-token", HeaderValue::from_str(token).expect("Invalid `x-amz-security-token` header"), ); canonical_headers .push_str(format!("{}:{}\n", "x-amz-security-token", token).as_ref()); } let date = chrono::offset::Utc::
random
[ { "content": "fn hmac(data: &[u8], secret: &[u8]) -> Vec<u8> {\n\n let mut hmac = Hmac::<Sha256>::new_varkey(secret).expect(\"HMAC can take key of any size\");\n\n hmac.update(data);\n\n hmac.finalize().into_bytes().as_slice().to_vec()\n\n}\n\n\n", "file_path": "src/azure/blobstore.rs", "rank":...
Rust
src/client.rs
jakalope/vixi
b0f39dc92c3eca21ccac17e1b54050569f72575e
use xrl; use xrl::{ClientResult, ViewId}; use serde_json::Value; use futures::future::ok; pub trait Client { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()>; fn request(&mut self, method: &str, params: Value) -> ClientResult<Value>; fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()>; fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()>; fn left(&mut self, view_id: ViewId) -> ClientResult<()>; fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn right(&mut self, view_id: ViewId) -> ClientResult<()>; fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn up(&mut self, view_id: ViewId) -> ClientResult<()>; fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn down(&mut self, view_id: ViewId) -> ClientResult<()>; fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn delete(&mut self, view_id: ViewId) -> ClientResult<()>; fn backspace(&mut self, view_id: ViewId) -> ClientResult<()>; fn del(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_up(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_down(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_start(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_end(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()>; fn f1(&mut self, view_id: ViewId) -> ClientResult<()>; fn f2(&mut self, view_id: ViewId) -> ClientResult<()>; fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()>; fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()>; fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()>; fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId>; fn close_view(&mut self, view_id: ViewId) -> ClientResult<()>; fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()>; fn set_theme(&mut self, theme: &str) -> ClientResult<()>; fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()>; fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()>; fn notify_plugin( &mut self, view_id: ViewId, plugin: &str, method: &str, params: Value, ) -> ClientResult<()>; } #[derive(Clone)] pub struct XrlClient { client: xrl::Client, } impl XrlClient { pub fn new(client: xrl::Client) -> Self { XrlClient { client: client } } } impl Client for XrlClient { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()> { self.client.notify(method, params) } fn request(&mut self, method: &str, params: Value) -> ClientResult<Value> { self.client.request(method, params) } fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()> { self.client.edit(view_id, method, params) } fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()> { self.client.scroll(view_id, first_line, last_line) } fn left(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.left(view_id) } fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.left_sel(view_id) } fn right(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.right(view_id) } fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.right_sel(view_id) } fn up(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.up(view_id) } fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.up_sel(view_id) } fn down(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.down(view_id) } fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.down_sel(view_id) } fn delete(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.delete(view_id) } fn backspace(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.backspace(view_id) } fn del(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.del(view_id) } fn page_up(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_up(view_id) } fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_up_sel(view_id) } fn page_down(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_down(view_id) } fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_down_sel(view_id) } fn line_start(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_start(view_id) } fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_start_sel(view_id) } fn line_end(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_end(view_id) } fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_end_sel(view_id) } fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.insert_newline(view_id) } fn f1(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.f1(view_id) } fn f2(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.f2(view_id) } fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()> { self.client.char(view_id, ch) } fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { self.client.click(view_id, line, column) } fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { self.client.drag(view_id, line, column) } fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId> { self.client.new_view(file_path) } fn close_view(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.close_view(view_id) } fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()> { self.client.save(view_id, file_path) } fn set_theme(&mut self, theme: &str) -> ClientResult<()> { self.client.set_theme(theme) } fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { self.client.start_plugin(view_id, name) } fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { self.client.stop_plugin(view_id, name) } fn notify_plugin( &mut self, view_id: ViewId, plugin: &str, method: &str, params: Value, ) -> ClientResult<()> { self.client.notify_plugin(view_id, plugin, method, &params) } } #[derive(Clone)] pub struct DummyClient; impl DummyClient { pub fn new() -> Self { DummyClient {} } } impl Client for DummyClient { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()> { Box::new(ok(())) } fn request(&mut self, method: &str, params: Value) -> ClientResult<Value> { Box::new(ok(json!({}))) } fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()> { Box::new(ok(())) } fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()> { Box::new(ok(())) } fn left(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn right(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn up(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn down(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn delete(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn backspace(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn del(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_up(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_down(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_start(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_end(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn f1(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn f2(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()> { Box::new(ok(())) } fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { Box::new(ok(())) } fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { Box::new(ok(())) } fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId> { Box::new(ok(ViewId(0))) } fn close_view(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()> { Box::new(ok(())) } fn set_theme(&mut self, theme: &str) -> ClientResult<()> { Box::new(ok(())) } fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { Box::new(ok(())) } fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { Box::new(ok(())) } fn notify_plugin( &mut self, view_id: ViewId, plugin: &str, method: &str, params: Value, ) -> ClientResult<()> { Box::new(ok(())) } }
use xrl; use xrl::{ClientResult, ViewId}; use serde_json::Value; use futures::future::ok; pub trait Client { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()>; fn request(&mut self, method: &str, params: Value) -> ClientResult<Value>; fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()>; fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()>; fn left(&mut self, view_id: ViewId) -> ClientResult<()>; fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn right(&mut self, view_id: ViewId) -> ClientResult<()>; fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn up(&mut self, view_id: ViewId) -> ClientResult<()>; fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn down(&mut self, view_id: ViewId) -> ClientResult<()>; fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn delete(&mut self, view_id: ViewId) -> ClientResult<()>; fn backspace(&mut self, view_id: ViewId) -> ClientResult<()>; fn del(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_up(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_down(&mut self, view_id: ViewId) -> ClientResult<()>; fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_start(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_end(&mut self, view_id: ViewId) -> ClientResult<()>; fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()>; fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()>; fn f1(&mut self, view_id: ViewId) -> ClientResult<()>; fn f2(&mut self, view_id: ViewId) -> ClientResult<()>; fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()>; fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()>; fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()>; fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId>; fn close_view(&mut self, view_id: ViewId) -> ClientResult<()>; fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()>; fn set_theme(&mut self, theme: &str) -> ClientResult<()>; fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()>; fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()>; fn notify_plugin( &mut self, view_id: ViewId, plugin: &str, method: &str, params: Value, ) -> ClientResult<()>; } #[derive(Clone)] pub struct XrlClient { client: xrl::Client, } impl XrlClient { pub fn new(client: xrl::Client) -> Self { XrlClient { client: client } } } impl Client for XrlClient { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()> { self.client.notify(method, params) } fn request(&mut self, method: &str, params: Value) -> ClientResult<Value> { self.client.request(method, params) } fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()> { self.client.edit(view_id, method, params) } fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()> { self.client.scroll(view_id, first_line, last_line) } fn left(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.left(view_id) } fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.left_sel(view_id) } fn right(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.right(view_id) } fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.right_sel(view_id) } fn up(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.up(view_id) } fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.up_sel(view_id) } fn down(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.down(view_id) } fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.down_sel(view_id) } fn delete(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.delete(view_id) } fn backspace(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.backspace(view_id) } fn del(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.del(view_id) } fn page_up(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_up(view_id) } fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_up_sel(view_id) } fn page_down(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_down(view_id) } fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.page_down_sel(view_id) } fn line_start(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_start(view_id) } fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_start_sel(view_id) } fn line_end(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_end(view_id) } fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.line_end_sel(view_id) } fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.insert_newline(view_id) } fn f1(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.f1(view_id) } fn f2(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.f2(view_id) } fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()> { self.client.char(view_id, ch) } fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { self.client.click(view_id, line, column) } fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { self.client.drag(view_id, line, column) } fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId> { self.client.new_view(file_path) } fn close_view(&mut self, view_id: ViewId) -> ClientResult<()> { self.client.close_view(view_id) } fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()> { self.client.save(view_id, file_path) } fn set_theme(&mut self, theme: &str) -> ClientResult<()> { self.client.set_theme(theme) } fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { self.client.start_plugin(view_id, name) } fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { self.client.stop_plugin(view_id, name) } fn notify_plugin( &mut self, view_id: ViewId, p
rams) } } #[derive(Clone)] pub struct DummyClient; impl DummyClient { pub fn new() -> Self { DummyClient {} } } impl Client for DummyClient { fn notify(&mut self, method: &str, params: Value) -> ClientResult<()> { Box::new(ok(())) } fn request(&mut self, method: &str, params: Value) -> ClientResult<Value> { Box::new(ok(json!({}))) } fn edit(&mut self, view_id: ViewId, method: &str, params: Option<Value>) -> ClientResult<()> { Box::new(ok(())) } fn scroll(&mut self, view_id: ViewId, first_line: u64, last_line: u64) -> ClientResult<()> { Box::new(ok(())) } fn left(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn left_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn right(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn right_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn up(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn down(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn delete(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn backspace(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn del(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_up(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_up_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_down(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn page_down_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_start(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_start_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_end(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn line_end_sel(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn insert_newline(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn f1(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn f2(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn char(&mut self, view_id: ViewId, ch: char) -> ClientResult<()> { Box::new(ok(())) } fn click(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { Box::new(ok(())) } fn drag(&mut self, view_id: ViewId, line: u64, column: u64) -> ClientResult<()> { Box::new(ok(())) } fn new_view(&mut self, file_path: Option<String>) -> ClientResult<ViewId> { Box::new(ok(ViewId(0))) } fn close_view(&mut self, view_id: ViewId) -> ClientResult<()> { Box::new(ok(())) } fn save(&mut self, view_id: ViewId, file_path: &str) -> ClientResult<()> { Box::new(ok(())) } fn set_theme(&mut self, theme: &str) -> ClientResult<()> { Box::new(ok(())) } fn start_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { Box::new(ok(())) } fn stop_plugin(&mut self, view_id: ViewId, name: &str) -> ClientResult<()> { Box::new(ok(())) } fn notify_plugin( &mut self, view_id: ViewId, plugin: &str, method: &str, params: Value, ) -> ClientResult<()> { Box::new(ok(())) } }
lugin: &str, method: &str, params: Value, ) -> ClientResult<()> { self.client.notify_plugin(view_id, plugin, method, &pa
function_block-random_span
[ { "content": "pub fn parse_any(buffer: &str) -> Option<Key> {\n\n parse_angle(buffer).or(parse_key(buffer))\n\n}\n\n\n\n#[macro_use]\n\npub mod parse {\n\n use super::*;\n\n use key::MultiKey::*;\n\n\n\n named!(\n\n shift<&str, MultiKey>,\n\n map_opt!(\n\n delimited!(tag_no_...
Rust
crates/bevy_asset/src/io/file_asset_io.rs
BoxyUwU/bevy
5d3d9723d15ae4ad12ffe50db4893531887c92c6
use crate::{filesystem_watcher::FilesystemWatcher, AssetIo, AssetIoError, AssetServer}; use anyhow::Result; use bevy_ecs::{bevy_utils::BoxedFuture, Res}; use bevy_utils::HashSet; use crossbeam_channel::TryRecvError; use fs::File; use io::Read; use parking_lot::RwLock; use std::{ env, fs, io, path::{Path, PathBuf}, sync::Arc, }; pub struct FileAssetIo { root_path: PathBuf, #[cfg(feature = "filesystem_watcher")] filesystem_watcher: Arc<RwLock<Option<FilesystemWatcher>>>, } impl FileAssetIo { pub fn new<P: AsRef<Path>>(path: P) -> Self { FileAssetIo { filesystem_watcher: Default::default(), root_path: Self::get_root_path().join(path.as_ref()), } } pub fn get_root_path() -> PathBuf { if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { PathBuf::from(manifest_dir) } else { env::current_exe() .map(|path| { path.parent() .map(|exe_parent_path| exe_parent_path.to_owned()) .unwrap() }) .unwrap() } } } impl AssetIo for FileAssetIo { fn load_path<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<Vec<u8>, AssetIoError>> { Box::pin(async move { let mut bytes = Vec::new(); match File::open(self.root_path.join(path)) { Ok(mut file) => { file.read_to_end(&mut bytes)?; } Err(e) => { if e.kind() == std::io::ErrorKind::NotFound { return Err(AssetIoError::NotFound(path.to_owned())); } else { return Err(e.into()); } } } Ok(bytes) }) } fn read_directory( &self, path: &Path, ) -> Result<Box<dyn Iterator<Item = PathBuf>>, AssetIoError> { let root_path = self.root_path.to_owned(); Ok(Box::new(fs::read_dir(root_path.join(path))?.map( move |entry| { let path = entry.unwrap().path(); path.strip_prefix(&root_path).unwrap().to_owned() }, ))) } fn watch_path_for_changes(&self, path: &Path) -> Result<(), AssetIoError> { #[cfg(feature = "filesystem_watcher")] { let path = self.root_path.join(path); let mut watcher = self.filesystem_watcher.write(); if let Some(ref mut watcher) = *watcher { watcher .watch(&path) .map_err(|_error| AssetIoError::PathWatchError(path))?; } } Ok(()) } fn watch_for_changes(&self) -> Result<(), AssetIoError> { #[cfg(feature = "filesystem_watcher")] { *self.filesystem_watcher.write() = Some(FilesystemWatcher::default()); } Ok(()) } fn is_directory(&self, path: &Path) -> bool { self.root_path.join(path).is_dir() } } #[cfg(all(feature = "filesystem_watcher", not(target_arch = "wasm32")))] pub fn filesystem_watcher_system(asset_server: Res<AssetServer>) { let mut changed = HashSet::default(); let asset_io = if let Some(asset_io) = asset_server.server.asset_io.downcast_ref::<FileAssetIo>() { asset_io } else { return; }; let watcher = asset_io.filesystem_watcher.read(); if let Some(ref watcher) = *watcher { loop { let event = match watcher.receiver.try_recv() { Ok(result) => result.unwrap(), Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => panic!("FilesystemWatcher disconnected"), }; if let notify::event::Event { kind: notify::event::EventKind::Modify(_), paths, .. } = event { for path in paths.iter() { if !changed.contains(path) { let relative_path = path.strip_prefix(&asset_io.root_path).unwrap(); let _ = asset_server.load_untracked(relative_path, true); } } changed.extend(paths); } } } }
use crate::{filesystem_watcher::FilesystemWatcher, AssetIo, AssetIoError, AssetServer}; use anyhow::Result; use bevy_ecs::{bevy_utils::BoxedFuture, Res}; use bevy_utils::HashSet; use crossbeam_channel::TryRecvError; use fs::File; use io::Read; use parking_lot::RwLock; use std::{ env, fs, io, path::{Path, PathBuf}, sync::Arc, }; pub struct FileAssetIo { root_path: PathBuf, #[cfg(feature = "filesystem_watcher")] filesystem_watcher: Arc<RwLock<Option<FilesystemWatcher>>>, } impl FileAssetIo { pub fn new<P: AsRef<Path>>(path: P) -> Self { FileAssetIo { filesystem_watcher: Default::default(), root_path: Self::get_root_path().join(path.as_ref()), } } pub fn get_root_path() -> PathBuf { if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { PathBuf::from(manifest_dir) } else { env::current_exe() .map(|path| { path.parent() .map(|exe_parent_path| exe_parent_path.to_owned()) .unwrap() }) .unwrap() } } } impl AssetIo for FileAssetIo { fn load_path<'a>(&'a self, path: &'a Path) -> BoxedFuture<'a, Result<Vec<u8>, AssetIoError>> { Box::pin(async move { let mut bytes = Vec::new(); match File::open(self.root_path.join(path)) { Ok(mut file) => { file.read_to_end(&mut bytes)?; } Err(e) => { if e.kind() == std::io::ErrorKind::NotFound { return Err(AssetIoError::NotFound(path.to_owned())); } else { return Err(e.into()); } } } Ok(bytes) }) } fn read_directory( &self, path: &Path, ) -> Result<Box<dyn Iterator<Item = PathBuf>>, AssetIoError> { let root_path = self.root_path.to_owned();
} fn watch_path_for_changes(&self, path: &Path) -> Result<(), AssetIoError> { #[cfg(feature = "filesystem_watcher")] { let path = self.root_path.join(path); let mut watcher = self.filesystem_watcher.write(); if let Some(ref mut watcher) = *watcher { watcher .watch(&path) .map_err(|_error| AssetIoError::PathWatchError(path))?; } } Ok(()) } fn watch_for_changes(&self) -> Result<(), AssetIoError> { #[cfg(feature = "filesystem_watcher")] { *self.filesystem_watcher.write() = Some(FilesystemWatcher::default()); } Ok(()) } fn is_directory(&self, path: &Path) -> bool { self.root_path.join(path).is_dir() } } #[cfg(all(feature = "filesystem_watcher", not(target_arch = "wasm32")))] pub fn filesystem_watcher_system(asset_server: Res<AssetServer>) { let mut changed = HashSet::default(); let asset_io = if let Some(asset_io) = asset_server.server.asset_io.downcast_ref::<FileAssetIo>() { asset_io } else { return; }; let watcher = asset_io.filesystem_watcher.read(); if let Some(ref watcher) = *watcher { loop { let event = match watcher.receiver.try_recv() { Ok(result) => result.unwrap(), Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => panic!("FilesystemWatcher disconnected"), }; if let notify::event::Event { kind: notify::event::EventKind::Modify(_), paths, .. } = event { for path in paths.iter() { if !changed.contains(path) { let relative_path = path.strip_prefix(&asset_io.root_path).unwrap(); let _ = asset_server.load_untracked(relative_path, true); } } changed.extend(paths); } } } }
Ok(Box::new(fs::read_dir(root_path.join(path))?.map( move |entry| { let path = entry.unwrap().path(); path.strip_prefix(&root_path).unwrap().to_owned() }, )))
call_expression
[ { "content": "pub fn get_wgpu_render_system(resources: &mut Resources) -> impl FnMut(&mut World, &mut Resources) {\n\n let options = resources\n\n .get_cloned::<WgpuOptions>()\n\n .unwrap_or_else(WgpuOptions::default);\n\n let mut wgpu_renderer = future::block_on(WgpuRenderer::new(options));...
Rust
examples/flat_2d_across_nodes.rs
jrxb/ui-navigation
0f92dd0df092469d2fb8beb1f5ae0d9fb06d007d
use bevy::prelude::*; use bevy_ui_navigation::{ systems::{default_gamepad_input, default_keyboard_input, InputMapping}, Focusable, Focused, NavEvent, NavMenu, NavigationPlugin, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugin(NavigationPlugin) .init_resource::<ButtonMaterials>() .init_resource::<InputMapping>() .add_startup_system(setup) .add_system(button_system) .add_system(print_nav_events) .add_system(default_keyboard_input) .add_system(default_gamepad_input) .run(); } struct ButtonMaterials { normal: Handle<ColorMaterial>, focused: Handle<ColorMaterial>, pink: Handle<ColorMaterial>, backgrounds: [Handle<ColorMaterial>; 3], } impl FromWorld for ButtonMaterials { fn from_world(world: &mut World) -> Self { let mut materials = world.get_resource_mut::<Assets<ColorMaterial>>().unwrap(); ButtonMaterials { normal: materials.add(Color::rgb(0.15, 0.15, 0.15).into()), focused: materials.add(Color::rgb(0.35, 0.75, 0.35).into()), pink: materials.add(Color::rgba(1.00, 0.35, 1.0, 0.5).into()), backgrounds: [ materials.add(Color::rgba(1.0, 0.35, 0.35, 0.5).into()), materials.add(Color::rgba(0.35, 1.0, 0.35, 0.5).into()), materials.add(Color::rgba(0.35, 0.35, 1.0, 0.5).into()), ], } } } fn print_nav_events(mut events: EventReader<NavEvent>) { for event in events.iter() { println!("{:?}", event); } } fn button_system( button_materials: Res<ButtonMaterials>, mut interaction_query: Query<(Option<&Focused>, &mut Handle<ColorMaterial>), With<Button>>, ) { for (interaction, mut material) in interaction_query.iter_mut() { match interaction { Some(_) => { *material = button_materials.focused.clone(); } None => { *material = button_materials.normal.clone(); } } } } fn setup(mut commands: Commands, button_materials: Res<ButtonMaterials>) { let size = |width, height| Size::new(Val::Percent(width), Val::Percent(height)); let flex_wrap = FlexWrap::Wrap; let style = Style { size: size(100.0, 100.0), flex_wrap, ..Style::default() }; let bundle = NodeBundle { style, ..Default::default() }; let size = size(45.0, 45.0); commands.spawn_bundle(UiCameraBundle::default()); commands .spawn_bundle(bundle) .insert(NavMenu::root()) .with_children(|commands| { for i in 0..3 { let style = Style { size, ..Style::default() }; let bundle = NodeBundle { style, material: button_materials.backgrounds[i].clone(), ..Default::default() }; commands.spawn_bundle(bundle).with_children(|commands| { spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); }); } let style = Style { size, ..Style::default() }; let bundle = NodeBundle { style, material: button_materials.pink.clone(), ..Default::default() }; commands .spawn_bundle(bundle) .insert(NavMenu::root()) .with_children(|commands| { spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); }); }); } fn spawn_button(commands: &mut ChildBuilder, button_materials: &ButtonMaterials) { commands .spawn_bundle(ButtonBundle { style: Style { size: Size::new(Val::Px(120.0), Val::Px(60.0)), margin: Rect::all(Val::Percent(4.0)), ..Default::default() }, material: button_materials.normal.clone(), ..Default::default() }) .insert(Focusable::default()); }
use bevy::prelude::*; use bevy_ui_navigation::{ systems::{default_gamepad_input, default_keyboard_input, InputMapping}, Focusable, Focused, NavEvent, NavMenu, NavigationPlugin, }; fn main() { App::new() .add_plugins(DefaultPlugins) .add_plugin(NavigationPlugin) .init_resource::<ButtonMaterials>() .init_resource::<InputMapping>() .add_startup_system(setup) .add_system(button_system) .add_system(print_nav_events) .add_system(default_keyboard_input) .add_system(default_gamepad_input) .run(); } struct ButtonMaterials { normal: Handle<ColorMaterial>, focused: Handle<ColorMaterial>, pink: Handle<ColorMaterial>, backgrounds: [Handle<ColorMaterial>; 3], } impl FromWorld for ButtonMaterials {
} fn print_nav_events(mut events: EventReader<NavEvent>) { for event in events.iter() { println!("{:?}", event); } } fn button_system( button_materials: Res<ButtonMaterials>, mut interaction_query: Query<(Option<&Focused>, &mut Handle<ColorMaterial>), With<Button>>, ) { for (interaction, mut material) in interaction_query.iter_mut() { match interaction { Some(_) => { *material = button_materials.focused.clone(); } None => { *material = button_materials.normal.clone(); } } } } fn setup(mut commands: Commands, button_materials: Res<ButtonMaterials>) { let size = |width, height| Size::new(Val::Percent(width), Val::Percent(height)); let flex_wrap = FlexWrap::Wrap; let style = Style { size: size(100.0, 100.0), flex_wrap, ..Style::default() }; let bundle = NodeBundle { style, ..Default::default() }; let size = size(45.0, 45.0); commands.spawn_bundle(UiCameraBundle::default()); commands .spawn_bundle(bundle) .insert(NavMenu::root()) .with_children(|commands| { for i in 0..3 { let style = Style { size, ..Style::default() }; let bundle = NodeBundle { style, material: button_materials.backgrounds[i].clone(), ..Default::default() }; commands.spawn_bundle(bundle).with_children(|commands| { spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); }); } let style = Style { size, ..Style::default() }; let bundle = NodeBundle { style, material: button_materials.pink.clone(), ..Default::default() }; commands .spawn_bundle(bundle) .insert(NavMenu::root()) .with_children(|commands| { spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); spawn_button(commands, &button_materials); }); }); } fn spawn_button(commands: &mut ChildBuilder, button_materials: &ButtonMaterials) { commands .spawn_bundle(ButtonBundle { style: Style { size: Size::new(Val::Px(120.0), Val::Px(60.0)), margin: Rect::all(Val::Percent(4.0)), ..Default::default() }, material: button_materials.normal.clone(), ..Default::default() }) .insert(Focusable::default()); }
fn from_world(world: &mut World) -> Self { let mut materials = world.get_resource_mut::<Assets<ColorMaterial>>().unwrap(); ButtonMaterials { normal: materials.add(Color::rgb(0.15, 0.15, 0.15).into()), focused: materials.add(Color::rgb(0.35, 0.75, 0.35).into()), pink: materials.add(Color::rgba(1.00, 0.35, 1.0, 0.5).into()), backgrounds: [ materials.add(Color::rgba(1.0, 0.35, 0.35, 0.5).into()), materials.add(Color::rgba(0.35, 1.0, 0.35, 0.5).into()), materials.add(Color::rgba(0.35, 0.35, 1.0, 0.5).into()), ], } }
function_block-full_function
[ { "content": "/// This example illustrates how to mark buttons as focusable and let\n\n/// NavigationPlugin figure out how to go from one to another.\n\nfn main() {\n\n App::new()\n\n .add_plugins(DefaultPlugins)\n\n // 1: Add the NavigationPlugin\n\n .add_plugin(NavigationPlugin)\n\n ...
Rust
src/error.rs
gnp/cusip-rs
f1f4bf8e244f30fd21e8347175e5da455de2b351
#![warn(missing_docs)] use std::error::Error; use std::fmt::Formatter; use std::fmt::{Debug, Display}; #[non_exhaustive] #[derive(Clone, PartialEq, Eq)] pub enum CUSIPError { InvalidCUSIPLength { was: usize, }, InvalidPayloadLength { was: usize, }, InvalidIssuerNumLength { was: usize, }, InvalidIssueNumLength { was: usize, }, InvalidIssuerNum { was: [u8; 6], }, InvalidIssueNum { was: [u8; 2], }, InvalidCheckDigit { was: u8, }, IncorrectCheckDigit { was: u8, expected: u8, }, } impl Debug for CUSIPError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { CUSIPError::InvalidCUSIPLength { was } => { write!(f, "InvalidCUSIPLength {{ was: {:?} }}", was) } CUSIPError::InvalidPayloadLength { was } => { write!(f, "InvalidPayloadLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssuerNumLength { was } => { write!(f, "InvalidIssuerNumLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssueNumLength { was } => { write!(f, "InvalidIssueNumLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssuerNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!(f, "InvalidIssuerNum {{ was: {:?} }}", s) } Err(_) => { write!(f, "InvalidIssuerNum {{ was: (invalid UTF-8) {:?} }}", was) } }, CUSIPError::InvalidIssueNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!(f, "InvalidIssueNum {{ was: {:?} }}", s) } Err(_) => { write!(f, "InvalidIssueNum {{ was: (invalid UTF-8) {:?} }}", was) } }, CUSIPError::InvalidCheckDigit { was } => { write!(f, "InvalidCheckDigit {{ was: {:?} }}", char::from(*was)) } CUSIPError::IncorrectCheckDigit { was, expected } => { write!( f, "IncorrectCheckDigit {{ was: {:?}, expected: {:?} }}", char::from(*was), char::from(*expected) ) } } } } impl Display for CUSIPError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { CUSIPError::InvalidCUSIPLength { was } => { write!(f, "invalid CUSIP length {} bytes when expecting 9", was) } CUSIPError::InvalidPayloadLength { was } => { write!(f, "invalid Payload length {} bytes when expecting 8", was) } CUSIPError::InvalidIssuerNumLength { was } => { write!( f, "invalid Issuer Number length {} bytes when expecting 6", was ) } CUSIPError::InvalidIssueNumLength { was } => { write!( f, "invalid Issue Number length {} bytes when expecting 2", was ) } CUSIPError::InvalidIssuerNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!( f, "Issuer Number {:?} is not six uppercase ASCII alphanumeric characters", s ) } Err(_) => { write!(f, "Issuer Number (invalid UTF-8) {:?} is not six uppercase ASCII alphanumeric characters", was) } }, CUSIPError::InvalidIssueNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!( f, "Issue Number {:?} is not two uppercase ASCII alphanumeric characters", s ) } Err(_) => { write!(f, "Issue Number (invalid UTF-8) {:?} is not two uppercase ASCII alphanumeric characters", was) } }, CUSIPError::InvalidCheckDigit { was } => { write!( f, "Check Digit {:?} is not one ASCII decimal digit", *was as char ) } CUSIPError::IncorrectCheckDigit { was, expected } => { write!( f, "incorrect Check Digit {:?} when expecting {:?}", char::from(*was), char::from(*expected) ) } } } } impl Error for CUSIPError {}
#![warn(missing_docs)] use std::error::Error; use std::fmt::Formatter; use std::fmt::{Debug, Display}; #[non_exhaustive] #[derive(Clone, PartialEq, Eq)] pub enum CUSIPError { InvalidCUSIPLength { was: usize, }, InvalidPayloadLength { was: usize, }, InvalidIssuerNumLength { was: usize, }, InvalidIssueNumLength { was: usize, }, InvalidIssuerNum { was: [u8; 6], }, InvalidIssueNum { was: [u8; 2], }, InvalidCheckDigit { was: u8, }, IncorrectCheckDigit { was: u8, expected: u8, }, } impl Debug for CUSIPError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { CUSIPError::InvalidCUSIPLength { was } => { write!(f, "InvalidCUSIPLength {{ was: {:?} }}", was) } CUSIPError::InvalidPayloadLength { was } => { write!(f, "InvalidPayloadLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssuerNumLength { was } => { write!(f, "InvalidIssuerNumLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssueNumLength { was } => { write!(f, "InvalidIssueNumLength {{ was: {:?} }}", was) } CUSIPError::InvalidIssuerNum { was } => match std::str::from_utf8(was) { Ok(s) => {
Digit { was } => { write!(f, "InvalidCheckDigit {{ was: {:?} }}", char::from(*was)) } CUSIPError::IncorrectCheckDigit { was, expected } => { write!( f, "IncorrectCheckDigit {{ was: {:?}, expected: {:?} }}", char::from(*was), char::from(*expected) ) } } } } impl Display for CUSIPError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { CUSIPError::InvalidCUSIPLength { was } => { write!(f, "invalid CUSIP length {} bytes when expecting 9", was) } CUSIPError::InvalidPayloadLength { was } => { write!(f, "invalid Payload length {} bytes when expecting 8", was) } CUSIPError::InvalidIssuerNumLength { was } => { write!( f, "invalid Issuer Number length {} bytes when expecting 6", was ) } CUSIPError::InvalidIssueNumLength { was } => { write!( f, "invalid Issue Number length {} bytes when expecting 2", was ) } CUSIPError::InvalidIssuerNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!( f, "Issuer Number {:?} is not six uppercase ASCII alphanumeric characters", s ) } Err(_) => { write!(f, "Issuer Number (invalid UTF-8) {:?} is not six uppercase ASCII alphanumeric characters", was) } }, CUSIPError::InvalidIssueNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!( f, "Issue Number {:?} is not two uppercase ASCII alphanumeric characters", s ) } Err(_) => { write!(f, "Issue Number (invalid UTF-8) {:?} is not two uppercase ASCII alphanumeric characters", was) } }, CUSIPError::InvalidCheckDigit { was } => { write!( f, "Check Digit {:?} is not one ASCII decimal digit", *was as char ) } CUSIPError::IncorrectCheckDigit { was, expected } => { write!( f, "incorrect Check Digit {:?} when expecting {:?}", char::from(*was), char::from(*expected) ) } } } } impl Error for CUSIPError {}
write!(f, "InvalidIssuerNum {{ was: {:?} }}", s) } Err(_) => { write!(f, "InvalidIssuerNum {{ was: (invalid UTF-8) {:?} }}", was) } }, CUSIPError::InvalidIssueNum { was } => match std::str::from_utf8(was) { Ok(s) => { write!(f, "InvalidIssueNum {{ was: {:?} }}", s) } Err(_) => { write!(f, "InvalidIssueNum {{ was: (invalid UTF-8) {:?} }}", was) } }, CUSIPError::InvalidCheck
function_block-random_span
[ { "content": "/// Compute the _checksum_ for a u8 array. No attempt is made to ensure the input string is in\n\n/// the CUSIP payload format or length.\n\n///\n\n/// The algorithm processes the input ASCII characters left-to-right, and counting from one, doubles\n\n/// the even ones and leaves the odd ones with...
Rust
src/sqllogictest/src/main.rs
priceloop/materialize
fa6d085455d94a2169d0df24805a5de76f2b3938
use std::cell::RefCell; use std::fmt; use std::fs::File; use std::io::{self, Write}; use std::path::PathBuf; use std::process; use chrono::Utc; use walkdir::WalkDir; use mz_sqllogictest::runner::{self, Outcomes, RunConfig, WriteFmt}; use mz_sqllogictest::util; #[derive(clap::Parser)] struct Args { #[clap(short = 'v', long = "verbose", parse(from_occurrences))] verbosity: usize, #[clap(long)] no_fail: bool, #[clap(long)] timestamps: bool, #[clap(long)] rewrite_results: bool, #[clap(long, value_name = "FILE")] json_summary_file: Option<PathBuf>, #[clap(long, value_name = "N", default_value = "3")] workers: usize, #[clap(value_name = "PATH", required = true)] paths: Vec<String>, #[clap(long)] fail_fast: bool, } #[tokio::main] async fn main() { mz_ore::panic::set_abort_on_panic(); mz_ore::test::init_logging_default("warn"); let args: Args = mz_ore::cli::parse_args(); let config = RunConfig { stdout: &OutputStream::new(io::stdout(), args.timestamps), stderr: &OutputStream::new(io::stderr(), args.timestamps), verbosity: args.verbosity, workers: args.workers, no_fail: args.no_fail, fail_fast: args.fail_fast, }; if args.rewrite_results { return rewrite(&config, args).await; } let json_summary_file = match args.json_summary_file { Some(filename) => match File::create(&filename) { Ok(file) => Some(file), Err(err) => { writeln!(config.stderr, "creating {}: {}", filename.display(), err); process::exit(1); } }, None => None, }; let mut bad_file = false; let mut outcomes = Outcomes::default(); for path in &args.paths { if path == "-" { match mz_sqllogictest::runner::run_stdin(&config).await { Ok(o) => outcomes += o, Err(err) => { writeln!(config.stderr, "error: parsing stdin: {}", err); bad_file = true; } } } else { for entry in WalkDir::new(path) { match entry { Ok(entry) if entry.file_type().is_file() => { match runner::run_file(&config, entry.path()).await { Ok(o) => { if o.any_failed() || config.verbosity >= 1 { writeln!( config.stdout, "{}", util::indent(&o.display(config.no_fail).to_string(), 4) ); } outcomes += o; } Err(err) => { writeln!(config.stderr, "error: parsing file: {}", err); bad_file = true; } } } Ok(_) => (), Err(err) => { writeln!(config.stderr, "error: reading directory entry: {}", err); bad_file = true; } } } } } if bad_file { process::exit(1); } writeln!(config.stdout, "{}", outcomes.display(config.no_fail)); if let Some(json_summary_file) = json_summary_file { match serde_json::to_writer(json_summary_file, &outcomes.as_json()) { Ok(()) => (), Err(err) => { writeln!( config.stderr, "error: unable to write summary file: {}", err ); process::exit(2); } } } if outcomes.any_failed() && !args.no_fail { process::exit(1); } } async fn rewrite(config: &RunConfig<'_>, args: Args) { if args.json_summary_file.is_some() { writeln!( config.stderr, "--rewrite-results is not compatible with --json-summary-file" ); process::exit(1); } if args.paths.iter().any(|path| path == "-") { writeln!(config.stderr, "--rewrite-results cannot be used with stdin"); process::exit(1); } let mut bad_file = false; for path in args.paths { for entry in WalkDir::new(path) { match entry { Ok(entry) => { if entry.file_type().is_file() { if let Err(err) = runner::rewrite_file(config, entry.path()).await { writeln!(config.stderr, "error: rewriting file: {}", err); bad_file = true; } } } Err(err) => { writeln!(config.stderr, "error: reading directory entry: {}", err); bad_file = true; } } } } if bad_file { process::exit(1); } } struct OutputStream<W> { inner: RefCell<W>, need_timestamp: RefCell<bool>, timestamps: bool, } impl<W> OutputStream<W> where W: Write, { fn new(inner: W, timestamps: bool) -> OutputStream<W> { OutputStream { inner: RefCell::new(inner), need_timestamp: RefCell::new(true), timestamps, } } fn emit_str(&self, s: &str) { self.inner.borrow_mut().write_all(s.as_bytes()).unwrap(); } } impl<W> WriteFmt for OutputStream<W> where W: Write, { fn write_fmt(&self, fmt: fmt::Arguments<'_>) { let s = format!("{}", fmt); if self.timestamps { let timestamp = Utc::now(); if self.need_timestamp.replace(false) { self.emit_str(&format!("[{}] ", timestamp)); } let (s, last_was_timestamp) = match s.strip_suffix('\n') { None => (&*s, false), Some(s) => (s, true), }; self.emit_str(&s.replace("\n", &format!("\n[{}] ", timestamp))); if last_was_timestamp { *self.need_timestamp.borrow_mut() = true; self.emit_str("\n"); } } else { self.emit_str(&s) } } }
use std::cell::RefCell; use std::fmt; use std::fs::File; use std::io::{self, Write}; use std::path::PathBuf; use std::process; use chrono::Utc; use walkdir::WalkDir; use mz_sqllogictest::runner::{self, Outcomes, RunConfig, WriteFmt}; use mz_sqllogictest::util; #[derive(clap::Parser)] struct Args { #[clap(short = 'v', long = "verbose", parse(from_occurrences))] verbosity: usize, #[clap(long)] no_fail: bool, #[clap(long)] timestamps: bool, #[clap(long)] rewrite_results: bool, #[clap(long, value_name = "FILE")] json_summary_file: Option<PathBuf>, #[clap(long, value_name = "N", default_value = "3")] workers: usize, #[clap(value_name = "PATH", required = true)] paths: Vec<String>, #[clap(long)] fail_fast: bool, } #[tokio::main] async fn main() { mz_ore::panic::set_abort_on_panic(); mz_ore::test::init_logging_default("warn"); let args: Args = mz_ore::cli::parse_args(); let config = RunConfig { stdout: &OutputStream::new(io::stdout(), args.timestamps), stderr: &OutputStream::new(io::stderr(), args.timestamps), verbosity: args.verbosity, workers: args.workers, no_fail: args.no_fail, fail_fast: args.fail_fast, }; if args.rewrite_results { return rewrite(&config, args).await; } let json_summary_file = match args.json_summary_file { Some(filename)
r: W, timestamps: bool) -> OutputStream<W> { OutputStream { inner: RefCell::new(inner), need_timestamp: RefCell::new(true), timestamps, } } fn emit_str(&self, s: &str) { self.inner.borrow_mut().write_all(s.as_bytes()).unwrap(); } } impl<W> WriteFmt for OutputStream<W> where W: Write, { fn write_fmt(&self, fmt: fmt::Arguments<'_>) { let s = format!("{}", fmt); if self.timestamps { let timestamp = Utc::now(); if self.need_timestamp.replace(false) { self.emit_str(&format!("[{}] ", timestamp)); } let (s, last_was_timestamp) = match s.strip_suffix('\n') { None => (&*s, false), Some(s) => (s, true), }; self.emit_str(&s.replace("\n", &format!("\n[{}] ", timestamp))); if last_was_timestamp { *self.need_timestamp.borrow_mut() = true; self.emit_str("\n"); } } else { self.emit_str(&s) } } }
=> match File::create(&filename) { Ok(file) => Some(file), Err(err) => { writeln!(config.stderr, "creating {}: {}", filename.display(), err); process::exit(1); } }, None => None, }; let mut bad_file = false; let mut outcomes = Outcomes::default(); for path in &args.paths { if path == "-" { match mz_sqllogictest::runner::run_stdin(&config).await { Ok(o) => outcomes += o, Err(err) => { writeln!(config.stderr, "error: parsing stdin: {}", err); bad_file = true; } } } else { for entry in WalkDir::new(path) { match entry { Ok(entry) if entry.file_type().is_file() => { match runner::run_file(&config, entry.path()).await { Ok(o) => { if o.any_failed() || config.verbosity >= 1 { writeln!( config.stdout, "{}", util::indent(&o.display(config.no_fail).to_string(), 4) ); } outcomes += o; } Err(err) => { writeln!(config.stderr, "error: parsing file: {}", err); bad_file = true; } } } Ok(_) => (), Err(err) => { writeln!(config.stderr, "error: reading directory entry: {}", err); bad_file = true; } } } } } if bad_file { process::exit(1); } writeln!(config.stdout, "{}", outcomes.display(config.no_fail)); if let Some(json_summary_file) = json_summary_file { match serde_json::to_writer(json_summary_file, &outcomes.as_json()) { Ok(()) => (), Err(err) => { writeln!( config.stderr, "error: unable to write summary file: {}", err ); process::exit(2); } } } if outcomes.any_failed() && !args.no_fail { process::exit(1); } } async fn rewrite(config: &RunConfig<'_>, args: Args) { if args.json_summary_file.is_some() { writeln!( config.stderr, "--rewrite-results is not compatible with --json-summary-file" ); process::exit(1); } if args.paths.iter().any(|path| path == "-") { writeln!(config.stderr, "--rewrite-results cannot be used with stdin"); process::exit(1); } let mut bad_file = false; for path in args.paths { for entry in WalkDir::new(path) { match entry { Ok(entry) => { if entry.file_type().is_file() { if let Err(err) = runner::rewrite_file(config, entry.path()).await { writeln!(config.stderr, "error: rewriting file: {}", err); bad_file = true; } } } Err(err) => { writeln!(config.stderr, "error: reading directory entry: {}", err); bad_file = true; } } } } if bad_file { process::exit(1); } } struct OutputStream<W> { inner: RefCell<W>, need_timestamp: RefCell<bool>, timestamps: bool, } impl<W> OutputStream<W> where W: Write, { fn new(inne
random
[]
Rust
src/libstd/sync/mutex.rs
quornian/rust
dbc379a66eae8504b663b0032da518595335d872
#![allow(dead_code)] use core::prelude::*; use alloc::boxed::Box; use rustrt::mutex; pub const LOCKED: uint = 1 << 0; pub const BLOCKED: uint = 1 << 1; pub struct Mutex { lock: Box<StaticMutex>, } pub struct StaticMutex { lock: mutex::StaticNativeMutex, } #[must_use] pub struct Guard<'a> { guard: mutex::LockGuard<'a>, } fn lift_guard(guard: mutex::LockGuard) -> Guard { Guard { guard: guard } } pub const MUTEX_INIT: StaticMutex = StaticMutex { lock: mutex::NATIVE_MUTEX_INIT }; impl StaticMutex { pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> { unsafe { self.lock.trylock().map(lift_guard) } } pub fn lock<'a>(&'a self) -> Guard<'a> { lift_guard(unsafe { self.lock.lock() }) } pub unsafe fn destroy(&self) { self.lock.destroy() } } impl Mutex { pub fn new() -> Mutex { Mutex { lock: box StaticMutex { lock: unsafe { mutex::StaticNativeMutex::new() }, } } } pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> { self.lock.try_lock() } pub fn lock<'a>(&'a self) -> Guard<'a> { self.lock.lock() } } impl Drop for Mutex { fn drop(&mut self) { unsafe { self.lock.destroy() } } } #[cfg(test)] mod test { use prelude::*; use super::{Mutex, StaticMutex, MUTEX_INIT}; #[test] fn smoke() { let m = Mutex::new(); drop(m.lock()); drop(m.lock()); } #[test] fn smoke_static() { static M: StaticMutex = MUTEX_INIT; unsafe { drop(M.lock()); drop(M.lock()); M.destroy(); } } #[test] fn lots_and_lots() { static M: StaticMutex = MUTEX_INIT; static mut CNT: uint = 0; static J: uint = 1000; static K: uint = 3; fn inc() { for _ in range(0, J) { unsafe { let _g = M.lock(); CNT += 1; } } } let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); } drop(tx); for _ in range(0, 2 * K) { rx.recv(); } assert_eq!(unsafe {CNT}, J * K * 2); unsafe { M.destroy(); } } #[test] fn trylock() { let m = Mutex::new(); assert!(m.try_lock().is_some()); } }
#![allow(dead_code)] use core::prelude::*; use alloc::boxed::Box; use rustrt::mutex; pub const LOCKED: uint = 1 << 0; pub const BLOCKED: uint = 1 << 1; pub struct Mutex { lock: Box<StaticMutex>, } pub struct StaticMutex { lock: mutex::StaticNativeMutex, } #[must_use] pub struct Guard<'a> { guard: mutex::LockGuard<'a>, } fn lift_guard(guard: mutex::LockGuard) -> Guard { Guard { guard: guard } } pub const MUTEX_INIT: StaticMutex = StaticMutex { lock: mutex::NATIVE_MUTEX_INIT }; impl StaticMutex { pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> { unsafe { self.lock.trylock().map(lift_guard) } } pub fn lock<'a>(&'a self) -> Guard<'a> { lift_guard(unsafe { self.lock.lock() }) } pub unsafe fn destroy(&self) { self.lock.destroy() } } impl Mutex { pub fn new() -> Mutex { Mutex { lock: box StaticMutex { lock: unsafe { mutex::StaticNativeMutex::new() }, } } } pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> { self.lock.try_lock() } pub fn lock<'a>(&'a self) -> Guard<'a> { self.lock.lock() } } impl Drop for Mutex { fn drop(&mut self) { unsafe { self.lock.destroy() } } } #[cfg(test)] mod test { use prelude::*; use super::{Mutex, StaticMutex, MUTEX_INIT}; #[test] fn smoke() { let m = Mutex::new(); drop(m.lock()); drop(m.lock()); } #[test] fn smoke_static() { static M: StaticMutex = MUTEX_INIT; unsafe { drop(M.lock()); drop(M.lock()); M.destroy(); } } #[test] fn lots_and_lots() { static M: StaticMutex = MUTEX_INIT; static mut CNT: uint = 0; static J: uint = 1000; static K: uint = 3; fn inc() {
let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); } drop(tx); for _ in range(0, 2 * K) { rx.recv(); } assert_eq!(unsafe {CNT}, J * K * 2); unsafe { M.destroy(); } } #[test] fn trylock() { let m = Mutex::new(); assert!(m.try_lock().is_some()); } }
for _ in range(0, J) { unsafe { let _g = M.lock(); CNT += 1; } } }
function_block-function_prefix_line
[ { "content": "pub fn main() { let _quux: Box<Vec<uint>> = box Vec::new(); }\n", "file_path": "src/test/run-pass/vector-no-ann-2.rs", "rank": 0, "score": 691504.1338730764 }, { "content": "#[rustc_move_fragments]\n\npub fn test_move_array_then_overwrite_elem2(mut a: [D, ..3], i: uint, j: uint...
Rust
types/src/deploy_info.rs
mcdee/casper-node
8cff3369480aaa7645bd7626ae0af19628873b2c
#![allow(clippy::field_reassign_with_default)] use alloc::vec::Vec; #[cfg(feature = "std")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ account::AccountHash, bytesrepr::{self, FromBytes, ToBytes}, DeployHash, TransferAddr, URef, U512, }; #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "std", derive(JsonSchema))] #[serde(deny_unknown_fields)] pub struct DeployInfo { pub deploy_hash: DeployHash, pub transfers: Vec<TransferAddr>, pub from: AccountHash, pub source: URef, pub gas: U512, } impl DeployInfo { pub fn new( deploy_hash: DeployHash, transfers: &[TransferAddr], from: AccountHash, source: URef, gas: U512, ) -> Self { let transfers = transfers.to_vec(); DeployInfo { deploy_hash, transfers, from, source, gas, } } } impl FromBytes for DeployInfo { fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> { let (deploy_hash, rem) = DeployHash::from_bytes(bytes)?; let (transfers, rem) = Vec::<TransferAddr>::from_bytes(rem)?; let (from, rem) = AccountHash::from_bytes(rem)?; let (source, rem) = URef::from_bytes(rem)?; let (gas, rem) = U512::from_bytes(rem)?; Ok(( DeployInfo { deploy_hash, transfers, from, source, gas, }, rem, )) } } impl ToBytes for DeployInfo { fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> { let mut result = bytesrepr::allocate_buffer(self)?; result.append(&mut self.deploy_hash.to_bytes()?); result.append(&mut self.transfers.to_bytes()?); result.append(&mut self.from.to_bytes()?); result.append(&mut self.source.to_bytes()?); result.append(&mut self.gas.to_bytes()?); Ok(result) } fn serialized_length(&self) -> usize { self.deploy_hash.serialized_length() + self.transfers.serialized_length() + self.from.serialized_length() + self.source.serialized_length() + self.gas.serialized_length() } } #[cfg(any(feature = "gens", test))] pub(crate) mod gens { use alloc::vec::Vec; use proptest::{ array, collection::{self, SizeRange}, prelude::{Arbitrary, Strategy}, }; use crate::{ account::AccountHash, gens::{u512_arb, uref_arb}, DeployHash, DeployInfo, TransferAddr, }; pub fn deploy_hash_arb() -> impl Strategy<Value = DeployHash> { array::uniform32(<u8>::arbitrary()).prop_map(DeployHash::new) } pub fn transfer_addr_arb() -> impl Strategy<Value = TransferAddr> { array::uniform32(<u8>::arbitrary()).prop_map(TransferAddr::new) } pub fn transfers_arb(size: impl Into<SizeRange>) -> impl Strategy<Value = Vec<TransferAddr>> { collection::vec(transfer_addr_arb(), size) } pub fn account_hash_arb() -> impl Strategy<Value = AccountHash> { array::uniform32(<u8>::arbitrary()).prop_map(AccountHash::new) } pub fn deploy_info_arb() -> impl Strategy<Value = DeployInfo> { let transfers_length_range = 0..5; ( deploy_hash_arb(), transfers_arb(transfers_length_range), account_hash_arb(), uref_arb(), u512_arb(), ) .prop_map(|(deploy_hash, transfers, from, source, gas)| DeployInfo { deploy_hash, transfers, from, source, gas, }) } } #[cfg(test)] mod tests { use proptest::prelude::*; use crate::bytesrepr; use super::gens; proptest! { #[test] fn test_serialization_roundtrip(deploy_info in gens::deploy_info_arb()) { bytesrepr::test_serialization_roundtrip(&deploy_info) } } }
#![allow(clippy::field_reassign_with_default)] use alloc::vec::Vec; #[cfg(feature = "std")] use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ account::AccountHash, bytesrepr::{self, FromBytes, ToBytes}, DeployHash, TransferAddr, URef, U512, }; #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "std", derive(JsonSchema))] #[serde(deny_unknown_fields)] pub struct DeployInfo { pub deploy_hash: DeployHash, pub transfers: Vec<TransferAddr>, pub from: AccountHash, pub source: URef, pub gas: U512, } impl DeployInfo { pub fn new( deploy_hash: DeployHash, transfers: &[TransferAddr], from: AccountHash, source: URef, gas: U512, ) -> Self { let transfers = transfers.to_vec(); DeployInfo { deploy_hash, transfers, from, source, gas, } } } impl FromBytes for DeployInfo { fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> { let (deploy_hash, rem) = DeployHash::from_bytes(bytes)?; let (transfers, rem) = Vec::<TransferAddr>::from_bytes(rem)?; let (from, rem) = AccountHash::from_bytes(rem)?; let (source, rem) = URef::from_bytes(rem)?; let (gas, rem) = U512::from_bytes(rem)?; Ok(( DeployInfo { deploy_hash, transfers, from, source, gas, }, rem, )) } } impl ToBytes for DeployInfo { fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> { let mut result = bytesrepr::allocate_buffer(self)?; result.append(&mut self.deploy_hash.to_bytes()?); result.append(&mut self.transfers.to_bytes()?); result.append(&mut self.from.to_bytes()?); result.append(&mut self.source.to_bytes()?); result.append(&mut self.gas.to_bytes()?); Ok(result) } fn serialized_length(&self) -> usize { self.deploy_hash.serialized_length() + self.transfers.serialized_length() + self.from.serialized_length() + self.source.serialized_length() + self.gas.serialized_length() } } #[cfg(any(feature = "gens", test))] pub(crate) mod gens {
roundtrip(deploy_info in gens::deploy_info_arb()) { bytesrepr::test_serialization_roundtrip(&deploy_info) } } }
use alloc::vec::Vec; use proptest::{ array, collection::{self, SizeRange}, prelude::{Arbitrary, Strategy}, }; use crate::{ account::AccountHash, gens::{u512_arb, uref_arb}, DeployHash, DeployInfo, TransferAddr, }; pub fn deploy_hash_arb() -> impl Strategy<Value = DeployHash> { array::uniform32(<u8>::arbitrary()).prop_map(DeployHash::new) } pub fn transfer_addr_arb() -> impl Strategy<Value = TransferAddr> { array::uniform32(<u8>::arbitrary()).prop_map(TransferAddr::new) } pub fn transfers_arb(size: impl Into<SizeRange>) -> impl Strategy<Value = Vec<TransferAddr>> { collection::vec(transfer_addr_arb(), size) } pub fn account_hash_arb() -> impl Strategy<Value = AccountHash> { array::uniform32(<u8>::arbitrary()).prop_map(AccountHash::new) } pub fn deploy_info_arb() -> impl Strategy<Value = DeployInfo> { let transfers_length_range = 0..5; ( deploy_hash_arb(), transfers_arb(transfers_length_range), account_hash_arb(), uref_arb(), u512_arb(), ) .prop_map(|(deploy_hash, transfers, from, source, gas)| DeployInfo { deploy_hash, transfers, from, source, gas, }) } } #[cfg(test)] mod tests { use proptest::prelude::*; use crate::bytesrepr; use super::gens; proptest! { #[test] fn test_serialization_
random
[ { "content": "/// Serializes `t` into a `Vec<u8>`.\n\npub fn serialize(t: impl ToBytes) -> Result<Vec<u8>, Error> {\n\n t.into_bytes()\n\n}\n\n\n\npub(crate) fn safe_split_at(bytes: &[u8], n: usize) -> Result<(&[u8], &[u8]), Error> {\n\n if n > bytes.len() {\n\n Err(Error::EarlyEndOfStream)\n\n ...
Rust
wiz/wizc/src/high_level_ir/type_resolver/name_environment.rs
ChanTsune/wiz
199d0f4698822a177ede8015bf8e04f190f39934
use crate::high_level_ir::declaration_id::DeclarationId; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::{EnvValue, ResolverStruct}; use crate::high_level_ir::type_resolver::declaration::DeclarationItemKind; use std::collections::{HashMap, HashSet}; use wiz_hir::typed_type::TypedType; use wiz_utils::StackedHashMap; #[derive(Debug, Clone)] pub(crate) struct NameEnvironment<'a> { local_stack: &'a StackedHashMap<String, EnvValue>, values: HashMap<String, HashSet<DeclarationId>>, arena: &'a ResolverArena, } impl<'a> NameEnvironment<'a> { pub fn new( arena: &'a ResolverArena, local_stack: &'a StackedHashMap<String, EnvValue>, ) -> Self { Self { local_stack, values: Default::default(), arena, } } pub(crate) fn use_asterisk<T: ToString>(&mut self, namespace: &[T]) -> Option<()> { let ns_id = self.arena.resolve_declaration_id_from_root(namespace)?; let ns = self.arena.get_by_id(&ns_id).unwrap(); self.values.extend(ns.children().clone()); Some(()) } pub(crate) fn use_<T: ToString>(&mut self, fqn: &[T]) { if fqn.last().map(T::to_string) == Some("*".to_string()) { self.use_asterisk(&fqn[..fqn.len() - 1]); } else { let item = self.arena.resolve_declaration_id_from_root(fqn).unwrap(); let entry = self .values .entry(fqn.last().unwrap().to_string()) .or_default(); entry.insert(item); } } pub(crate) fn get_type( &self, name_space: Vec<String>, type_name: &str, ) -> Option<&ResolverStruct> { let maybe_type_parameter = match self.local_stack.get(type_name) { Some(EnvValue::Type(id)) => Some(id), _ => None, }; let n = match maybe_type_parameter { None => self.arena.get_type(&name_space, type_name), Some(id) => self.arena.get_type_by_id(id), }; n } pub(crate) fn get_type_by_typed_type(&self, typ: TypedType) -> Option<&ResolverStruct> { self.get_type(typ.package().into_resolved().names, &typ.name()) } pub(crate) fn get_env_item(&self, namespace: &[String], name: &str) -> Option<EnvValue> { if namespace.is_empty() { let maybe_local_value = self.local_stack.get(name).cloned(); match maybe_local_value { None => { let ids = self.values.get(name)?; let ids = ids.iter().collect::<Vec<_>>(); let items = self.arena.get_by_ids(&ids)?; if !items.is_empty() { if let DeclarationItemKind::Type(_) = &items.first().unwrap().kind { return Some(EnvValue::from(**ids.first().unwrap())); } else { let mut values = HashSet::new(); for item in items { if let DeclarationItemKind::Value(v) = &item.kind { values.insert((item.parent().unwrap(), v.clone())); } else { None? } } return Some(EnvValue::from(values)); } }; None } Some(t) => Some(t), } } else { let ids = self.values.get(&namespace[0].to_string())?; let ids = ids.iter().copied().collect::<Vec<_>>(); let parent_id = ids.first()?; let id = self .arena .resolve_declaration_id(*parent_id, &namespace[1..])?; let item = self.arena.get_by_id(&id)?; let child = item.get_child(name)?; let child = child.iter().collect::<Vec<_>>(); let items = self.arena.get_by_ids(&child)?; if !items.is_empty() { if let DeclarationItemKind::Type(_) = &items.first().unwrap().kind { return Some(EnvValue::from(**child.first().unwrap())); } else { let mut values = HashSet::new(); for item in items { if let DeclarationItemKind::Value(v) = &item.kind { values.insert((item.parent().unwrap(), v.clone())); } else { None? } } return Some(EnvValue::from(values)); } }; None } } }
use crate::high_level_ir::declaration_id::DeclarationId; use crate::high_level_ir::type_resolver::arena::ResolverArena; use crate::high_level_ir::type_resolver::context::{EnvValue, ResolverStruct}; use crate::high_level_ir::type_resolver::declaration::DeclarationItemKind; use std::collections::{HashMap, HashSet}; use wiz_hir::typed_type::TypedType; use wiz_utils::StackedHashMap; #[derive(Debug, Clone)] pub(crate) struct NameEnvironment<'a> { local_stack: &'a StackedHashMap<String, EnvValue>, values: HashMap<String, HashSet<DeclarationId>>, arena: &'a ResolverArena, } impl<'a> NameEnvironment<'a> { pub fn new( arena: &'a ResolverArena, local_stack: &'a StackedHashMap<String, EnvValue>, ) -> Self { Self { local_stack, values: Default::defau
return Some(EnvValue::from(values)); } }; None } Some(t) => Some(t), } } else { let ids = self.values.get(&namespace[0].to_string())?; let ids = ids.iter().copied().collect::<Vec<_>>(); let parent_id = ids.first()?; let id = self .arena .resolve_declaration_id(*parent_id, &namespace[1..])?; let item = self.arena.get_by_id(&id)?; let child = item.get_child(name)?; let child = child.iter().collect::<Vec<_>>(); let items = self.arena.get_by_ids(&child)?; if !items.is_empty() { if let DeclarationItemKind::Type(_) = &items.first().unwrap().kind { return Some(EnvValue::from(**child.first().unwrap())); } else { let mut values = HashSet::new(); for item in items { if let DeclarationItemKind::Value(v) = &item.kind { values.insert((item.parent().unwrap(), v.clone())); } else { None? } } return Some(EnvValue::from(values)); } }; None } } }
lt(), arena, } } pub(crate) fn use_asterisk<T: ToString>(&mut self, namespace: &[T]) -> Option<()> { let ns_id = self.arena.resolve_declaration_id_from_root(namespace)?; let ns = self.arena.get_by_id(&ns_id).unwrap(); self.values.extend(ns.children().clone()); Some(()) } pub(crate) fn use_<T: ToString>(&mut self, fqn: &[T]) { if fqn.last().map(T::to_string) == Some("*".to_string()) { self.use_asterisk(&fqn[..fqn.len() - 1]); } else { let item = self.arena.resolve_declaration_id_from_root(fqn).unwrap(); let entry = self .values .entry(fqn.last().unwrap().to_string()) .or_default(); entry.insert(item); } } pub(crate) fn get_type( &self, name_space: Vec<String>, type_name: &str, ) -> Option<&ResolverStruct> { let maybe_type_parameter = match self.local_stack.get(type_name) { Some(EnvValue::Type(id)) => Some(id), _ => None, }; let n = match maybe_type_parameter { None => self.arena.get_type(&name_space, type_name), Some(id) => self.arena.get_type_by_id(id), }; n } pub(crate) fn get_type_by_typed_type(&self, typ: TypedType) -> Option<&ResolverStruct> { self.get_type(typ.package().into_resolved().names, &typ.name()) } pub(crate) fn get_env_item(&self, namespace: &[String], name: &str) -> Option<EnvValue> { if namespace.is_empty() { let maybe_local_value = self.local_stack.get(name).cloned(); match maybe_local_value { None => { let ids = self.values.get(name)?; let ids = ids.iter().collect::<Vec<_>>(); let items = self.arena.get_by_ids(&ids)?; if !items.is_empty() { if let DeclarationItemKind::Type(_) = &items.first().unwrap().kind { return Some(EnvValue::from(**ids.first().unwrap())); } else { let mut values = HashSet::new(); for item in items { if let DeclarationItemKind::Value(v) = &item.kind { values.insert((item.parent().unwrap(), v.clone())); } else { None? } }
random
[ { "content": "pub fn hlir2mlir<'arena>(\n\n target: TypedSourceSet,\n\n dependencies: &'arena [MLFile],\n\n arena: &'arena ResolverArena,\n\n) -> Result<MLFile> {\n\n let mut converter = HLIR2MLIR::new(arena);\n\n converter.load_dependencies(dependencies)?;\n\n Ok(converter.convert_from_source...
Rust
src/net/mod.rs
rusty-io/coio-rs
fc3e1270937175eff8dbe1e2606a413c80c7ec28
pub mod tcp; pub mod udp; #[cfg(unix)] pub mod unix; pub use self::tcp::{TcpListener, TcpStream, Shutdown}; pub use self::udp::UdpSocket; #[cfg(unix)] pub use self::unix::{UnixListener, UnixStream, UnixSocket}; use std::fmt::Debug; use std::io::{self, Read, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::{AsRawFd, RawFd}; use mio::{Evented, EventSet, Token}; use scheduler::{ReadyStates, ReadyType, Scheduler}; #[derive(Debug)] #[doc(hidden)] pub struct GenericEvented<E: Evented + Debug> { inner: E, ready_states: ReadyStates, token: Token, } impl<E: Evented + Debug> GenericEvented<E> { #[doc(hidden)] pub fn new(inner: E, interest: EventSet) -> io::Result<GenericEvented<E>> { let scheduler = try!(Scheduler::instance_or_err()); let (token, ready_states) = try!(scheduler.register(&inner, interest)); Ok(GenericEvented { inner: inner, ready_states: ready_states, token: token, }) } } impl<E: Evented + Debug> Drop for GenericEvented<E> { fn drop(&mut self) { let scheduler = Scheduler::instance().unwrap(); scheduler.deregister(&self.inner, self.token).unwrap(); } } impl<E: Evented + Debug> Deref for GenericEvented<E> { type Target = E; fn deref(&self) -> &Self::Target { &self.inner } } impl<E: Evented + Debug> DerefMut for GenericEvented<E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<E: Evented + Debug + Read> Read for GenericEvented<E> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.read(buf) { Ok(len) => { trace!("GenericEvented({:?}): read() => Ok({})", self.token, len); return Ok(len); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): read() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): read() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): read() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Readable)", self.token); self.ready_states.wait(ReadyType::Readable); sync_guard.disarm(); } } } impl<E: Evented + Debug + Write> Write for GenericEvented<E> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.write(buf) { Ok(len) => { trace!("GenericEvented({:?}): write() => Ok({})", self.token, len); return Ok(len); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): write() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): write() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): write() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Writable)", self.token); self.ready_states.wait(ReadyType::Writable); sync_guard.disarm(); } } fn flush(&mut self) -> io::Result<()> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.flush() { Ok(()) => { trace!("GenericEvented({:?}): write() => Ok(())", self.token); return Ok(()); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): flush() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): flush() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): flush() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Writable)", self.token); self.ready_states.wait(ReadyType::Writable); sync_guard.disarm(); } } } #[cfg(unix)] impl<E: Evented + Debug + AsRawFd> AsRawFd for GenericEvented<E> { fn as_raw_fd(&self) -> RawFd { self.inner.as_raw_fd() } } struct SyncGuard(bool); impl SyncGuard { #[inline] pub fn new() -> SyncGuard { SyncGuard(true) } #[inline] pub fn disarm(&mut self) { self.0 = false; } } impl Drop for SyncGuard { fn drop(&mut self) { if self.0 { Scheduler::sched(); } } } fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> where F: FnMut(&SocketAddr) -> io::Result<T> { let mut last_err = None; for addr in try!(addr.to_socket_addrs()) { match f(&addr) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { io::Error::new(io::ErrorKind::InvalidInput, "could not resolve to any addresses") })) }
pub mod tcp; pub mod udp; #[cfg(unix)] pub mod unix; pub use self::tcp::{TcpListener, TcpStream, Shutdown}; pub use self::udp::UdpSocket; #[cfg(unix)] pub use self::unix::{UnixListener, UnixStream, UnixSocket}; use std::fmt::Debug; use std::io::{self, Read, Write}; use std::net::{SocketAddr, ToSocketAddrs}; use std::ops::{Deref, DerefMut}; #[cfg(unix)] use std::os::unix::io::{AsRawFd, RawFd}; use mio::{Evented, EventSet, Token}; use scheduler::{ReadyStates, ReadyType, Scheduler}; #[derive(Debug)] #[doc(hidden)] pub struct GenericEvented<E: Evented + Debug> { inner: E, ready_states: ReadyStates, token: Token, } impl<E: Evented + Debug> GenericEvented<E> { #[doc(hidden)] pub fn new(inner: E, interest: EventSet) -> io::Result<GenericEvented<E>> { let scheduler = try!(Scheduler::instance_or_err()); let (token, ready_states) = try!(scheduler.register(&inner, interest)); Ok(GenericEvented { inner: inner, ready_states: ready_states, token: token, }) } } impl<E: Evented + Debug> Drop for GenericEvented<E> { fn drop(&mut self) { let scheduler = Scheduler::instance().unwrap(); scheduler.deregister(&self.inner, self.token).unwrap(); } } impl<E: Evented + Debug> Deref for GenericEvented<E> { type Target = E; fn deref(&self) -> &Self::Target { &self.inner } } impl<E: Evented + Debug> DerefMut for GenericEvented<E> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } impl<E: Evented + Debug + Read> Read for GenericEvented<E> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.read(buf) { Ok(len) => { trace!("GenericEvented({:?}): read() => Ok({})", self.token, len); return Ok(len); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): read() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): read() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): read() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Readable)", self.token); self.ready_states.wait(ReadyType::Readable); sync_guard.disarm(); } } } impl<E: Evented + Debug + Write> Write for GenericEvented<E> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.write(buf) { Ok(len) => { trace!("GenericEvented({:?}): write() => Ok({})", self.token, len); return Ok(len); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): write() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): write() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): write() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Writable)", self.token); self.ready_states.wait(ReadyType::Writable); sync_guard.disarm(); } }
} #[cfg(unix)] impl<E: Evented + Debug + AsRawFd> AsRawFd for GenericEvented<E> { fn as_raw_fd(&self) -> RawFd { self.inner.as_raw_fd() } } struct SyncGuard(bool); impl SyncGuard { #[inline] pub fn new() -> SyncGuard { SyncGuard(true) } #[inline] pub fn disarm(&mut self) { self.0 = false; } } impl Drop for SyncGuard { fn drop(&mut self) { if self.0 { Scheduler::sched(); } } } fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> where F: FnMut(&SocketAddr) -> io::Result<T> { let mut last_err = None; for addr in try!(addr.to_socket_addrs()) { match f(&addr) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } } Err(last_err.unwrap_or_else(|| { io::Error::new(io::ErrorKind::InvalidInput, "could not resolve to any addresses") })) }
fn flush(&mut self) -> io::Result<()> { let mut sync_guard = SyncGuard::new(); loop { match self.inner.flush() { Ok(()) => { trace!("GenericEvented({:?}): write() => Ok(())", self.token); return Ok(()); } Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { trace!("GenericEvented({:?}): flush() => WouldBlock", self.token); } Err(ref err) if err.kind() == io::ErrorKind::NotConnected => { trace!("GenericEvented({:?}): flush() => NotConnected", self.token); } Err(err) => { trace!("GenericEvented({:?}): flush() => Err(..)", self.token); return Err(err); } } trace!("GenericEvented({:?}): wait(Writable)", self.token); self.ready_states.wait(ReadyType::Writable); sync_guard.disarm(); } }
function_block-full_function
[ { "content": "type RegisterCallback<'a> = &'a mut FnMut(&mut EventLoop<Scheduler>, Token, ReadyStates) -> bool;\n", "file_path": "src/scheduler.rs", "rank": 0, "score": 256797.86269830115 }, { "content": "type DeregisterCallback<'a> = &'a mut FnMut(&mut EventLoop<Scheduler>);\n\n\n\n#[doc(hi...
Rust
relay-general/src/protocol/exception.rs
rhcarvalho/relay
6f1e81115f1dd82aaf63d242d4e4db754c393a5e
use crate::protocol::{JsonLenientString, Mechanism, RawStacktrace, Stacktrace, ThreadId}; use crate::types::{Annotated, Object, Value}; #[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)] #[metastructure(process_func = "process_exception", value_type = "Exception")] pub struct Exception { #[metastructure(field = "type", max_chars = "symbol")] pub ty: Annotated<String>, #[metastructure(max_chars = "message")] pub value: Annotated<JsonLenientString>, #[metastructure(max_chars = "symbol")] pub module: Annotated<String>, #[metastructure( legacy_alias = "sentry.interfaces.Stacktrace", skip_serialization = "empty" )] pub stacktrace: Annotated<Stacktrace>, #[metastructure(skip_serialization = "empty")] pub raw_stacktrace: Annotated<RawStacktrace>, #[metastructure(max_chars = "enumlike")] pub thread_id: Annotated<ThreadId>, pub mechanism: Annotated<Mechanism>, #[metastructure(additional_properties)] pub other: Object<Value>, } #[test] fn test_exception_roundtrip() { use crate::types::Map; let json = r#"{ "type": "mytype", "value": "myvalue", "module": "mymodule", "thread_id": 42, "other": "value" }"#; let exception = Annotated::new(Exception { ty: Annotated::new("mytype".to_string()), value: Annotated::new("myvalue".to_string().into()), module: Annotated::new("mymodule".to_string()), thread_id: Annotated::new(ThreadId::Int(42)), other: { let mut map = Map::new(); map.insert( "other".to_string(), Annotated::new(Value::String("value".to_string())), ); map }, ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json_pretty().unwrap()); } #[test] fn test_exception_default_values() { let json = r#"{"type":"mytype"}"#; let exception = Annotated::new(Exception { ty: Annotated::new("mytype".to_string()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json().unwrap()); } #[test] fn test_exception_empty_fields() { let json = r#"{"type":"","value":""}"#; let exception = Annotated::new(Exception { ty: Annotated::new("".to_string()), value: Annotated::new("".to_string().into()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json().unwrap()); } #[test] fn test_coerces_object_value_to_string() { let input = r#"{"value":{"unauthorized":true}}"#; let output = r#"{"value":"{\"unauthorized\":true}"}"#; let exception = Annotated::new(Exception { value: Annotated::new(r#"{"unauthorized":true}"#.to_string().into()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(input).unwrap()); assert_eq_str!(output, exception.to_json().unwrap()); } #[test] fn test_explicit_none() { let json = r#"{ "value": null, "type": "ZeroDivisionError" }"#; let exception = Annotated::new(Exception { ty: Annotated::new("ZeroDivisionError".to_string()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!( r#"{"type":"ZeroDivisionError"}"#, exception.to_json().unwrap() ); }
use crate::protocol::{JsonLenientString, Mechanism, RawStacktrace, Stacktrace, ThreadId}; use crate::types::{Annotated, Object, Value}; #[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, ToValue, ProcessValue)] #[metastructure(process_func = "process_exception", value_type = "Exception")] pub struct Exception { #[metastructure(field = "type", max_chars = "symbol")] pub ty: Annotated<String>, #[metastructure(max_chars = "message")] pub value: Annotated<JsonLenientString>, #[metastructure(max_chars = "symbol")] pub module: Annotated<String>, #[metastructure( legacy_alias = "sentry.interfaces.Stacktrace", skip_serialization = "empty" )] pub stacktrace: Annotated<Stacktrace>, #[metastructure(skip_serialization = "empty")] pub raw_stacktrace: Annotated<RawStacktrace>, #[metastructure(max_chars = "enumlike")] pub thread_id: Annotated<ThreadId>, pub mechanism: Annotated<Mechanism>, #[metastructure(additional_properties)] pub other: Object<Value>, } #[test] fn test_exception_roundtrip() { use crate::types::Map; let json = r#"{ "type": "mytype", "value": "myvalue", "module": "mymodule", "thread_id": 42, "other": "value" }"#; let exception = Annotated::new(Exception { ty: Annotated::new("mytype".to_string()), value: Annotated::new("myvalue".to_string().into()), module: Annotated::new("mymodule".to_string()), thread_id: Annotated::new(ThreadId::Int(42)), other: { let mut map = Map::new(); map.insert( "other".to_string(), Annotated::new(Value::String("value".to_string())), ); map }, ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json_pretty().unwrap()); } #[test] fn test_exception_default_values() { let json = r#"{"type":"mytype"}"#; let exception = Annotated::new(Exception { ty: Annotated::new("mytype".to_string()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json().unwrap()); } #[test] fn test_exception_empty_fields() { let json = r#"{"type":"","value":""}"#; let exception = Annotated::new(Exception { ty: Annotated::new("".to_string()), value: Annotated::new("".to_string().into()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!(json, exception.to_json().unwrap()); } #[test] fn test_coerces_object_value_to_string() { let input = r#"{"value":{"unauthorized":true}}"#; let output = r#"{"value":"{\"unauthorized\":true}"}"#; let exception = Annotated::new(Exception { value: Annotated::new(r#"{"unauthorized":true}"#.to_string().into()), ..Default::default() });
#[test] fn test_explicit_none() { let json = r#"{ "value": null, "type": "ZeroDivisionError" }"#; let exception = Annotated::new(Exception { ty: Annotated::new("ZeroDivisionError".to_string()), ..Default::default() }); assert_eq_dbg!(exception, Annotated::from_json(json).unwrap()); assert_eq_str!( r#"{"type":"ZeroDivisionError"}"#, exception.to_json().unwrap() ); }
assert_eq_dbg!(exception, Annotated::from_json(input).unwrap()); assert_eq_str!(output, exception.to_json().unwrap()); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_debug_image_symbolic_default_values() {\n\n let json = r#\"{\n\n \"code_file\": \"CoreFoundation\",\n\n \"debug_id\": \"494f3aea-88fa-4296-9644-fa8ef5d139b6-1234\",\n\n \"image_addr\": \"0x0\",\n\n \"image_size\": 4096,\n\n \"type\": \"symbolic\"\n\n}\"#;\n\n\n\n let ...
Rust
chain-impl-mockchain/benches/tally.rs
bernardoaraujor/chain-libs
715644b517be119eb856ca06893e01edbd777995
use chain_crypto::testing::TestCryptoRng; use chain_impl_mockchain::testing::scenario::template::WalletTemplateBuilder; use chain_impl_mockchain::{ certificate::{ DecryptedPrivateTally, DecryptedPrivateTallyProposal, EncryptedVoteTally, VoteCast, VotePlan, VoteTally, }, fee::LinearFee, header::BlockDate, testing::{ data::CommitteeMembersManager, ledger::ConfigBuilder, scenario::{prepare_scenario, proposal, vote_plan, wallet}, VoteTestGen, }, value::Value, vote::{Choice, PayloadType}, }; use criterion::{criterion_group, criterion_main, Criterion}; use rand::{ distributions::{Distribution, Uniform, WeightedIndex}, Rng, SeedableRng, }; use rayon::prelude::*; const ALICE: &str = "Alice"; const STAKE_POOL: &str = "stake_pool"; const CRS_SEED: &[u8] = b"This should be a shared seed among the different committee members. Could be the id of the previous VotePlan"; const VOTE_PLAN: &str = "fund1"; const MEMBERS_NO: usize = 3; const THRESHOLD: usize = 2; fn tally_benchmark( benchmark_name: &str, n_proposals: usize, voters_count: usize, proposals_per_voter_ratio: f64, yes_votes_ratio: f64, voting_power_distribution: impl Distribution<u64>, c: &mut Criterion, ) { let mut rng = TestCryptoRng::seed_from_u64(0); let mut wallets: Vec<&mut WalletTemplateBuilder> = Vec::new(); let mut alice_wallet_builder = wallet(ALICE); alice_wallet_builder .with(1_000) .owns(STAKE_POOL) .committee_member(); wallets.push(&mut alice_wallet_builder); let voters_aliases: Vec<_> = (1..=voters_count) .map(|counter| format!("voter_{}", counter)) .collect(); let voting_powers: Vec<_> = voting_power_distribution .sample_iter(&mut rng) .take(voters_count) .collect(); let total_votes = voting_powers.iter().sum(); let mut voters_wallets: Vec<_> = voters_aliases .iter() .zip(voting_powers.iter()) .map(|(alias, voting_power)| { let mut wallet_builder = WalletTemplateBuilder::new(alias); wallet_builder.with(*voting_power); wallet_builder }) .collect(); wallets.append(&mut voters_wallets.iter_mut().collect()); let members = CommitteeMembersManager::new(&mut rng, CRS_SEED, THRESHOLD, MEMBERS_NO); let committee_keys: Vec<_> = members .members() .iter() .map(|committee_member| committee_member.public_key()) .collect(); let mut vote_plan_builder = vote_plan(VOTE_PLAN); vote_plan_builder .owner(ALICE) .consecutive_epoch_dates() .payload_type(PayloadType::Private) .committee_keys(committee_keys); for _ in 0..n_proposals { let mut proposal_builder = proposal(VoteTestGen::external_proposal_id()); proposal_builder.options(3).action_off_chain(); vote_plan_builder.with_proposal(&mut proposal_builder); } let (mut ledger, controller) = prepare_scenario() .with_config( ConfigBuilder::new(0) .with_fee(LinearFee::new(0, 0, 0)) .with_rewards(Value(1000)), ) .with_initials(wallets) .with_vote_plans(vec![&mut vote_plan_builder]) .build() .unwrap(); let vote_plan_def = controller.vote_plan(VOTE_PLAN).unwrap(); let vote_plan: VotePlan = vote_plan_def.into(); let mut total_votes_per_proposal = vec![0; n_proposals]; let mut voters_and_powers: Vec<_> = voters_aliases .iter() .map(|alias| controller.wallet(alias).unwrap()) .zip(voting_powers.into_iter()) .collect(); let vote_fragments = { let mut res = Vec::new(); for (proposal_idx, proposal) in vote_plan.proposals().iter().enumerate() { for (private_voter, voting_power) in voters_and_powers.iter_mut() { let should_vote = rng.gen_bool(proposals_per_voter_ratio); if !should_vote { continue; } let choice = Choice::new(rng.gen_bool(yes_votes_ratio) as u8); let payload = VoteTestGen::private_vote_cast_payload_for( &vote_plan, proposal, choice, &mut rng, ); res.push(controller.fragment_factory().vote_cast( BlockDate::first(), private_voter, VoteCast::new(vote_plan.to_id(), proposal_idx as u8, payload), )); total_votes_per_proposal[proposal_idx] += *voting_power; } } res }; let mut vote_casting_bench = c.benchmark_group("vote_casting"); vote_casting_bench.sample_size(10); vote_casting_bench.bench_function(&format!("vote_cast_{}", benchmark_name), |b| { b.iter(|| { let mut ledger = ledger.clone(); for vote in &vote_fragments { ledger.apply_fragment(vote, ledger.date()).unwrap(); } }) }); vote_casting_bench.finish(); for vote in vote_fragments { ledger.apply_fragment(&vote, ledger.date()).unwrap(); } ledger.fast_forward_to(BlockDate { epoch: 1, slot_id: 1, }); let mut alice = controller.wallet(ALICE).unwrap(); let encrypted_tally = EncryptedVoteTally::new(vote_plan.to_id()); let fragment = controller.fragment_factory().vote_encrypted_tally( BlockDate::first(), &alice, encrypted_tally, ); let parameters = ledger.parameters.clone(); let date = ledger.date(); c.bench_function(&format!("vote_encrypted_tally_{}", benchmark_name), |b| { b.iter(|| { ledger .ledger .apply_fragment(&parameters, &fragment, date) .unwrap(); }) }); ledger.apply_fragment(&fragment, ledger.date()).unwrap(); alice.confirm_transaction(); let vote_plans = ledger.ledger.active_vote_plans(); let vote_plan_status = vote_plans .iter() .find(|c_vote_plan| { let vote_plan: VotePlan = vote_plan.clone(); c_vote_plan.id == vote_plan.to_id() }) .unwrap(); c.bench_function(&format!("tally_decrypt_share_{}", benchmark_name), |b| { b.iter(|| { members.members()[0].produce_decrypt_shares(&vote_plan_status); }) }); let mut decrypt_shares_iter: Vec<_> = members .members() .iter() .map(|member| member.produce_decrypt_shares(&vote_plan_status).into_iter()) .collect(); let decrypt_shares: Vec<Vec<_>> = (0..n_proposals) .map(|_| { decrypt_shares_iter .iter_mut() .filter_map(|member_shares| member_shares.next()) .collect() }) .collect(); let decrypt_tally = || { let table = chain_vote::TallyOptimizationTable::generate(total_votes); vote_plan_status .proposals .par_iter() .enumerate() .map(|(i, proposal)| { proposal .tally .clone() .unwrap() .private_encrypted() .unwrap() .0 .validate_partial_decryptions( &vote_plan.committee_public_keys(), &decrypt_shares[i], ) .unwrap() .decrypt_tally(total_votes_per_proposal[i], &table) .unwrap() }) .collect::<Vec<_>>() }; c.bench_function(&format!("decrypt_private_tally_{}", benchmark_name), |b| { b.iter(decrypt_tally) }); let shares = decrypt_tally() .into_iter() .zip(decrypt_shares.into_iter()) .map(|(tally, decrypt_shares)| DecryptedPrivateTallyProposal { decrypt_shares: decrypt_shares.into_boxed_slice(), tally_result: tally.votes.into_boxed_slice(), }) .collect(); let decrypted_tally = VoteTally::new_private(vote_plan.to_id(), DecryptedPrivateTally::new(shares)); let fragment = controller .fragment_factory() .vote_tally(BlockDate::first(), &alice, decrypted_tally); c.bench_function(&format!("vote_tally_{}", benchmark_name), |b| { b.iter(|| { ledger .ledger .apply_fragment(&parameters, &fragment, ledger.date()) .unwrap(); }) }); ledger.apply_fragment(&fragment, ledger.date()).unwrap(); } fn tally_benchmark_flat_distribution( benchmark_name: &str, voters_count: usize, voting_power_per_voter: u64, c: &mut Criterion, ) { let voting_power_distribution = rand::distributions::uniform::Uniform::from( voting_power_per_voter..voting_power_per_voter + 1, ); tally_benchmark( benchmark_name, 1, voters_count, 1.0, 0.5, voting_power_distribution, c, ); } fn tally_benchmark_128_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("128_voters_1000_ada", 128, 1000, c); } fn tally_benchmark_200_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("200_voters_1000_ada", 200, 1000, c); } fn tally_benchmark_200_voters_1_000_000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("200_voters_1_000_000_ada", 200, 1_000_000, c); } fn tally_benchmark_1000_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("1000_voters_1000_ada", 1000, 1000, c); } struct FundDistribution { ranges_no_sampler: WeightedIndex<f64>, ranges_values_samplers: Vec<Uniform<u64>>, } impl FundDistribution { pub fn new(ranges_bounds: &[u64], ranges_weights: &[f64]) -> Self { assert_eq!(ranges_bounds.len(), ranges_weights.len() + 1); let ranges_no_sampler = WeightedIndex::new(ranges_weights).unwrap(); let ranges_values_samplers = ranges_bounds .windows(2) .map(|bounds| Uniform::from(bounds[0]..bounds[1])) .collect(); Self { ranges_no_sampler, ranges_values_samplers, } } } impl Distribution<u64> for FundDistribution { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 { let range_no = self.ranges_no_sampler.sample(rng); self.ranges_values_samplers[range_no].sample(rng) } } fn tally_benchmark_fund3_scenario(c: &mut Criterion) { let voters_count = 15_000; let n_proposals = 150; let proposals_per_voter_ratio = 0.75; let ranges_bounds = &[3_000, 200_000, 1_000_000, 10_000_000]; let ranges_weights = &[0.4, 0.4, 0.2]; let yes_votes_ratio = 0.35; let voting_power_distribution = FundDistribution::new(ranges_bounds, ranges_weights); tally_benchmark( "fund3_scenario", n_proposals, voters_count, proposals_per_voter_ratio, yes_votes_ratio, voting_power_distribution, c, ); } fn tally_benchmark_fund4_scenario(c: &mut Criterion) { let voters_count = 30_000; let n_proposals = 300; let proposals_per_voter_ratio = 0.75; let ranges_bounds = &[3_000, 200_000, 1_000_000, 10_000_000]; let ranges_weights = &[0.4, 0.4, 0.2]; let yes_votes_ratio = 0.35; let voting_power_distribution = FundDistribution::new(ranges_bounds, ranges_weights); tally_benchmark( "fund4_scenario", n_proposals, voters_count, proposals_per_voter_ratio, yes_votes_ratio, voting_power_distribution, c, ); } criterion_group!( fast_bench, tally_benchmark_128_voters_1000_ada, tally_benchmark_200_voters_1000_ada, tally_benchmark_200_voters_1_000_000_ada, tally_benchmark_1000_voters_1000_ada, ); criterion_group!( big_bench, tally_benchmark_fund3_scenario, tally_benchmark_fund4_scenario, ); criterion_main!(fast_bench, big_bench);
use chain_crypto::testing::TestCryptoRng; use chain_impl_mockchain::testing::scenario::template::WalletTemplateBuilder; use chain_impl_mockchain::{ certificate::{ DecryptedPrivateTally, DecryptedPrivateTallyProposal, EncryptedVoteTally, VoteCast, VotePlan, VoteTally, }, fee::LinearFee, header::BlockDate, testing::{ data::CommitteeMembersManager, ledger::ConfigBuilder, scenario::{prepare_scenario, proposal, vote_plan, wallet}, VoteTestGen, }, value::Value, vote::{Choice, PayloadType}, }; use criterion::{criterion_group, criterion_main, Criterion}; use rand::{ distributions::{Distribution, Uniform, WeightedIndex}, Rng, SeedableRng, }; use rayon::prelude::*; const ALICE: &str = "Alice"; const STAKE_POOL: &str = "stake_pool"; const CRS_SEED: &[u8] = b"This should be a shared seed among the different committee members. Could be the id of the previous VotePlan"; const VOTE_PLAN: &str = "fund1"; const MEMBERS_NO: usize = 3; const THRESHOLD: usize = 2; fn tally_benchmark( benchmark_name: &str, n_proposals: usize, voters_count: usize, proposals_per_voter_ratio: f64, yes_votes_ratio: f64, voting_power_distribution: impl Distribution<u64>, c: &mut Criterion, ) { let mut rng = TestCryptoRng::seed_from_u64(0); let mut wallets: Vec<&mut WalletTemplateBuilder> = Vec::new(); let mut alice_wallet_builder = wallet(ALICE); alice_wallet_builder .with(1_000) .owns(STAKE_POOL) .committee_member(); wallets.push(&mut alice_wallet_builder); let voters_aliases: Vec<_> = (1..=voters_count) .map(|counter| format!("voter_{}", counter)) .collect(); let voting_powers: Vec<_> = voting_power_distribution .sample_iter(&mut rng) .take(voters_count) .collect(); let total_votes = voting_powers.iter().sum(); let mut voters_wallets: Vec<_> = voters_aliases .iter() .zip(voting_powers.iter()) .map(|(alias, voting_power)| { let mut wallet_builder = WalletTemplateBuilder::new(alias); wallet_builder.with(*voting_power); wallet_builder }) .collect(); wallets.append(&mut voters_wallets.iter_mut().collect()); let members = CommitteeMembersManager::new(&mut rng, CRS_SEED, THRESHOLD, MEMBERS_NO); let committee_keys: Vec<_> = members .members() .iter() .map(|committee_member| committee_member.public_key()) .collect(); let mut vote_plan_builder = vote_plan(VOTE_PLAN); vote_plan_builder .owner(ALICE) .consecutive_epoch_dates() .payload_type(PayloadType::Private) .committee_keys(committee_keys); for _ in 0..n_proposals { let mut proposal_builder = proposal(VoteTestGen::external_proposal_id()); proposal_builder.options(3).action_off_chain(); vote_plan_builder.with_proposal(&mut proposal_builder); } let (mut ledger, controller) = prepare_scenario() .with_config( ConfigBuilder::new(0) .with_fee(LinearFee::new(0, 0, 0)) .with_rewards(Value(1000)), ) .with_initials(wallets) .with_vote_plans(vec![&mut vote_plan_builder]) .build() .unwrap(); let vote_plan_def = controller.vote_plan(VOTE_PLAN).unwrap(); let vote_plan: VotePlan = vote_plan_def.into(); let mut total_votes_per_proposal = vec![0; n_proposals]; let mut voters_and_powers: Vec<_> = voters_aliases .iter() .map(|alias| controller.wallet(alias).unwrap()) .zip(voting_powers.into_iter()) .collect(); let vote_fragments = { let mut res = Vec::new(); for (proposal_idx, proposal) in vote_plan.proposals().iter().enumerate() { for (private_voter, voting_power) in voters_and_powers.iter_mut() { let should_vote = rng.gen_bool(proposals_per_voter_ratio); if !should_vote { continue; } let choice = Choice::new(rng.gen_bool(yes_votes_ratio) as u8); let payload = VoteTestGen::private_vote_cast_payload_for( &vote_plan, proposal, choice, &mut rng, ); res.push(controller.fragment_factory().vote_cast( BlockDate::first(), private_voter, VoteCast::new(vote_plan.to_id(), proposal_idx as u8, payload), )); total_votes_per_proposal[proposal_idx] += *voting_power; }
edger .apply_fragment(&parameters, &fragment, date) .unwrap(); }) }); ledger.apply_fragment(&fragment, ledger.date()).unwrap(); alice.confirm_transaction(); let vote_plans = ledger.ledger.active_vote_plans(); let vote_plan_status = vote_plans .iter() .find(|c_vote_plan| { let vote_plan: VotePlan = vote_plan.clone(); c_vote_plan.id == vote_plan.to_id() }) .unwrap(); c.bench_function(&format!("tally_decrypt_share_{}", benchmark_name), |b| { b.iter(|| { members.members()[0].produce_decrypt_shares(&vote_plan_status); }) }); let mut decrypt_shares_iter: Vec<_> = members .members() .iter() .map(|member| member.produce_decrypt_shares(&vote_plan_status).into_iter()) .collect(); let decrypt_shares: Vec<Vec<_>> = (0..n_proposals) .map(|_| { decrypt_shares_iter .iter_mut() .filter_map(|member_shares| member_shares.next()) .collect() }) .collect(); let decrypt_tally = || { let table = chain_vote::TallyOptimizationTable::generate(total_votes); vote_plan_status .proposals .par_iter() .enumerate() .map(|(i, proposal)| { proposal .tally .clone() .unwrap() .private_encrypted() .unwrap() .0 .validate_partial_decryptions( &vote_plan.committee_public_keys(), &decrypt_shares[i], ) .unwrap() .decrypt_tally(total_votes_per_proposal[i], &table) .unwrap() }) .collect::<Vec<_>>() }; c.bench_function(&format!("decrypt_private_tally_{}", benchmark_name), |b| { b.iter(decrypt_tally) }); let shares = decrypt_tally() .into_iter() .zip(decrypt_shares.into_iter()) .map(|(tally, decrypt_shares)| DecryptedPrivateTallyProposal { decrypt_shares: decrypt_shares.into_boxed_slice(), tally_result: tally.votes.into_boxed_slice(), }) .collect(); let decrypted_tally = VoteTally::new_private(vote_plan.to_id(), DecryptedPrivateTally::new(shares)); let fragment = controller .fragment_factory() .vote_tally(BlockDate::first(), &alice, decrypted_tally); c.bench_function(&format!("vote_tally_{}", benchmark_name), |b| { b.iter(|| { ledger .ledger .apply_fragment(&parameters, &fragment, ledger.date()) .unwrap(); }) }); ledger.apply_fragment(&fragment, ledger.date()).unwrap(); } fn tally_benchmark_flat_distribution( benchmark_name: &str, voters_count: usize, voting_power_per_voter: u64, c: &mut Criterion, ) { let voting_power_distribution = rand::distributions::uniform::Uniform::from( voting_power_per_voter..voting_power_per_voter + 1, ); tally_benchmark( benchmark_name, 1, voters_count, 1.0, 0.5, voting_power_distribution, c, ); } fn tally_benchmark_128_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("128_voters_1000_ada", 128, 1000, c); } fn tally_benchmark_200_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("200_voters_1000_ada", 200, 1000, c); } fn tally_benchmark_200_voters_1_000_000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("200_voters_1_000_000_ada", 200, 1_000_000, c); } fn tally_benchmark_1000_voters_1000_ada(c: &mut Criterion) { tally_benchmark_flat_distribution("1000_voters_1000_ada", 1000, 1000, c); } struct FundDistribution { ranges_no_sampler: WeightedIndex<f64>, ranges_values_samplers: Vec<Uniform<u64>>, } impl FundDistribution { pub fn new(ranges_bounds: &[u64], ranges_weights: &[f64]) -> Self { assert_eq!(ranges_bounds.len(), ranges_weights.len() + 1); let ranges_no_sampler = WeightedIndex::new(ranges_weights).unwrap(); let ranges_values_samplers = ranges_bounds .windows(2) .map(|bounds| Uniform::from(bounds[0]..bounds[1])) .collect(); Self { ranges_no_sampler, ranges_values_samplers, } } } impl Distribution<u64> for FundDistribution { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 { let range_no = self.ranges_no_sampler.sample(rng); self.ranges_values_samplers[range_no].sample(rng) } } fn tally_benchmark_fund3_scenario(c: &mut Criterion) { let voters_count = 15_000; let n_proposals = 150; let proposals_per_voter_ratio = 0.75; let ranges_bounds = &[3_000, 200_000, 1_000_000, 10_000_000]; let ranges_weights = &[0.4, 0.4, 0.2]; let yes_votes_ratio = 0.35; let voting_power_distribution = FundDistribution::new(ranges_bounds, ranges_weights); tally_benchmark( "fund3_scenario", n_proposals, voters_count, proposals_per_voter_ratio, yes_votes_ratio, voting_power_distribution, c, ); } fn tally_benchmark_fund4_scenario(c: &mut Criterion) { let voters_count = 30_000; let n_proposals = 300; let proposals_per_voter_ratio = 0.75; let ranges_bounds = &[3_000, 200_000, 1_000_000, 10_000_000]; let ranges_weights = &[0.4, 0.4, 0.2]; let yes_votes_ratio = 0.35; let voting_power_distribution = FundDistribution::new(ranges_bounds, ranges_weights); tally_benchmark( "fund4_scenario", n_proposals, voters_count, proposals_per_voter_ratio, yes_votes_ratio, voting_power_distribution, c, ); } criterion_group!( fast_bench, tally_benchmark_128_voters_1000_ada, tally_benchmark_200_voters_1000_ada, tally_benchmark_200_voters_1_000_000_ada, tally_benchmark_1000_voters_1000_ada, ); criterion_group!( big_bench, tally_benchmark_fund3_scenario, tally_benchmark_fund4_scenario, ); criterion_main!(fast_bench, big_bench);
} res }; let mut vote_casting_bench = c.benchmark_group("vote_casting"); vote_casting_bench.sample_size(10); vote_casting_bench.bench_function(&format!("vote_cast_{}", benchmark_name), |b| { b.iter(|| { let mut ledger = ledger.clone(); for vote in &vote_fragments { ledger.apply_fragment(vote, ledger.date()).unwrap(); } }) }); vote_casting_bench.finish(); for vote in vote_fragments { ledger.apply_fragment(&vote, ledger.date()).unwrap(); } ledger.fast_forward_to(BlockDate { epoch: 1, slot_id: 1, }); let mut alice = controller.wallet(ALICE).unwrap(); let encrypted_tally = EncryptedVoteTally::new(vote_plan.to_id()); let fragment = controller.fragment_factory().vote_encrypted_tally( BlockDate::first(), &alice, encrypted_tally, ); let parameters = ledger.parameters.clone(); let date = ledger.date(); c.bench_function(&format!("vote_encrypted_tally_{}", benchmark_name), |b| { b.iter(|| { ledger .l
random
[]
Rust
src/resp2/encode.rs
marius-meissner/redis-protocol.rs
e68cee7ca0b74666e0cdbd91fce32087caeed84e
use crate::resp2::types::*; use crate::resp2::utils::{self as resp2_utils}; use crate::types::{RedisProtocolError, CRLF}; use crate::utils; use crate::alloc::string::ToString; use alloc::vec::Vec; use bytes::BytesMut; use cookie_factory::GenError; fn gen_simplestring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::simplestring_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::SimpleString.to_byte()) >> gen_slice!(data) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_error<'a>(x: (&'a mut [u8], usize), data: &str) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::error_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::Error.to_byte()) >> gen_slice!(data.as_bytes()) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_integer<'a>(x: (&'a mut [u8], usize), data: &i64) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::integer_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::Integer.to_byte()) >> gen_slice!(data.to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_bulkstring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::bulkstring_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::BulkString.to_byte()) >> gen_slice!(data.len().to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) >> gen_slice!(data) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_null(x: (&mut [u8], usize)) -> Result<(&mut [u8], usize), GenError> { encode_checks!(x, NULL.as_bytes().len()); do_gen!(x, gen_slice!(NULL.as_bytes())) } fn gen_array<'a>(x: (&'a mut [u8], usize), data: &Vec<Frame>) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::array_encode_len(data)?); let mut x = do_gen!( x, gen_be_u8!(FrameKind::Array.to_byte()) >> gen_slice!(data.len().to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) )?; for frame in data.iter() { x = match frame { Frame::SimpleString(ref s) => gen_simplestring(x, &s)?, Frame::BulkString(ref b) => gen_bulkstring(x, &b)?, Frame::Null => gen_null(x)?, Frame::Error(ref s) => gen_error(x, s)?, Frame::Array(ref frames) => gen_array(x, frames)?, Frame::Integer(ref i) => gen_integer(x, i)?, }; } Ok(x) } fn attempt_encoding(buf: &mut [u8], offset: usize, frame: &Frame) -> Result<usize, GenError> { match *frame { Frame::BulkString(ref b) => gen_bulkstring((buf, offset), b).map(|(_, l)| l), Frame::Null => gen_null((buf, offset)).map(|(_, l)| l), Frame::Array(ref frames) => gen_array((buf, offset), frames).map(|(_, l)| l), Frame::Error(ref s) => gen_error((buf, offset), s).map(|(_, l)| l), Frame::SimpleString(ref s) => gen_simplestring((buf, offset), s).map(|(_, l)| l), Frame::Integer(ref i) => gen_integer((buf, offset), i).map(|(_, l)| l), } } pub fn encode(buf: &mut [u8], offset: usize, frame: &Frame) -> Result<usize, RedisProtocolError> { attempt_encoding(buf, offset, frame).map_err(|e| e.into()) } pub fn encode_bytes(buf: &mut BytesMut, frame: &Frame) -> Result<usize, RedisProtocolError> { let offset = buf.len(); loop { match attempt_encoding(buf, offset, frame) { Ok(size) => return Ok(size), Err(e) => match e { GenError::BufferTooSmall(amt) => utils::zero_extend(buf, amt), _ => return Err(e.into()), }, } } } #[cfg(test)] mod tests { use super::*; use crate::utils::*; const PADDING: &'static str = "foobar"; fn encode_and_verify_empty(input: &Frame, expected: &str) { let mut buf = BytesMut::new(); let len = match encode_bytes(&mut buf, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; assert_eq!(buf, expected.as_bytes(), "empty buf contents match"); assert_eq!(len, expected.as_bytes().len(), "empty expected len is correct"); } fn encode_and_verify_non_empty(input: &Frame, expected: &str) { let mut buf = BytesMut::new(); buf.extend_from_slice(PADDING.as_bytes()); let len = match encode_bytes(&mut buf, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; let padded = vec![PADDING, expected].join(""); assert_eq!(buf, padded.as_bytes(), "padded buf contents match"); assert_eq!(len, padded.as_bytes().len(), "padded expected len is correct"); } fn encode_raw_and_verify_empty(input: &Frame, expected: &str) { let mut buf = Vec::from(&ZEROED_KB[0..expected.as_bytes().len()]); let len = match encode(&mut buf, 0, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; assert_eq!(buf, expected.as_bytes(), "empty buf contents match"); assert_eq!(len, expected.as_bytes().len(), "empty expected len is correct"); } #[test] fn should_encode_llen_req_example() { let expected = "*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"; let input = Frame::Array(vec![ Frame::BulkString("LLEN".into()), Frame::BulkString("mylist".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_incr_req_example() { let expected = "*2\r\n$4\r\nINCR\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("INCR".into()), Frame::BulkString("mykey".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_bitcount_req_example() { let expected = "*2\r\n$8\r\nBITCOUNT\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("BITCOUNT".into()), Frame::BulkString("mykey".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_array_bulk_string_test() { let expected = "*3\r\n$5\r\nWATCH\r\n$6\r\nWIBBLE\r\n$9\r\nfooBARbaz\r\n"; let input = Frame::Array(vec![ Frame::BulkString("WATCH".into()), Frame::BulkString("WIBBLE".into()), Frame::BulkString("fooBARbaz".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_array_null_test() { let expected = "*3\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$-1\r\n"; let input = Frame::Array(vec![ Frame::BulkString("HSET".into()), Frame::BulkString("foo".into()), Frame::Null, ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_raw_llen_req_example() { let expected = "*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"; let input = Frame::Array(vec![ Frame::BulkString("LLEN".into()), Frame::BulkString("mylist".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_incr_req_example() { let expected = "*2\r\n$4\r\nINCR\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("INCR".into()), Frame::BulkString("mykey".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_bitcount_req_example() { let expected = "*2\r\n$8\r\nBITCOUNT\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("BITCOUNT".into()), Frame::BulkString("mykey".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_array_bulk_string_test() { let expected = "*3\r\n$5\r\nWATCH\r\n$6\r\nWIBBLE\r\n$9\r\nfooBARbaz\r\n"; let input = Frame::Array(vec![ Frame::BulkString("WATCH".into()), Frame::BulkString("WIBBLE".into()), Frame::BulkString("fooBARbaz".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_array_null_test() { let expected = "*3\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$-1\r\n"; let input = Frame::Array(vec![ Frame::BulkString("HSET".into()), Frame::BulkString("foo".into()), Frame::Null, ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_moved_error() { let expected = "-MOVED 3999 127.0.0.1:6381\r\n"; let input = Frame::Error("MOVED 3999 127.0.0.1:6381".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_ask_error() { let expected = "-ASK 3999 127.0.0.1:6381\r\n"; let input = Frame::Error("ASK 3999 127.0.0.1:6381".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_error() { let expected = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"; let input = Frame::Error("WRONGTYPE Operation against a key holding the wrong kind of value".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_simplestring() { let expected = "+OK\r\n"; let input = Frame::SimpleString("OK".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_integer() { let i1_expected = ":1000\r\n"; let i1_input = Frame::Integer(1000); encode_and_verify_empty(&i1_input, i1_expected); encode_and_verify_non_empty(&i1_input, i1_expected); } #[test] fn should_encode_negative_integer() { let i2_expected = ":-1000\r\n"; let i2_input = Frame::Integer(-1000); encode_and_verify_empty(&i2_input, i2_expected); encode_and_verify_non_empty(&i2_input, i2_expected); } }
use crate::resp2::types::*; use crate::resp2::utils::{self as resp2_utils}; use crate::types::{RedisProtocolError, CRLF}; use crate::utils; use crate::alloc::string::ToString; use alloc::vec::Vec; use bytes::BytesMut; use cookie_factory::GenError; fn gen_simplestring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::simplestring_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::SimpleString.to_byte()) >> gen_slice!(data) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_error<'a>(x: (&'a mut [u8], usize), data: &str) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::error_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::Error.to_byte()) >> gen_slice!(data.as_bytes()) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_integer<'a>(x: (&'a mut [u8], usize), data: &i64) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::integer_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::Integer.to_byte()) >> gen_slice!(data.to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_bulkstring<'a>(x: (&'a mut [u8], usize), data: &[u8]) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::bulkstring_encode_len(data)); do_gen!( x, gen_be_u8!(FrameKind::BulkString.to_byte()) >> gen_slice!(data.len().to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) >> gen_slice!(data) >> gen_slice!(CRLF.as_bytes()) ) } fn gen_null(x: (&mut [u8], usize)) -> Result<(&mut [u8], usize), GenError> { encode_checks!(x, NULL.as_bytes().len()); do_gen!(x, gen_slice!(NULL.as_bytes())) } fn gen_array<'a>(x: (&'a mut [u8], usize), data: &Vec<Frame>) -> Result<(&'a mut [u8], usize), GenError> { encode_checks!(x, resp2_utils::array_encode_len(data)?); let mut x = do_gen!( x, gen_be_u8!(FrameKind::Array.to_byte()) >> gen_slice!(data.len().to_string().as_bytes()) >> gen_slice!(CRLF.as_bytes()) )?; for frame in data.iter() { x = match frame { Frame::SimpleString(ref s) => gen_simplestring(x, &s)?, Frame::BulkString(ref b) => gen_bulkstring(x, &b)?, Frame::Null => gen_null(x)?, Frame::Error(ref s) => gen_error(x, s)?, Frame::Array(ref frames) => gen_array(x, frames)?, Frame::Integer(ref i) => gen_integer(x, i)?, }; } Ok(x) } fn attempt_encoding(buf: &mut [u8], offset: usize, frame: &Frame) -> Result<usize, GenError> { match *frame { Frame::BulkString(ref b) => gen_bulkstring((buf, offset), b).map(|(_, l)| l), Frame::Null => gen_null((buf, offset)).map(|(_, l)| l), Frame::Array(ref frames) => gen_array((buf, offset), frames).map(|(_, l)| l), Frame::Error(ref s) => gen_error((buf, offset), s).map(|(_, l)| l), Frame::SimpleString(ref s) => gen_simplestring((buf, offset), s).map(|(_, l)| l), Frame::Integer(ref i) => gen_integer((buf, offset), i).map(|(_, l)| l), } } pub fn encode(buf: &mut [u8], offset: usize, frame: &Frame) -> Result<usize, RedisProtocolError> { attempt_encoding(buf, offset, frame).map_err(|e| e.into()) } pub fn encode_bytes(buf: &mut BytesMut, frame: &Frame) -> Result<usize, RedisProtocolError> { let offset = buf.len(); loop { match attempt_encoding(buf, offset, frame) { Ok(size) => return Ok(size), Err(e) => match e { GenError::BufferTooSmall(amt) => utils::zero_extend(buf, amt), _ => return Err(e.into()), }, } } } #[cfg(test)] mod tests { use super::*; use crate::utils::*; const PADDING: &'static str = "foobar"; fn encode_and_verify_empty(input: &Frame, expected: &str) { let mut buf = BytesMut::new(); let len = match encode_bytes(&mut buf, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; assert_eq!(buf, expected.as_bytes(), "empty buf contents match"); assert_eq!(len, expected.as_bytes().len(), "empty expected len is correct"); } fn encode_and_verify_non_empty(input: &Frame, expected: &str) { let mut buf = BytesMut::new(); buf.extend_from_slice(PADDING.as_bytes()); let len = match encode_bytes(&mut buf, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; let padded = vec![PADDING, expected].join(""); assert_eq!(buf, padded.as_bytes(), "padded buf contents match"); assert_eq!(len, padded.as_bytes().len(), "padded expected len is correct"); } fn encode_raw_and_verify_empty(input: &Frame, expected: &str) { let mut buf = Vec::from(&ZEROED_KB[0..expected.as_bytes().len()]); let len = match encode(&mut buf, 0, input) { Ok(l) => l, Err(e) => panic!("{:?}", e), }; assert_eq!(buf, expected.as_bytes(), "empty buf contents match"); assert_eq!(len, expected.as_bytes().len(), "empty expected len is correct"); } #[test] fn should_encode_llen_req_example() { let expected = "*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"; let input = Frame::Array(vec![ Frame::BulkString("LLEN".into()), Frame::BulkString("mylist".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_incr_req_example() { let expected = "*2\r\n$4\r\nINCR\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("INCR".into()), Frame::BulkString("mykey".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_bitcount_req_example() { let expected = "*2\r\n$8\r\nBITCOUNT\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("BITCOUNT".into()), Frame::BulkString("mykey".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_array_bulk_string_test() { let expected = "*3\r\n$5\r\nWATCH\r\n$6\r\nWIBBLE\r\n$9\r\nfooBARbaz\r\n"; let input = Frame::Array(vec![ Frame::BulkString("WATCH".into()), Frame::BulkString("WIBBLE".into()), Frame::BulkString("fooBARbaz".into()), ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_array_null_test() { let expected = "*3\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$-1\r\n"; let input = Frame::Array(vec![ Frame::BulkString("HSET".into()), Frame::BulkString("foo".into()), Frame::Null, ]); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_raw_llen_req_example() { let expecte
#[test] fn should_encode_raw_incr_req_example() { let expected = "*2\r\n$4\r\nINCR\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("INCR".into()), Frame::BulkString("mykey".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_bitcount_req_example() { let expected = "*2\r\n$8\r\nBITCOUNT\r\n$5\r\nmykey\r\n"; let input = Frame::Array(vec![ Frame::BulkString("BITCOUNT".into()), Frame::BulkString("mykey".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_array_bulk_string_test() { let expected = "*3\r\n$5\r\nWATCH\r\n$6\r\nWIBBLE\r\n$9\r\nfooBARbaz\r\n"; let input = Frame::Array(vec![ Frame::BulkString("WATCH".into()), Frame::BulkString("WIBBLE".into()), Frame::BulkString("fooBARbaz".into()), ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_raw_array_null_test() { let expected = "*3\r\n$4\r\nHSET\r\n$3\r\nfoo\r\n$-1\r\n"; let input = Frame::Array(vec![ Frame::BulkString("HSET".into()), Frame::BulkString("foo".into()), Frame::Null, ]); encode_raw_and_verify_empty(&input, expected); } #[test] fn should_encode_moved_error() { let expected = "-MOVED 3999 127.0.0.1:6381\r\n"; let input = Frame::Error("MOVED 3999 127.0.0.1:6381".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_ask_error() { let expected = "-ASK 3999 127.0.0.1:6381\r\n"; let input = Frame::Error("ASK 3999 127.0.0.1:6381".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_error() { let expected = "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n"; let input = Frame::Error("WRONGTYPE Operation against a key holding the wrong kind of value".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_simplestring() { let expected = "+OK\r\n"; let input = Frame::SimpleString("OK".into()); encode_and_verify_empty(&input, expected); encode_and_verify_non_empty(&input, expected); } #[test] fn should_encode_integer() { let i1_expected = ":1000\r\n"; let i1_input = Frame::Integer(1000); encode_and_verify_empty(&i1_input, i1_expected); encode_and_verify_non_empty(&i1_input, i1_expected); } #[test] fn should_encode_negative_integer() { let i2_expected = ":-1000\r\n"; let i2_input = Frame::Integer(-1000); encode_and_verify_empty(&i2_input, i2_expected); encode_and_verify_non_empty(&i2_input, i2_expected); } }
d = "*2\r\n$4\r\nLLEN\r\n$6\r\nmylist\r\n"; let input = Frame::Array(vec![ Frame::BulkString("LLEN".into()), Frame::BulkString("mylist".into()), ]); encode_raw_and_verify_empty(&input, expected); }
function_block-function_prefixed
[ { "content": "fn attempt_encoding<'a>(buf: &'a mut [u8], offset: usize, frame: &Frame) -> Result<(&'a mut [u8], usize), GenError> {\n\n use crate::resp3::types::Frame::*;\n\n\n\n let x = (buf, offset);\n\n let total_size = resp3_utils::encode_len(frame)?;\n\n trace!(\"Attempting to encode {:?} with total si...
Rust
src/bin/run.rs
Pilyushkin/onnxruntime-rs
72da91d9ec56fb80e1528520e74a04ec3a4d2274
use std::ffi::CStr; use std::time::{Duration, Instant}; use onnxruntime::*; use structopt::{clap, StructOpt}; #[structopt( name = "run", about = "Run a benchmark on an onnx model. Each worker runs the model in a loop in its own thead. Once done it will print the average time to run the model.", setting = clap::AppSettings::ColoredHelp )] #[derive(StructOpt)] struct Opt { onnx: Vec<String>, #[structopt(long)] dims: Option<String>, #[structopt(long, default_value = "1")] workers: usize, #[structopt(long, default_value = "1")] runs: usize, } use std::collections::HashMap; fn key_val_parse(str: &str) -> HashMap<String, usize> { let mut map = HashMap::new(); if str.is_empty() { return map; } for key_val in str.split(',') { let mut iter = key_val.split('='); let key = iter.next().expect("no ="); let val = iter .next() .expect("nothing after =") .parse() .expect("parse error"); assert!(iter.next().is_none(), "more than 1 ="); map.insert(key.to_owned(), val); } map } fn tensor_size( info: &TensorInfo, named_sizes: &mut HashMap<String, usize>, ) -> (OnnxTensorElementDataType, Vec<usize>) { let dims = info .symbolic_dims() .map(|d| match d { SymbolicDim::Symbolic(name) => { let name = name.to_str().unwrap(); named_sizes.get(name).cloned().unwrap_or_else(|| { eprintln!("name {} not specified, setting to 1", name); named_sizes.insert(name.to_owned(), 1); 1 }) } SymbolicDim::Fixed(x) => x, }) .collect(); (info.elem_type(), dims) } fn tensor_mut(elem_type: OnnxTensorElementDataType, dims: &[usize]) -> Box<dyn AsMut<Val>> { use OnnxTensorElementDataType::*; match elem_type { Float => Box::new(Tensor::<f32>::init(dims, 0.0).unwrap()), Int64 => Box::new(Tensor::<i64>::init(dims, 0).unwrap()), Int32 => Box::new(Tensor::<i32>::init(dims, 0).unwrap()), t => panic!("Unsupported type {:?}", t), } } fn tensor_with_size( info: &TensorInfo, named_sizes: &mut HashMap<String, usize>, ) -> Box<dyn AsRef<Val>> { let (ty, dims) = tensor_size(info, named_sizes); use OnnxTensorElementDataType::*; match ty { Float => Box::new(Tensor::<f32>::init(&dims, 0.0).unwrap()), Int64 => Box::new(Tensor::<i64>::init(&dims, 0).unwrap()), Int32 => Box::new(Tensor::<i32>::init(&dims, 0).unwrap()), t => panic!("Unsupported type {:?}", t), } } fn main() -> Result<()> { let env = Env::new(LoggingLevel::Fatal, "test")?; let opt = Opt::from_args(); let so = SessionOptions::new()?; let mut map = if let Some(dims) = &opt.dims { key_val_parse(dims) } else { HashMap::new() }; for path in &opt.onnx { println!("model {:?}", path); let session = match Session::new(&env, path, &so) { Ok(sess) => sess, Err(err) => { eprintln!("error: {}\n", err); continue; } }; let metadata = session.metadata(); eprintln!("name: {}", metadata.producer_name()); eprintln!("graph_name: {}", metadata.graph_name()); eprintln!("domain: {}", metadata.domain()); eprintln!("description: {}", metadata.description()); let mut input_names: Vec<OrtString> = vec![]; let mut input_tensors: Vec<Box<dyn AsRef<Val>>> = vec![]; for (i, input) in session.inputs().enumerate() { if let Some(tensor_info) = input.tensor_info() { input_names.push(input.name()); input_tensors.push(tensor_with_size(&tensor_info, &mut map)); } else { println!("input {}: {:?} {:?}", i, &*input.name(), input.onnx_type()); } } let mut output_names: Vec<OrtString> = vec![]; let mut output_sizes: Vec<(OnnxTensorElementDataType, Vec<usize>)> = vec![]; for (i, output) in session.outputs().enumerate() { if let Some(tensor_info) = output.tensor_info() { output_names.push(output.name()); output_sizes.push(tensor_size(&tensor_info, &mut map)); } else { println!( "output {}: {:?} {:?}", i, &*output.name(), output.onnx_type() ); } } let in_names: Vec<&CStr> = input_names.iter().map(|x| x.as_c_str()).collect(); let in_vals: Vec<&Val> = input_tensors.iter().map(|x| x.as_ref().as_ref()).collect(); let out_names: Vec<&CStr> = output_names.iter().map(|x| x.as_c_str()).collect(); crossbeam::scope(|s| { let mut workers = vec![]; for i in 0..opt.workers { let i = std::sync::Arc::new(i); workers.push(s.spawn(|_| { let i = i; let ro = RunOptions::new(); let mut output_tensors: Vec<_> = output_sizes .iter() .map(|(elem_type, size)| tensor_mut(*elem_type, size)) .collect(); let mut out_vals: Vec<&mut Val> = output_tensors .iter_mut() .map(|x| x.as_mut().as_mut()) .collect(); session .run_mut(&ro, &in_names, &in_vals[..], &out_names, &mut out_vals[..]) .expect("run"); let mut times = vec![]; for _ in 0..opt.runs { let before = Instant::now(); session .run_mut(&ro, &in_names, &in_vals[..], &out_names, &mut out_vals[..]) .expect("run"); times.push(before.elapsed()); } let total: Duration = times.iter().sum(); let avg = total / (times.len() as u32); eprintln!("worker {} avg time: {:.2} ms", i, avg.as_secs_f64() * 1e3); })); } workers.into_iter().for_each(|j| j.join().unwrap()); }) .unwrap(); } Ok(()) }
use std::ffi::CStr; use std::time::{Duration, Instant}; use onnxruntime::*; use structopt::{clap, StructOpt}; #[structopt( name = "run", about = "Run a benchmark on an onnx model. Each worker runs the model in a loop in its own thead. Once done it will print the average time to run the model.", setting = clap::AppSettings::ColoredHelp )] #[derive(StructOpt)] struct Opt { onnx: Vec<String>, #[structopt(long)] dims: Option<String>, #[structopt(long, default_value = "1")] workers: usize, #[structopt(long, default_value = "1")] runs: usize, } use std::collections::HashMap; fn key_val_parse(str: &str) -> HashMap<String, usize> { let mut map = HashMap::new(); if str.is_empty() { return map; } for key_val in str.split(',') { let mut iter = key_val.split('='); let key = iter.next().expect("no ="); let val = iter .next() .expect("nothing after =") .parse() .expect("parse error"); assert!(iter.next().is_none(), "more than 1 ="); map.insert(key.to_owned(), val); } map } fn tensor_size( info: &TensorInfo, named_sizes: &mut HashMap<String, usize>, ) -> (OnnxTensorElementDataType, Vec<usize>) { let dims = info .symbolic_dims() .map(|d| match d { SymbolicDim::Symbolic(name) => { let name = name.to_str().unwrap(); named_sizes.get(name).cloned().unwrap_or_else(|| { eprintln!("name {} not specified, setting to 1", name); named_sizes.insert(name.to_owned(),
fn tensor_mut(elem_type: OnnxTensorElementDataType, dims: &[usize]) -> Box<dyn AsMut<Val>> { use OnnxTensorElementDataType::*; match elem_type { Float => Box::new(Tensor::<f32>::init(dims, 0.0).unwrap()), Int64 => Box::new(Tensor::<i64>::init(dims, 0).unwrap()), Int32 => Box::new(Tensor::<i32>::init(dims, 0).unwrap()), t => panic!("Unsupported type {:?}", t), } } fn tensor_with_size( info: &TensorInfo, named_sizes: &mut HashMap<String, usize>, ) -> Box<dyn AsRef<Val>> { let (ty, dims) = tensor_size(info, named_sizes); use OnnxTensorElementDataType::*; match ty { Float => Box::new(Tensor::<f32>::init(&dims, 0.0).unwrap()), Int64 => Box::new(Tensor::<i64>::init(&dims, 0).unwrap()), Int32 => Box::new(Tensor::<i32>::init(&dims, 0).unwrap()), t => panic!("Unsupported type {:?}", t), } } fn main() -> Result<()> { let env = Env::new(LoggingLevel::Fatal, "test")?; let opt = Opt::from_args(); let so = SessionOptions::new()?; let mut map = if let Some(dims) = &opt.dims { key_val_parse(dims) } else { HashMap::new() }; for path in &opt.onnx { println!("model {:?}", path); let session = match Session::new(&env, path, &so) { Ok(sess) => sess, Err(err) => { eprintln!("error: {}\n", err); continue; } }; let metadata = session.metadata(); eprintln!("name: {}", metadata.producer_name()); eprintln!("graph_name: {}", metadata.graph_name()); eprintln!("domain: {}", metadata.domain()); eprintln!("description: {}", metadata.description()); let mut input_names: Vec<OrtString> = vec![]; let mut input_tensors: Vec<Box<dyn AsRef<Val>>> = vec![]; for (i, input) in session.inputs().enumerate() { if let Some(tensor_info) = input.tensor_info() { input_names.push(input.name()); input_tensors.push(tensor_with_size(&tensor_info, &mut map)); } else { println!("input {}: {:?} {:?}", i, &*input.name(), input.onnx_type()); } } let mut output_names: Vec<OrtString> = vec![]; let mut output_sizes: Vec<(OnnxTensorElementDataType, Vec<usize>)> = vec![]; for (i, output) in session.outputs().enumerate() { if let Some(tensor_info) = output.tensor_info() { output_names.push(output.name()); output_sizes.push(tensor_size(&tensor_info, &mut map)); } else { println!( "output {}: {:?} {:?}", i, &*output.name(), output.onnx_type() ); } } let in_names: Vec<&CStr> = input_names.iter().map(|x| x.as_c_str()).collect(); let in_vals: Vec<&Val> = input_tensors.iter().map(|x| x.as_ref().as_ref()).collect(); let out_names: Vec<&CStr> = output_names.iter().map(|x| x.as_c_str()).collect(); crossbeam::scope(|s| { let mut workers = vec![]; for i in 0..opt.workers { let i = std::sync::Arc::new(i); workers.push(s.spawn(|_| { let i = i; let ro = RunOptions::new(); let mut output_tensors: Vec<_> = output_sizes .iter() .map(|(elem_type, size)| tensor_mut(*elem_type, size)) .collect(); let mut out_vals: Vec<&mut Val> = output_tensors .iter_mut() .map(|x| x.as_mut().as_mut()) .collect(); session .run_mut(&ro, &in_names, &in_vals[..], &out_names, &mut out_vals[..]) .expect("run"); let mut times = vec![]; for _ in 0..opt.runs { let before = Instant::now(); session .run_mut(&ro, &in_names, &in_vals[..], &out_names, &mut out_vals[..]) .expect("run"); times.push(before.elapsed()); } let total: Duration = times.iter().sum(); let avg = total / (times.len() as u32); eprintln!("worker {} avg time: {:.2} ms", i, avg.as_secs_f64() * 1e3); })); } workers.into_iter().for_each(|j| j.join().unwrap()); }) .unwrap(); } Ok(()) }
1); 1 }) } SymbolicDim::Fixed(x) => x, }) .collect(); (info.elem_type(), dims) }
function_block-function_prefixed
[ { "content": "fn key_val_parse(str: &str) -> HashMap<String, usize> {\n\n let mut map = HashMap::new();\n\n if str.is_empty() {\n\n return map;\n\n }\n\n for key_val in str.split(',') {\n\n let mut iter = key_val.split('=');\n\n let key = iter.next().expect(\"no =\");\n\n ...
Rust
rups/src/blocking/mod.rs
aramperes/nut-rs
35d40d31116b745967927fbc944a18232dbf8fb1
use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpStream}; use crate::blocking::stream::ConnectionStream; use crate::cmd::{Command, Response}; use crate::{ClientError, Config, Host, NutError}; mod stream; pub enum Connection { Tcp(TcpConnection), } impl Connection { pub fn new(config: &Config) -> crate::Result<Self> { let mut conn = match &config.host { Host::Tcp(host) => Self::Tcp(TcpConnection::new(config.clone(), &host.addr)?), }; conn.get_network_version()?; conn.login(config)?; Ok(conn) } pub fn close(mut self) -> crate::Result<()> { self.logout()?; Ok(()) } fn login(&mut self, config: &Config) -> crate::Result<()> { if let Some(auth) = config.auth.clone() { self.set_username(&auth.username)?; if let Some(password) = &auth.password { self.set_password(password)?; } } Ok(()) } } pub struct TcpConnection { config: Config, stream: ConnectionStream, } impl TcpConnection { fn new(config: Config, socket_addr: &SocketAddr) -> crate::Result<Self> { let tcp_stream = TcpStream::connect_timeout(socket_addr, config.timeout)?; let mut connection = Self { config, stream: ConnectionStream::Plain(tcp_stream), }; connection = connection.enable_ssl()?; Ok(connection) } #[cfg(feature = "ssl")] fn enable_ssl(mut self) -> crate::Result<Self> { if self.config.ssl { self.write_cmd(Command::StartTLS)?; self.read_response() .map_err(|e| { if let crate::ClientError::Nut(NutError::FeatureNotConfigured) = e { crate::ClientError::Nut(NutError::SslNotSupported) } else { e } })? .expect_ok()?; let mut ssl_config = rustls::ClientConfig::new(); let sess = if self.config.ssl_insecure { ssl_config .dangerous() .set_certificate_verifier(std::sync::Arc::new( crate::ssl::InsecureCertificateValidator::new(&self.config), )); let dns_name = webpki::DNSNameRef::try_from_ascii_str("www.google.com").unwrap(); rustls::ClientSession::new(&std::sync::Arc::new(ssl_config), dns_name) } else { let hostname = self .config .host .hostname() .ok_or(ClientError::Nut(NutError::SslInvalidHostname))?; let dns_name = webpki::DNSNameRef::try_from_ascii_str(&hostname) .map_err(|_| ClientError::Nut(NutError::SslInvalidHostname))?; ssl_config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); rustls::ClientSession::new(&std::sync::Arc::new(ssl_config), dns_name) }; self.stream = self.stream.upgrade_ssl(sess)?; } Ok(self) } #[cfg(not(feature = "ssl"))] fn enable_ssl(self) -> crate::Result<Self> { Ok(self) } pub(crate) fn write_cmd(&mut self, line: Command) -> crate::Result<()> { let line = format!("{}\n", line); if self.config.debug { eprint!("DEBUG -> {}", line); } self.stream.write_all(line.as_bytes())?; self.stream.flush()?; Ok(()) } fn parse_line( reader: &mut BufReader<&mut ConnectionStream>, debug: bool, ) -> crate::Result<Vec<String>> { let mut raw = String::new(); reader.read_line(&mut raw)?; if debug { eprint!("DEBUG <- {}", raw); } raw = raw[..raw.len() - 1].to_string(); let args = shell_words::split(&raw) .map_err(|e| NutError::generic(format!("Parsing server response failed: {}", e)))?; Ok(args) } pub(crate) fn read_response(&mut self) -> crate::Result<Response> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Response::from_args(args) } pub(crate) fn read_plain_response(&mut self) -> crate::Result<String> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Ok(args.join(" ")) } pub(crate) fn read_list(&mut self, query: &[&str]) -> crate::Result<Vec<Response>> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Response::from_args(args)?.expect_begin_list(query)?; let mut lines: Vec<Response> = Vec::new(); loop { let args = Self::parse_line(&mut reader, self.config.debug)?; let resp = Response::from_args(args)?; match resp { Response::EndList(_) => { break; } _ => lines.push(resp), } } Ok(lines) } }
use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpStream}; use crate::blocking::stream::ConnectionStream; use crate::cmd::{Command, Response}; use crate::{ClientError, Config, Host, NutError}; mod stream; pub enum Connection { Tcp(TcpConnection), } impl Connection { pub fn new(config: &Config) -> crate::Result<Self> { let mut conn = match &config.host { Host::Tcp(host) => Self::Tcp(TcpConnection::new(config.clone(), &host.addr)?), }; conn.get_network_version()?; conn.login(config)?; Ok(conn) } pub fn close(mut self) -> crate::Result<()> { self.logout()?; Ok(()) } fn login(&mut self, config: &Config) -> crate::Result<()> { if let Some(auth) = config.auth.clone() { self.set_username(&auth.username)?; if let Some(password) = &auth.password { self.set_password(password)?; } } Ok(()) } } pub struct TcpConnection { config: Config, stream: ConnectionStream, } impl TcpConnection { fn new(config: Config, socket_addr: &SocketAddr) -> crate::Result<Self> { let tcp_stream = TcpStream::connect_timeout(socket_addr, config.timeout)?; let mut connection = Self { config, stream: ConnectionStream::Plain(tcp_stream), }; connection = connection.enable_ssl()?; Ok(connection) } #[cfg(feature = "ssl")] fn enable_ssl(mut self) -> crate::Result<Self> { if self.config.ssl { self.write_cmd(Command::StartTLS)?; self.read_response() .map_err(|e| { if let crate::ClientError::Nut(NutError::FeatureNotConfigured) = e { crate::ClientError::Nut(NutError::SslNotSupported) } else { e } })? .expect_ok()?; let mut ssl_config = rustls::ClientConfig::new(); let sess = if self.config.ssl_insecure { ssl_config .dangerous() .set_certificate_verifier(std::sync::Arc::new( crate::ssl::InsecureCertificateValidator::new(&self.config), )); let dns_name = webpki::DNSNameRef::try_from_ascii_str("www.google.com").unwrap(); rustls::ClientSession::new(&std::sync::Arc::new(ssl_config), dns_name) } else { let hostname = self .config .host .hostname() .ok_or(ClientError::Nut(NutError::Ssl
eprint!("DEBUG -> {}", line); } self.stream.write_all(line.as_bytes())?; self.stream.flush()?; Ok(()) } fn parse_line( reader: &mut BufReader<&mut ConnectionStream>, debug: bool, ) -> crate::Result<Vec<String>> { let mut raw = String::new(); reader.read_line(&mut raw)?; if debug { eprint!("DEBUG <- {}", raw); } raw = raw[..raw.len() - 1].to_string(); let args = shell_words::split(&raw) .map_err(|e| NutError::generic(format!("Parsing server response failed: {}", e)))?; Ok(args) } pub(crate) fn read_response(&mut self) -> crate::Result<Response> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Response::from_args(args) } pub(crate) fn read_plain_response(&mut self) -> crate::Result<String> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Ok(args.join(" ")) } pub(crate) fn read_list(&mut self, query: &[&str]) -> crate::Result<Vec<Response>> { let mut reader = BufReader::new(&mut self.stream); let args = Self::parse_line(&mut reader, self.config.debug)?; Response::from_args(args)?.expect_begin_list(query)?; let mut lines: Vec<Response> = Vec::new(); loop { let args = Self::parse_line(&mut reader, self.config.debug)?; let resp = Response::from_args(args)?; match resp { Response::EndList(_) => { break; } _ => lines.push(resp), } } Ok(lines) } }
InvalidHostname))?; let dns_name = webpki::DNSNameRef::try_from_ascii_str(&hostname) .map_err(|_| ClientError::Nut(NutError::SslInvalidHostname))?; ssl_config .root_store .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS); rustls::ClientSession::new(&std::sync::Arc::new(ssl_config), dns_name) }; self.stream = self.stream.upgrade_ssl(sess)?; } Ok(self) } #[cfg(not(feature = "ssl"))] fn enable_ssl(self) -> crate::Result<Self> { Ok(self) } pub(crate) fn write_cmd(&mut self, line: Command) -> crate::Result<()> { let line = format!("{}\n", line); if self.config.debug {
random
[ { "content": "fn connect(config: Config) -> anyhow::Result<Connection> {\n\n Connection::new(&config).with_context(|| format!(\"Failed to connect to upsd: {:?}\", &config))\n\n}\n\n\n", "file_path": "rupsc/src/cmd.rs", "rank": 0, "score": 117285.13075444756 }, { "content": "/// Lists each...
Rust
src/cargo/util/rustc.rs
xobs/cargo
ab64d1393b5b77c66b6534ef5023a1b89ee7bf64
use std::collections::hash_map::HashMap; use std::env; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use log::{debug, info, warn}; use serde::{Deserialize, Serialize}; use crate::util::interning::InternedString; use crate::util::paths; use crate::util::{self, profile, CargoResult, CargoResultExt, ProcessBuilder, StableHasher}; #[derive(Debug)] pub struct Rustc { pub path: PathBuf, pub wrapper: Option<PathBuf>, pub workspace_wrapper: Option<PathBuf>, pub verbose_version: String, pub version: semver::Version, pub host: InternedString, cache: Mutex<Cache>, } impl Rustc { pub fn new( path: PathBuf, wrapper: Option<PathBuf>, workspace_wrapper: Option<PathBuf>, rustup_rustc: &Path, cache_location: Option<PathBuf>, ) -> CargoResult<Rustc> { let _p = profile::start("Rustc::new"); let mut cache = Cache::load(&path, rustup_rustc, cache_location); let mut cmd = util::process(&path); cmd.arg("-vV"); let verbose_version = cache.cached_output(&cmd)?.0; let extract = |field: &str| -> CargoResult<&str> { verbose_version .lines() .find(|l| l.starts_with(field)) .map(|l| &l[field.len()..]) .ok_or_else(|| { anyhow::format_err!( "`rustc -vV` didn't have a line for `{}`, got:\n{}", field.trim(), verbose_version ) }) }; let host = InternedString::new(extract("host: ")?); let version = semver::Version::parse(extract("release: ")?).chain_err(|| { format!( "rustc version does not appear to be a valid semver version, from:\n{}", verbose_version ) })?; Ok(Rustc { path, wrapper, workspace_wrapper, verbose_version, version, host, cache: Mutex::new(cache), }) } pub fn process(&self) -> ProcessBuilder { util::process(self.path.as_path()).wrapped(self.wrapper.as_ref()) } pub fn workspace_process(&self) -> ProcessBuilder { util::process(self.path.as_path()) .wrapped(self.workspace_wrapper.as_ref()) .wrapped(self.wrapper.as_ref()) } pub fn process_no_wrapper(&self) -> ProcessBuilder { util::process(&self.path) } pub fn cached_output(&self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> { self.cache.lock().unwrap().cached_output(cmd) } } #[derive(Debug)] struct Cache { cache_location: Option<PathBuf>, dirty: bool, data: CacheData, } #[derive(Serialize, Deserialize, Debug, Default)] struct CacheData { rustc_fingerprint: u64, outputs: HashMap<u64, Output>, successes: HashMap<u64, bool>, } #[derive(Serialize, Deserialize, Debug)] struct Output { success: bool, status: String, code: Option<i32>, stdout: String, stderr: String, } impl Cache { fn load(rustc: &Path, rustup_rustc: &Path, cache_location: Option<PathBuf>) -> Cache { match (cache_location, rustc_fingerprint(rustc, rustup_rustc)) { (Some(cache_location), Ok(rustc_fingerprint)) => { let empty = CacheData { rustc_fingerprint, outputs: HashMap::new(), successes: HashMap::new(), }; let mut dirty = true; let data = match read(&cache_location) { Ok(data) => { if data.rustc_fingerprint == rustc_fingerprint { debug!("reusing existing rustc info cache"); dirty = false; data } else { debug!("different compiler, creating new rustc info cache"); empty } } Err(e) => { debug!("failed to read rustc info cache: {}", e); empty } }; return Cache { cache_location: Some(cache_location), dirty, data, }; fn read(path: &Path) -> CargoResult<CacheData> { let json = paths::read(path)?; Ok(serde_json::from_str(&json)?) } } (_, fingerprint) => { if let Err(e) = fingerprint { warn!("failed to calculate rustc fingerprint: {}", e); } debug!("rustc info cache disabled"); Cache { cache_location: None, dirty: false, data: CacheData::default(), } } } } fn cached_output(&mut self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> { let key = process_fingerprint(cmd); if self.data.outputs.contains_key(&key) { debug!("rustc info cache hit"); } else { debug!("rustc info cache miss"); debug!("running {}", cmd); let output = cmd .build_command() .output() .chain_err(|| format!("could not execute process {} (never executed)", cmd))?; let stdout = String::from_utf8(output.stdout) .map_err(|e| anyhow::anyhow!("{}: {:?}", e, e.as_bytes())) .chain_err(|| anyhow::anyhow!("`{}` didn't return utf8 output", cmd))?; let stderr = String::from_utf8(output.stderr) .map_err(|e| anyhow::anyhow!("{}: {:?}", e, e.as_bytes())) .chain_err(|| anyhow::anyhow!("`{}` didn't return utf8 output", cmd))?; self.data.outputs.insert( key, Output { success: output.status.success(), status: if output.status.success() { String::new() } else { util::exit_status_to_string(output.status) }, code: output.status.code(), stdout, stderr, }, ); self.dirty = true; } let output = &self.data.outputs[&key]; if output.success { Ok((output.stdout.clone(), output.stderr.clone())) } else { Err(util::process_error_raw( &format!("process didn't exit successfully: {}", cmd), output.code, &output.status, Some(output.stdout.as_ref()), Some(output.stderr.as_ref()), ) .into()) } } } impl Drop for Cache { fn drop(&mut self) { if !self.dirty { return; } if let Some(ref path) = self.cache_location { let json = serde_json::to_string(&self.data).unwrap(); match paths::write(path, json.as_bytes()) { Ok(()) => info!("updated rustc info cache"), Err(e) => warn!("failed to update rustc info cache: {}", e), } } } } fn rustc_fingerprint(path: &Path, rustup_rustc: &Path) -> CargoResult<u64> { let mut hasher = StableHasher::new(); let path = paths::resolve_executable(path)?; path.hash(&mut hasher); paths::mtime(&path)?.hash(&mut hasher); let maybe_rustup = rustup_rustc == path; match ( maybe_rustup, env::var("RUSTUP_HOME"), env::var("RUSTUP_TOOLCHAIN"), ) { (_, Ok(rustup_home), Ok(rustup_toolchain)) => { debug!("adding rustup info to rustc fingerprint"); rustup_toolchain.hash(&mut hasher); rustup_home.hash(&mut hasher); let real_rustc = Path::new(&rustup_home) .join("toolchains") .join(rustup_toolchain) .join("bin") .join("rustc") .with_extension(env::consts::EXE_EXTENSION); paths::mtime(&real_rustc)?.hash(&mut hasher); } (true, _, _) => anyhow::bail!("probably rustup rustc, but without rustup's env vars"), _ => (), } Ok(hasher.finish()) } fn process_fingerprint(cmd: &ProcessBuilder) -> u64 { let mut hasher = StableHasher::new(); cmd.get_args().hash(&mut hasher); let mut env = cmd.get_envs().iter().collect::<Vec<_>>(); env.sort_unstable(); env.hash(&mut hasher); hasher.finish() }
use std::collections::hash_map::HashMap; use std::env; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use log::{debug, info, warn}; use serde::{Deserialize, Serialize}; use crate::util::interning::InternedString; use crate::util::paths; use crate::util::{self, profile, CargoResult, CargoResultExt, ProcessBuilder, StableHasher}; #[derive(Debug)] pub struct Rustc { pub path: PathBuf, pub wrapper: Option<PathBuf>, pub workspace_wrapper: Option<PathBuf>, pub verbose_version: String, pub version: semver::Version, pub host: InternedString, cache: Mutex<Cache>, } impl Rustc { pub fn new( path: PathBuf, wrapper: Option<PathBuf>, workspace_wrapper: Option<PathBuf>, rustup_rustc: &Path, cache_location: Option<PathBuf>, ) -> CargoResult<Rustc> { let _p = profile::start("Rustc::new"); let mut cache = Cache::load(&path, rustup_rustc, cache_location); let mut cmd = util::process(&path); cmd.arg("-vV"); let verbose_version = cache.cached_output(&cmd)?.0; let
host, cache: Mutex::new(cache), }) } pub fn process(&self) -> ProcessBuilder { util::process(self.path.as_path()).wrapped(self.wrapper.as_ref()) } pub fn workspace_process(&self) -> ProcessBuilder { util::process(self.path.as_path()) .wrapped(self.workspace_wrapper.as_ref()) .wrapped(self.wrapper.as_ref()) } pub fn process_no_wrapper(&self) -> ProcessBuilder { util::process(&self.path) } pub fn cached_output(&self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> { self.cache.lock().unwrap().cached_output(cmd) } } #[derive(Debug)] struct Cache { cache_location: Option<PathBuf>, dirty: bool, data: CacheData, } #[derive(Serialize, Deserialize, Debug, Default)] struct CacheData { rustc_fingerprint: u64, outputs: HashMap<u64, Output>, successes: HashMap<u64, bool>, } #[derive(Serialize, Deserialize, Debug)] struct Output { success: bool, status: String, code: Option<i32>, stdout: String, stderr: String, } impl Cache { fn load(rustc: &Path, rustup_rustc: &Path, cache_location: Option<PathBuf>) -> Cache { match (cache_location, rustc_fingerprint(rustc, rustup_rustc)) { (Some(cache_location), Ok(rustc_fingerprint)) => { let empty = CacheData { rustc_fingerprint, outputs: HashMap::new(), successes: HashMap::new(), }; let mut dirty = true; let data = match read(&cache_location) { Ok(data) => { if data.rustc_fingerprint == rustc_fingerprint { debug!("reusing existing rustc info cache"); dirty = false; data } else { debug!("different compiler, creating new rustc info cache"); empty } } Err(e) => { debug!("failed to read rustc info cache: {}", e); empty } }; return Cache { cache_location: Some(cache_location), dirty, data, }; fn read(path: &Path) -> CargoResult<CacheData> { let json = paths::read(path)?; Ok(serde_json::from_str(&json)?) } } (_, fingerprint) => { if let Err(e) = fingerprint { warn!("failed to calculate rustc fingerprint: {}", e); } debug!("rustc info cache disabled"); Cache { cache_location: None, dirty: false, data: CacheData::default(), } } } } fn cached_output(&mut self, cmd: &ProcessBuilder) -> CargoResult<(String, String)> { let key = process_fingerprint(cmd); if self.data.outputs.contains_key(&key) { debug!("rustc info cache hit"); } else { debug!("rustc info cache miss"); debug!("running {}", cmd); let output = cmd .build_command() .output() .chain_err(|| format!("could not execute process {} (never executed)", cmd))?; let stdout = String::from_utf8(output.stdout) .map_err(|e| anyhow::anyhow!("{}: {:?}", e, e.as_bytes())) .chain_err(|| anyhow::anyhow!("`{}` didn't return utf8 output", cmd))?; let stderr = String::from_utf8(output.stderr) .map_err(|e| anyhow::anyhow!("{}: {:?}", e, e.as_bytes())) .chain_err(|| anyhow::anyhow!("`{}` didn't return utf8 output", cmd))?; self.data.outputs.insert( key, Output { success: output.status.success(), status: if output.status.success() { String::new() } else { util::exit_status_to_string(output.status) }, code: output.status.code(), stdout, stderr, }, ); self.dirty = true; } let output = &self.data.outputs[&key]; if output.success { Ok((output.stdout.clone(), output.stderr.clone())) } else { Err(util::process_error_raw( &format!("process didn't exit successfully: {}", cmd), output.code, &output.status, Some(output.stdout.as_ref()), Some(output.stderr.as_ref()), ) .into()) } } } impl Drop for Cache { fn drop(&mut self) { if !self.dirty { return; } if let Some(ref path) = self.cache_location { let json = serde_json::to_string(&self.data).unwrap(); match paths::write(path, json.as_bytes()) { Ok(()) => info!("updated rustc info cache"), Err(e) => warn!("failed to update rustc info cache: {}", e), } } } } fn rustc_fingerprint(path: &Path, rustup_rustc: &Path) -> CargoResult<u64> { let mut hasher = StableHasher::new(); let path = paths::resolve_executable(path)?; path.hash(&mut hasher); paths::mtime(&path)?.hash(&mut hasher); let maybe_rustup = rustup_rustc == path; match ( maybe_rustup, env::var("RUSTUP_HOME"), env::var("RUSTUP_TOOLCHAIN"), ) { (_, Ok(rustup_home), Ok(rustup_toolchain)) => { debug!("adding rustup info to rustc fingerprint"); rustup_toolchain.hash(&mut hasher); rustup_home.hash(&mut hasher); let real_rustc = Path::new(&rustup_home) .join("toolchains") .join(rustup_toolchain) .join("bin") .join("rustc") .with_extension(env::consts::EXE_EXTENSION); paths::mtime(&real_rustc)?.hash(&mut hasher); } (true, _, _) => anyhow::bail!("probably rustup rustc, but without rustup's env vars"), _ => (), } Ok(hasher.finish()) } fn process_fingerprint(cmd: &ProcessBuilder) -> u64 { let mut hasher = StableHasher::new(); cmd.get_args().hash(&mut hasher); let mut env = cmd.get_envs().iter().collect::<Vec<_>>(); env.sort_unstable(); env.hash(&mut hasher); hasher.finish() }
extract = |field: &str| -> CargoResult<&str> { verbose_version .lines() .find(|l| l.starts_with(field)) .map(|l| &l[field.len()..]) .ok_or_else(|| { anyhow::format_err!( "`rustc -vV` didn't have a line for `{}`, got:\n{}", field.trim(), verbose_version ) }) }; let host = InternedString::new(extract("host: ")?); let version = semver::Version::parse(extract("release: ")?).chain_err(|| { format!( "rustc version does not appear to be a valid semver version, from:\n{}", verbose_version ) })?; Ok(Rustc { path, wrapper, workspace_wrapper, verbose_version, version,
random
[ { "content": "pub fn read(path: &Path) -> CargoResult<String> {\n\n match String::from_utf8(read_bytes(path)?) {\n\n Ok(s) => Ok(s),\n\n Err(_) => anyhow::bail!(\"path at `{}` was not valid utf-8\", path.display()),\n\n }\n\n}\n\n\n", "file_path": "src/cargo/util/paths.rs", "rank": 0...
Rust
associated-token-account/program/tests/create_idempotent.rs
biw/solana-program-library
5611ad8bd595d9e3666f8b115cd28f8116038645
#![cfg(feature = "test-bpf")] mod program_test; use { program_test::program_test_2022, solana_program::{instruction::*, pubkey::Pubkey}, solana_program_test::*, solana_sdk::{ account::Account as SolanaAccount, program_option::COption, program_pack::Pack, signature::Signer, signer::keypair::Keypair, system_instruction::create_account, transaction::{Transaction, TransactionError}, }, spl_associated_token_account::{ error::AssociatedTokenAccountError, get_associated_token_address_with_program_id, instruction::{ create_associated_token_account, create_associated_token_account_idempotent, }, }, spl_token_2022::{ extension::ExtensionType, instruction::initialize_account, state::{Account, AccountState}, }, }; #[tokio::test] async fn success_account_exists() { let wallet_address = Pubkey::new_unique(); let token_mint_address = Pubkey::new_unique(); let associated_token_address = get_associated_token_address_with_program_id( &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let (mut banks_client, payer, recent_blockhash) = program_test_2022(token_mint_address, true).start().await; let rent = banks_client.get_rent().await.unwrap(); let expected_token_account_len = ExtensionType::get_account_len::<Account>(&[ExtensionType::ImmutableOwner]); let expected_token_account_balance = rent.minimum_balance(expected_token_account_len); let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let associated_account = banks_client .get_account(associated_token_address) .await .expect("get_account") .expect("associated_account not none"); assert_eq!(associated_account.data.len(), expected_token_account_len); assert_eq!(associated_account.owner, spl_token_2022::id()); assert_eq!(associated_account.lamports, expected_token_account_balance); let instruction = create_associated_token_account( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::IllegalOwner) ); let recent_blockhash = banks_client .get_new_latest_blockhash(&recent_blockhash) .await .unwrap(); let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let associated_account = banks_client .get_account(associated_token_address) .await .expect("get_account") .expect("associated_account not none"); assert_eq!(associated_account.data.len(), expected_token_account_len); assert_eq!(associated_account.owner, spl_token_2022::id()); assert_eq!(associated_account.lamports, expected_token_account_balance); } #[tokio::test] async fn fail_account_exists_with_wrong_owner() { let wallet_address = Pubkey::new_unique(); let token_mint_address = Pubkey::new_unique(); let associated_token_address = get_associated_token_address_with_program_id( &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let wrong_owner = Pubkey::new_unique(); let mut associated_token_account = SolanaAccount::new(1_000_000_000, Account::LEN, &spl_token_2022::id()); let token_account = Account { mint: token_mint_address, owner: wrong_owner, amount: 0, delegate: COption::None, state: AccountState::Initialized, is_native: COption::None, delegated_amount: 0, close_authority: COption::None, }; Account::pack(token_account, &mut associated_token_account.data).unwrap(); let mut pt = program_test_2022(token_mint_address, true); pt.add_account(associated_token_address, associated_token_account); let (mut banks_client, payer, recent_blockhash) = pt.start().await; let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 0, InstructionError::Custom(AssociatedTokenAccountError::InvalidOwner as u32) ) ); } #[tokio::test] async fn fail_non_ata() { let token_mint_address = Pubkey::new_unique(); let (mut banks_client, payer, recent_blockhash) = program_test_2022(token_mint_address, true).start().await; let rent = banks_client.get_rent().await.unwrap(); let token_account_len = ExtensionType::get_account_len::<Account>(&[ExtensionType::ImmutableOwner]); let token_account_balance = rent.minimum_balance(token_account_len); let wallet_address = Pubkey::new_unique(); let account = Keypair::new(); let transaction = Transaction::new_signed_with_payer( &[ create_account( &payer.pubkey(), &account.pubkey(), token_account_balance, token_account_len as u64, &spl_token_2022::id(), ), initialize_account( &spl_token_2022::id(), &account.pubkey(), &token_mint_address, &wallet_address, ) .unwrap(), ], Some(&payer.pubkey()), &[&payer, &account], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let mut instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); instruction.accounts[1] = AccountMeta::new(account.pubkey(), false); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidSeeds) ); }
#![cfg(feature = "test-bpf")] mod program_test; use { program_test::program_test_2022, solana_program::{instruction::*, pubkey::Pubkey}, solana_program_test::*, solana_sdk::{ account::Account as SolanaAccount, program_option::COption, program_pack::Pack, signature::Signer, signer::keypair::Keypair, system_instruction::create_account, transaction::{Transaction, TransactionError}, }, spl_associated_token_account::{ error::AssociatedTokenAccountError, get_associated_token_address_with_program_id, instruction::{ create_associated_token_account, create_associated_token_account_idempotent, }, }, spl_token_2022::{ extension::ExtensionType, instruction::initialize_account, state::{Account, AccountState}, }, }; #[tokio::test] async fn success_account_exists() { let wallet_address = Pubkey::new_unique(); let token_mint_address = Pubkey::new_unique(); let associated_token_address = get_associated_token_address_with_program_id( &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let (mut banks_client, payer, recent_blockhash) = program_test_2022(token_mint_address, true).start().await; let rent = banks_client.get_rent().await.unwrap(); let expected_token_account_len = ExtensionType::get_account_len::<Account>(&[ExtensionType::ImmutableOwner]); let expected_token_account_balance = rent.minimum_balance(expected_token_account_len); let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let associated_account = banks_client .get_account(associated_token_address) .await .expect("get_account") .expect("associated_account not none"); assert_eq!(associated_account.data.len(), expected_token_account_len); assert_eq!(associated_account.owner, spl_token_2022::id()); assert_eq!(associated_account.lamports, expected_token_account_balance); let instruction = create_associated_token_account( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::IllegalOwner) ); let recent_blockhash = banks_client .get_new_latest_blockhash(&recent_blockhash) .await .unwrap(); let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let associated_account = banks_client .get_account(associated_token_address) .await .expect("get_account") .expect("associated_account not none"); assert_eq!(associated_account.data.len(), expected_token_account_len); assert_eq!(associated_account.owner, spl_token_2022::id()); assert_eq!(associated_account.lamports, expected_token_account_balance); } #[tokio::test] async fn fail_account_exists_with_wrong_owner() { let wallet_address = Pubkey::new_unique(); let token_mint_address = Pubkey::new_unique(); let associated_token_address = get_associated_token_address_with_program_id( &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let wrong_owner = Pubkey::new_unique(); let mut associated_token_account = SolanaAccount::new(1_000_000_000, Account::LEN, &spl_token_2022::id()); let token_account = Account { mint: token_mint_address, owner: wrong_owner, amount: 0, delegate: COption::None, state: AccountState::Initialized, is_native: COption::None, delegated_amount: 0, close_authority: COption::None, }; Account::pack(token_account, &mut associated_token_account.data).unwrap(); let mut pt = program_test_2022(token_mint_address, true); pt.add_account(associated_token_address, associated_token_account); let (mut banks_client, payer, recent_blockhash) = pt.start().await; let instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash,
ta() { let token_mint_address = Pubkey::new_unique(); let (mut banks_client, payer, recent_blockhash) = program_test_2022(token_mint_address, true).start().await; let rent = banks_client.get_rent().await.unwrap(); let token_account_len = ExtensionType::get_account_len::<Account>(&[ExtensionType::ImmutableOwner]); let token_account_balance = rent.minimum_balance(token_account_len); let wallet_address = Pubkey::new_unique(); let account = Keypair::new(); let transaction = Transaction::new_signed_with_payer( &[ create_account( &payer.pubkey(), &account.pubkey(), token_account_balance, token_account_len as u64, &spl_token_2022::id(), ), initialize_account( &spl_token_2022::id(), &account.pubkey(), &token_mint_address, &wallet_address, ) .unwrap(), ], Some(&payer.pubkey()), &[&payer, &account], recent_blockhash, ); banks_client.process_transaction(transaction).await.unwrap(); let mut instruction = create_associated_token_account_idempotent( &payer.pubkey(), &wallet_address, &token_mint_address, &spl_token_2022::id(), ); instruction.accounts[1] = AccountMeta::new(account.pubkey(), false); let transaction = Transaction::new_signed_with_payer( &[instruction], Some(&payer.pubkey()), &[&payer], recent_blockhash, ); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError(0, InstructionError::InvalidSeeds) ); }
); assert_eq!( banks_client .process_transaction(transaction) .await .unwrap_err() .unwrap(), TransactionError::InstructionError( 0, InstructionError::Custom(AssociatedTokenAccountError::InvalidOwner as u32) ) ); } #[tokio::test] async fn fail_non_a
random
[ { "content": "/// Determine if a memo is required for transfers into this account\n\npub fn memo_required(account_state: &StateWithExtensionsMut<Account>) -> bool {\n\n if let Ok(extension) = account_state.get_extension::<MemoTransfer>() {\n\n return extension.require_incoming_transfer_memos.into();\n...
Rust
src/parsers/elements_section.rs
w1th0utnam3/mshio
53f0d1d4c4cd0bbd50387c4a45aa5b666a9bf9ed
use std::collections::HashMap; use nom::IResult; use num::traits::FromPrimitive; use crate::error::{ always_error, context, make_error, MapMshError, MshParserError, MshParserErrorKind, }; use crate::mshfile::{Element, ElementBlock, ElementType, Elements, MshIntT, MshUsizeT}; use crate::parsers::num_parser_traits::{ int_parser, size_t_parser, usize_parser, ParsesInt, ParsesSizeT, }; use crate::parsers::{count_indexed, verify_or}; struct ElementSectionHeader<U: MshUsizeT> { num_entity_blocks: usize, num_elements: U, min_element_tag: U, max_element_tag: U, } pub(crate) fn parse_element_section<'a, 'b: 'a>( parsers: impl ParsesSizeT<u64> + ParsesInt<i32>, ) -> impl Fn(&'b [u8]) -> IResult<&'b [u8], Elements<u64, i32>, MshParserError<&'b [u8]>> { move |input| { let (input, element_section_header) = context("element section header", |input| { parse_element_section_header(&parsers, input) })(input)?; let ElementSectionHeader { num_entity_blocks, num_elements, min_element_tag, max_element_tag, } = element_section_header; let sparse_tags = if max_element_tag - min_element_tag > num_elements - 1 { true } else { false }; let (input, element_entity_blocks) = count_indexed( |index, input| { parse_element_entity(&parsers, sparse_tags, input).with_context_from(input, || { format!( "element entity block ({} of {})", index + 1, num_entity_blocks ) }) }, num_entity_blocks, )(input)?; Ok(( input, Elements { num_elements, min_element_tag, max_element_tag, element_blocks: element_entity_blocks, }, )) } } fn parse_element_section_header<'a, U: MshUsizeT>( parser: impl ParsesSizeT<U>, input: &'a [u8], ) -> IResult<&'a [u8], ElementSectionHeader<U>, MshParserError<&'a [u8]>> { let size_t_parser = size_t_parser(&parser); let usize_parser = usize_parser(&parser); let (input, num_entity_blocks) = context("number of element entity blocks", usize_parser)(input)?; let (input, num_elements) = context("total number of elements", &size_t_parser)(input)?; let (input, min_element_tag) = context( "min element tag", verify_or( &size_t_parser, |&tag| tag != U::zero(), context( "Element tag 0 is reserved for internal use", always_error(MshParserErrorKind::InvalidTag), ), ), )(input)?; let (input, max_element_tag) = context( "max element tag", verify_or( &size_t_parser, |&max_tag| max_tag >= min_element_tag, context( "The maximum element tag has to be larger or equal to the minimum element tag", always_error(MshParserErrorKind::InvalidTag), ), ), )(input)?; Ok(( input, ElementSectionHeader { num_entity_blocks, num_elements, min_element_tag, max_element_tag, }, )) } fn parse_element_entity<'a, U, I>( parser: impl ParsesSizeT<U> + ParsesInt<I>, sparse_tags: bool, input: &'a [u8], ) -> IResult<&'a [u8], ElementBlock<U, I>, MshParserError<&'a [u8]>> where U: MshUsizeT, I: MshIntT, { let parser = &parser; let int_parser = int_parser(parser); let usize_parser = usize_parser(parser); let (input, entity_dim) = context("entity dimension", &int_parser)(input)?; let (input, entity_tag) = context("entity tag", &int_parser)(input)?; let (input, element_type) = context("element type", move |i| parse_element_type(parser, i))(input)?; let (input_new, num_elements_in_block) = context("number of elements in element block", usize_parser)(input)?; let num_nodes_per_element = element_type.nodes().map_err(|_| { make_error(input, MshParserErrorKind::Unimplemented).with_context( input, "An element type encountered in the MSH file does not have a known number of nodes.", ) })?; let (input, elements) = count_indexed( |index, input| { parse_element(&parser, num_nodes_per_element, input) .with_error(input, MshParserErrorKind::InvalidElementDefinition) .with_context_from(input, || { format!( "element definition ({} of {})", index + 1, num_elements_in_block ) }) }, num_elements_in_block, )(input_new)?; let element_tags = if sparse_tags { Some( elements .iter() .enumerate() .map(|(i, ele)| (ele.element_tag.clone(), i)) .collect::<HashMap<_, _>>(), ) } else { None }; Ok(( input, ElementBlock { entity_dim, entity_tag, element_type, element_tags, elements, }, )) } fn parse_element_type<'a, I>( parser: impl ParsesInt<I>, input: &'a [u8], ) -> IResult<&'a [u8], ElementType, MshParserError<&'a [u8]>> where I: MshIntT, { let (input_new, element_type_raw) = parser.parse_int(input)?; let element_type_raw = element_type_raw .to_i32() .ok_or_else(|| make_error(input, MshParserErrorKind::UnknownElement))?; let element_type = ElementType::from_i32(element_type_raw).ok_or_else(|| { make_error(input, MshParserErrorKind::UnknownElement) .with_context_from(input, || format!("value {}", element_type_raw)) })?; Ok((input_new, element_type)) } fn parse_element<'a, U>( parser: impl ParsesSizeT<U>, num_nodes_per_element: usize, input: &'a [u8], ) -> IResult<&'a [u8], Element<U>, MshParserError<&'a [u8]>> where U: MshUsizeT, { let (input, element_tag) = parser.parse_size_t(input)?; let mut input = input; let mut node_tags = Vec::with_capacity(num_nodes_per_element); for _ in 0..num_nodes_per_element { let (input_, node_tag) = parser.parse_size_t(input)?; node_tags.push(node_tag); input = input_; } Ok(( input, Element { element_tag, nodes: node_tags, }, )) }
use std::collections::HashMap; use nom::IResult; use num::traits::FromPrimitive; use crate::error::{ always_error, context, make_error, MapMshError, MshParserError, MshParserErrorKind, }; use crate::mshfile::{Element, ElementBlock, ElementType, Elements, MshIntT, MshUsizeT}; use crate::parsers::num_parser_traits::{ int_parser, size_t_parser, usize_parser, ParsesInt, ParsesSizeT, }; use crate::parsers::{count_indexed, verify_or}; struct ElementSectionHeader<U: MshUsizeT> { num_entity_blocks: usize, num_elements: U, min_element_tag: U, max_element_tag: U, } pub(crate) fn parse_element_section<'a, 'b: 'a>( parsers: impl ParsesSizeT<u64> + ParsesInt<i32>, ) -> impl Fn(&'b [u8]) -> IResult<&'b [u8], Elements<u64, i32>, MshParserError<&'b [u8]>> { move |input| { let (input, element_section_header) = context("element section header", |input| { parse_element_section_header(&parsers, input) })(input)?; let ElementSectionHeader { num_entity_blocks, num_elements, min_element_tag, max_element_tag, } = element_section_header; let sparse_tags = if max_element_tag - min_element_tag > num_elements - 1 { true } else { false }; let (input, element_entity_blocks) = count_indexed( |index, input| { parse_element_entity(&parsers, sparse_tags, input).with_context_from(input, || { format!( "element entity block ({} of {})", index + 1, num_entity_blocks ) }) }, num_entity_blocks, )(input)?; Ok(( input, Elements { num_elements, min_element_tag, max_element_tag, element_blocks: element_entity_blocks, }, )) } } fn parse_element_section_header<'a, U: MshUsizeT>( parser: impl ParsesSizeT<U>,
ement_type = ElementType::from_i32(element_type_raw).ok_or_else(|| { make_error(input, MshParserErrorKind::UnknownElement) .with_context_from(input, || format!("value {}", element_type_raw)) })?; Ok((input_new, element_type)) } fn parse_element<'a, U>( parser: impl ParsesSizeT<U>, num_nodes_per_element: usize, input: &'a [u8], ) -> IResult<&'a [u8], Element<U>, MshParserError<&'a [u8]>> where U: MshUsizeT, { let (input, element_tag) = parser.parse_size_t(input)?; let mut input = input; let mut node_tags = Vec::with_capacity(num_nodes_per_element); for _ in 0..num_nodes_per_element { let (input_, node_tag) = parser.parse_size_t(input)?; node_tags.push(node_tag); input = input_; } Ok(( input, Element { element_tag, nodes: node_tags, }, )) }
input: &'a [u8], ) -> IResult<&'a [u8], ElementSectionHeader<U>, MshParserError<&'a [u8]>> { let size_t_parser = size_t_parser(&parser); let usize_parser = usize_parser(&parser); let (input, num_entity_blocks) = context("number of element entity blocks", usize_parser)(input)?; let (input, num_elements) = context("total number of elements", &size_t_parser)(input)?; let (input, min_element_tag) = context( "min element tag", verify_or( &size_t_parser, |&tag| tag != U::zero(), context( "Element tag 0 is reserved for internal use", always_error(MshParserErrorKind::InvalidTag), ), ), )(input)?; let (input, max_element_tag) = context( "max element tag", verify_or( &size_t_parser, |&max_tag| max_tag >= min_element_tag, context( "The maximum element tag has to be larger or equal to the minimum element tag", always_error(MshParserErrorKind::InvalidTag), ), ), )(input)?; Ok(( input, ElementSectionHeader { num_entity_blocks, num_elements, min_element_tag, max_element_tag, }, )) } fn parse_element_entity<'a, U, I>( parser: impl ParsesSizeT<U> + ParsesInt<I>, sparse_tags: bool, input: &'a [u8], ) -> IResult<&'a [u8], ElementBlock<U, I>, MshParserError<&'a [u8]>> where U: MshUsizeT, I: MshIntT, { let parser = &parser; let int_parser = int_parser(parser); let usize_parser = usize_parser(parser); let (input, entity_dim) = context("entity dimension", &int_parser)(input)?; let (input, entity_tag) = context("entity tag", &int_parser)(input)?; let (input, element_type) = context("element type", move |i| parse_element_type(parser, i))(input)?; let (input_new, num_elements_in_block) = context("number of elements in element block", usize_parser)(input)?; let num_nodes_per_element = element_type.nodes().map_err(|_| { make_error(input, MshParserErrorKind::Unimplemented).with_context( input, "An element type encountered in the MSH file does not have a known number of nodes.", ) })?; let (input, elements) = count_indexed( |index, input| { parse_element(&parser, num_nodes_per_element, input) .with_error(input, MshParserErrorKind::InvalidElementDefinition) .with_context_from(input, || { format!( "element definition ({} of {})", index + 1, num_elements_in_block ) }) }, num_elements_in_block, )(input_new)?; let element_tags = if sparse_tags { Some( elements .iter() .enumerate() .map(|(i, ele)| (ele.element_tag.clone(), i)) .collect::<HashMap<_, _>>(), ) } else { None }; Ok(( input, ElementBlock { entity_dim, entity_tag, element_type, element_tags, elements, }, )) } fn parse_element_type<'a, I>( parser: impl ParsesInt<I>, input: &'a [u8], ) -> IResult<&'a [u8], ElementType, MshParserError<&'a [u8]>> where I: MshIntT, { let (input_new, element_type_raw) = parser.parse_int(input)?; let element_type_raw = element_type_raw .to_i32() .ok_or_else(|| make_error(input, MshParserErrorKind::UnknownElement))?; let el
random
[ { "content": "fn parse_entity_section_header<'a, U: MshUsizeT>(\n\n parser: impl ParsesSizeT<U>,\n\n input: &'a [u8],\n\n) -> IResult<&'a [u8], EntitySectionHeader, MshParserError<&'a [u8]>> {\n\n let usize_parser = usize_parser(&parser);\n\n\n\n let (input, num_points) = context(\"number of point e...
Rust
src/pg/numeric.rs
shenhunluo/rustorm
cb7c7b203c718a71b76dc93d51017af57e55003f
use byteorder::{ NetworkEndian, ReadBytesExt, WriteBytesExt, }; use std::error::Error; use postgres::types::{ self, FromSql, IsNull, ToSql, Type, }; use bigdecimal::BigDecimal; use num_bigint::{ BigInt, BigUint, Sign, }; use num_integer::Integer; use num_traits::{ Signed, ToPrimitive, Zero, }; #[derive(Debug, Clone, PartialEq, Eq)] pub enum PgNumeric { Positive { weight: i16, scale: u16, digits: Vec<i16>, }, Negative { weight: i16, scale: u16, digits: Vec<i16>, }, NaN, } #[derive(Debug, Clone, Copy)] struct InvalidNumericSign(u16); impl ::std::fmt::Display for InvalidNumericSign { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "InvalidNumericSign({0:x})", self.0) } } impl Error for InvalidNumericSign { fn description(&self) -> &str { "sign for numeric field was not one of 0, 0x4000, 0xC000" } } impl FromSql for PgNumeric { fn from_sql(_ty: &Type, bytes: &[u8]) -> Result<Self, Box<dyn Error + Send + Sync>> { let mut bytes = <&[u8]>::clone(&bytes); let ndigits = bytes.read_u16::<NetworkEndian>()?; let mut digits = Vec::with_capacity(ndigits as usize); let weight = bytes.read_i16::<NetworkEndian>()?; let sign = bytes.read_u16::<NetworkEndian>()?; let scale = bytes.read_u16::<NetworkEndian>()?; for _ in 0..ndigits { digits.push(bytes.read_i16::<NetworkEndian>()?); } match sign { 0 => { Ok(PgNumeric::Positive { weight, scale, digits, }) } 0x4000 => { Ok(PgNumeric::Negative { weight, scale, digits, }) } 0xC000 => Ok(PgNumeric::NaN), invalid => Err(Box::new(InvalidNumericSign(invalid))), } } fn accepts(ty: &Type) -> bool { match *ty { types::NUMERIC => true, _ => panic!("can not accept type {:?}", ty), } } } impl ToSql for PgNumeric { to_sql_checked!(); fn to_sql( &self, _ty: &Type, out: &mut Vec<u8>, ) -> Result<IsNull, Box<dyn Error + Sync + Send>> { let sign = match *self { PgNumeric::Positive { .. } => 0, PgNumeric::Negative { .. } => 0x4000, PgNumeric::NaN => 0xC000, }; let empty_vec = Vec::new(); let digits = match *self { PgNumeric::Positive { ref digits, .. } | PgNumeric::Negative { ref digits, .. } => { digits } PgNumeric::NaN => &empty_vec, }; let weight = match *self { PgNumeric::Positive { weight, .. } | PgNumeric::Negative { weight, .. } => weight, PgNumeric::NaN => 0, }; let scale = match *self { PgNumeric::Positive { scale, .. } | PgNumeric::Negative { scale, .. } => scale, PgNumeric::NaN => 0, }; out.write_u16::<NetworkEndian>(digits.len() as u16)?; out.write_i16::<NetworkEndian>(weight)?; out.write_u16::<NetworkEndian>(sign)?; out.write_u16::<NetworkEndian>(scale)?; for digit in digits.iter() { out.write_i16::<NetworkEndian>(*digit)?; } Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { match *ty { types::NUMERIC => true, _ => false, } } } struct ToBase10000(Option<BigUint>); impl Iterator for ToBase10000 { type Item = i16; fn next(&mut self) -> Option<Self::Item> { self.0.take().map(|v| { let (div, rem) = v.div_rem(&BigUint::from(10_000u16)); if !div.is_zero() { self.0 = Some(div); } rem.to_i16().expect("10000 always fits in an i16") }) } } impl<'a> From<&'a BigDecimal> for PgNumeric { #[allow(clippy::redundant_closure)] fn from(decimal: &'a BigDecimal) -> Self { let (mut integer, scale) = decimal.as_bigint_and_exponent(); let scale = scale as u16; integer = integer.abs(); for _ in 0..(4 - scale % 4) { integer *= 10; } let integer = integer.to_biguint().expect("integer is always positive"); let mut digits = ToBase10000(Some(integer)).collect::<Vec<_>>(); digits.reverse(); let digits_after_decimal = scale as u16 / 4 + 1; let weight = digits.len() as i16 - digits_after_decimal as i16 - 1; let unnecessary_zeroes = if weight >= 0 { let index_of_decimal = (weight + 1) as usize; digits .get(index_of_decimal..) .expect("enough digits exist") .iter() .rev() .take_while(|i| i.is_zero()) .count() } else { 0 }; let relevant_digits = digits.len() - unnecessary_zeroes; digits.truncate(relevant_digits); match decimal.sign() { Sign::Plus => { PgNumeric::Positive { digits, scale, weight, } } Sign::Minus => { PgNumeric::Negative { digits, scale, weight, } } Sign::NoSign => { PgNumeric::Positive { digits: vec![0], scale: 0, weight: 0, } } } } } impl From<BigDecimal> for PgNumeric { fn from(bigdecimal: BigDecimal) -> Self { (&bigdecimal).into() } } impl From<PgNumeric> for BigDecimal { fn from(numeric: PgNumeric) -> Self { let (sign, weight, _, digits) = match numeric { PgNumeric::Positive { weight, scale, digits, } => (Sign::Plus, weight, scale, digits), PgNumeric::Negative { weight, scale, digits, } => (Sign::Minus, weight, scale, digits), PgNumeric::NaN => panic!("NaN is not (yet) supported in BigDecimal"), }; let mut result = BigUint::default(); let count = digits.len() as i64; for digit in digits { result *= BigUint::from(10_000u64); result += BigUint::from(digit as u64); } let correction_exp = 4 * (i64::from(weight) - count + 1); BigDecimal::new(BigInt::from_biguint(sign, result), -correction_exp) } }
use byteorder::{ NetworkEndian, ReadBytesExt, WriteBytesExt, }; use std::error::Error; use postgres::types::{ self, FromSql, IsNull, ToSql, Type, }; use bigdecimal::BigDecimal; use num_bigint::{ BigInt, BigUint, Sign, }; use num_integer::Integer; use num_traits::{ Signed, ToPrimitive, Zero, }; #[derive(Debug, Clone, PartialEq, Eq)] pub enum PgNumeric { Positive { weight: i16, scale: u16, digits: Vec<i16>, }, Negative { weight: i16, scale: u16, digits: Vec<i16>, }, NaN, } #[derive(Debug, Clone, Copy)] struct InvalidNumericSign(u16); impl ::std::fmt::Display for InvalidNumericSign { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(f, "InvalidNumericSign({0:x})", self.0) } } impl Error for InvalidNumericSign { fn description(&self) -> &str { "sign for numeric field was not one of 0, 0x4000, 0xC000" } } impl FromSql for PgNumeric { fn from_sql(_ty: &Type, bytes: &[u8]) -> Result<Self, Box<dyn Error + Send + Sync>> { let mut bytes = <&[u8]>::clone(&bytes); let ndigits = bytes.read_u16::<NetworkEndian>()?; let mut digits = Vec::with_capacity(ndigits as usize); let weight = bytes.read_i16::<NetworkEndian>()?; let sign = bytes.read_u16::<NetworkEndian>()?; let scale = bytes.read_u16::<NetworkEndian>()?; for _ in 0..ndigits { digits.push(bytes.read_i16::<NetworkEndian>()?); } match sign { 0 => { Ok(PgNumeric::Positive { weight, scale, digits, }) } 0x4000 => { Ok(PgNumeric::Negative { weight, scale, digits, }) } 0xC000 => Ok(PgNumeric::NaN), invalid => Err(Box::new(InvalidNumericSign(invalid))), } } fn accepts(ty: &Type) -> bool { match *ty { types::NUMERIC => true, _ => panic!("can not accept type {:?}", ty), } } } impl ToSql for PgNumeric { to_sql_checked!(); fn to_sql( &self, _ty: &Type, out: &mut Vec<u8>, ) -> Result<IsNull, Box<dyn Error + Sync + Send>> { let sign = match *self { PgNumeric::Positive { .. } => 0, PgNumeric::Negative { .. } => 0x4000, PgNumeric::NaN => 0xC000, }; let empty_vec = Vec::new(); let digits = match *self { PgNumeric::Positive { ref digits, .. } | PgNumeric::Negative { ref digits, .. } => { digits } PgNumeric::NaN => &empty_vec, }; let weight = match *self { PgNumeric::Positive { weight, .. } | PgNumeric::Negative { weight, .. } => weight, PgNumeric::NaN => 0, }; let scale = match *self { PgNumeric::Positive { scale, .. } | PgNumeric::Negative { scale, .. } => scale, PgNumeric::NaN => 0, }; out.write_u16::<NetworkEndian>(digits.len() as u16)?; out.write_i16::<NetworkEndian>(weight)?; out.write_u16::<NetworkEndian>(sign)?; out.write_u16::<NetworkEndian>(scale)?; for digit in digits.iter() { out.write_i16::<NetworkEndian>(*digit)?; } Ok(IsNull::No) } fn accepts(ty: &Type) -> bool { match *ty { types::NUMERIC => true, _ => false, } } } struct ToBase10000(Option<BigUint>); impl Iterator for ToBase10000 { type Item = i16; fn next(&mut self) -> Option<Self::Item> { self.0.take().map(|v| { let (div, rem) = v.div_rem(&BigUint::from(10_000u16)); if !div.is_zero() { self.0 = Some(div); } rem.to_i16().expect("10000 always fits in an i16") }) } } impl<'a> From<&'a BigDecimal> for PgNumeric { #[allow(clippy::redundant_closure)] fn from(decimal: &'a BigDecimal) -> Self { let (mut integer, scale) = decimal.as_bigint_and_exponent(); let scale = scale as u16; integer = integer.abs(); for _ in 0..(4 - scale % 4) { integer *= 10; } let integer = integer.to_biguint().expect("integer is always positive"); let mut digits = ToBase10000(Some(integer)).collect::<Vec<_>>(); digits.reverse(); let digits_after_decimal = scale as u16 / 4 + 1; let weight = digits.len() as i16 - digits_after_decimal as i16 - 1;
let relevant_digits = digits.len() - unnecessary_zeroes; digits.truncate(relevant_digits); match decimal.sign() { Sign::Plus => { PgNumeric::Positive { digits, scale, weight, } } Sign::Minus => { PgNumeric::Negative { digits, scale, weight, } } Sign::NoSign => { PgNumeric::Positive { digits: vec![0], scale: 0, weight: 0, } } } } } impl From<BigDecimal> for PgNumeric { fn from(bigdecimal: BigDecimal) -> Self { (&bigdecimal).into() } } impl From<PgNumeric> for BigDecimal { fn from(numeric: PgNumeric) -> Self { let (sign, weight, _, digits) = match numeric { PgNumeric::Positive { weight, scale, digits, } => (Sign::Plus, weight, scale, digits), PgNumeric::Negative { weight, scale, digits, } => (Sign::Minus, weight, scale, digits), PgNumeric::NaN => panic!("NaN is not (yet) supported in BigDecimal"), }; let mut result = BigUint::default(); let count = digits.len() as i64; for digit in digits { result *= BigUint::from(10_000u64); result += BigUint::from(digit as u64); } let correction_exp = 4 * (i64::from(weight) - count + 1); BigDecimal::new(BigInt::from_biguint(sign, result), -correction_exp) } }
let unnecessary_zeroes = if weight >= 0 { let index_of_decimal = (weight + 1) as usize; digits .get(index_of_decimal..) .expect("enough digits exist") .iter() .rev() .take_while(|i| i.is_zero()) .count() } else { 0 };
assignment_statement
[ { "content": "pub fn eval_f64(expr: &str) -> Result<f64, meval::Error> { meval::eval_str(expr) }\n", "file_path": "src/util.rs", "rank": 1, "score": 149008.67453994806 }, { "content": "pub fn maybe_trim_parenthesis(arg: &str) -> &str {\n\n if arg.starts_with('(') && arg.ends_with(')') {\n...
Rust
api/src/models/image.rs
jpommerening/PREvant
856102242987cb6b39cc6d5096e325ff817bbb3a
/*- * ========================LICENSE_START================================= * PREvant REST API * %% * Copyright (C) 2018 - 2019 aixigo AG * %% * 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. * =========================LICENSE_END================================== */ use crate::models::service::ServiceError; use regex::Regex; use serde::{Deserialize, Deserializer}; use std::fmt::{Display, Formatter}; use std::str::FromStr; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Image { Named { image_repository: String, registry: Option<String>, image_user: Option<String>, image_tag: Option<String>, }, Digest { hash: String, }, } impl Image { pub fn tag(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository: _, registry: _, image_user: _, image_tag, } => match &image_tag { None => Some(String::from("latest")), Some(tag) => Some(tag.clone()), }, } } pub fn name(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository, registry: _, image_user, image_tag: _, } => { let user = match &image_user { None => String::from("library"), Some(user) => user.clone(), }; Some(format!("{}/{}", user, image_repository)) } } } pub fn registry(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository: _, registry, image_user: _, image_tag: _, } => Some(registry.clone().unwrap_or(String::from("docker.io"))), } } } impl FromStr for Image { type Err = ServiceError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut regex = Regex::new(r"^(sha256:)?(?P<id>[a-fA-F0-9]+)$").unwrap(); if let Some(_captures) = regex.captures(s) { return Ok(Image::Digest { hash: s.to_string(), }); } regex = Regex::new( r"^(((?P<registry>.+)/)?(?P<user>[\w-]+)/)?(?P<repo>[\w-]+)(:(?P<tag>[\w\.-]+))?$", ) .unwrap(); let captures = match regex.captures(s) { Some(captures) => captures, None => { return Err(ServiceError::InvalidImageString { invalid_string: s.to_string(), }); } }; let repo = captures .name("repo") .map(|m| String::from(m.as_str())) .unwrap(); let registry = captures.name("registry").map(|m| String::from(m.as_str())); let user = captures.name("user").map(|m| String::from(m.as_str())); let tag = captures.name("tag").map(|m| String::from(m.as_str())); Ok(Image::Named { image_repository: repo, registry, image_user: user, image_tag: tag, }) } } impl Display for Image { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match &self { Image::Digest { hash } => write!(f, "{}", hash), Image::Named { image_repository, registry, image_user, image_tag, } => { let registry = match &registry { None => String::from("docker.io"), Some(registry) => registry.clone(), }; let user = match &image_user { None => String::from("library"), Some(user) => user.clone(), }; let tag = match &image_tag { None => "latest".to_owned(), Some(tag) => tag.clone(), }; write!(f, "{}/{}/{}:{}", registry, user, image_repository, tag) } } } } impl<'de> Deserialize<'de> for Image { fn deserialize<D>(deserializer: D) -> Result<Image, D::Error> where D: Deserializer<'de>, { struct ImageVisitor; impl<'de> serde::de::Visitor<'de> for ImageVisitor { type Value = Image; fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(formatter, "a string containing a docker image reference") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(Image::from_str(v).map_err(serde::de::Error::custom)?) } } deserializer.deserialize_string(ImageVisitor) } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn should_parse_image_id_with_sha_prefix() { let image = Image::from_str( "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913", ) .unwrap(); assert_eq!( &image.to_string(), "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913" ); assert_eq!(image.name(), None); assert_eq!(image.tag(), None); } #[test] fn should_convert_to_string_for_named() { let image = Image::from_str("zammad/zammad-docker-compose").unwrap(); assert_eq!( &image.to_string(), "docker.io/zammad/zammad-docker-compose:latest" ); } #[test] fn should_convert_to_string_for_digest() { let image = Image::from_str( "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913", ) .unwrap(); assert_eq!( &image.to_string(), "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913" ); } #[test] fn should_parse_image_id() { let image = Image::from_str("9895c9b90b58").unwrap(); assert_eq!(&image.to_string(), "9895c9b90b58"); assert_eq!(image.name(), None); assert_eq!(image.tag(), None); } #[test] fn should_parse_image_with_repo_and_user() { let image = Image::from_str("zammad/zammad-docker-compose").unwrap(); assert_eq!(&image.name().unwrap(), "zammad/zammad-docker-compose"); assert_eq!(&image.tag().unwrap(), "latest"); } #[test] fn should_parse_image_with_version() { let image = Image::from_str("mariadb:10.3").unwrap(); assert_eq!(&image.name().unwrap(), "library/mariadb"); assert_eq!(&image.tag().unwrap(), "10.3"); assert_eq!(&image.to_string(), "docker.io/library/mariadb:10.3"); } #[test] fn should_parse_image_with_latest_version() { let image = Image::from_str("nginx:latest").unwrap(); assert_eq!(&image.name().unwrap(), "library/nginx"); assert_eq!(&image.tag().unwrap(), "latest"); assert_eq!(&image.to_string(), "docker.io/library/nginx:latest"); } #[test] fn should_parse_image_with_all_information() { let image = Image::from_str("docker.io/library/nginx:latest").unwrap(); assert_eq!(&image.to_string(), "docker.io/library/nginx:latest"); } #[test] fn should_parse_image_from_localhost() { let image = Image::from_str("localhost:5000/library/nginx:latest").unwrap(); assert_eq!(&image.to_string(), "localhost:5000/library/nginx:latest"); assert_eq!(&image.registry().unwrap(), "localhost:5000"); } }
/*- * ========================LICENSE_START================================= * PREvant REST API * %% * Copyright (C) 2018 - 2019 aixigo AG * %% * 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. * =========================LICENSE_END================================== */ use crate::models::service::ServiceError; use regex::Regex; use serde::{Deserialize, Deserializer}; use std::fmt::{Display, Formatter}; use std::str::FromStr; #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum Image { Named { image_repository: String, registry: Option<String>, image_user: Option<String>, image_tag: Option<String>, }, Digest { hash: String, }, } impl Image { pub fn tag(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository: _, registry: _, image_user: _, image_tag, } => match &image_tag { None => Some(String::from("latest")), Some(tag) => Some(tag.clone()), }, } } pub fn name(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository, registry: _, image_user, image_tag: _, } => { let user = match &image_user { None => String::from("library"), Some(user) => user.clone(), }; Some(format!("{}/{}", user, image_repository)) } } } pub fn registry(&self) -> Option<String> { match &self { Image::Digest { .. } => None, Image::Named { image_repository: _, registry, image_user: _, image_tag: _, } => Some(registry.clone().unwrap_or(String::from("docker.io"))), } } } impl FromStr for Image { type Err = ServiceError; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut regex = Regex::new(r"^(sha256:)?(?P<id>[a-fA-F0-9]+)$").unwrap(); if let Some(_captures) = regex.captures(s) { return Ok(Image::Digest { hash: s.to_string(), }); } regex = Regex::new( r"^(((?P<registry>.+)/)?(?P<user>[\w-]+)/)?(?P<repo>[\w-]+)(:(?P<tag>[\w\.-]+))?$", ) .unwrap(); let captures = match regex.captures(s) { Some(captures) => captures, None => { return Err(ServiceError::InvalidImageString { invalid_string: s.to_string(), }); } }; let repo = captures .name("repo") .map(|m| String::from(m.as_str())) .unwrap(); let registry = captures.name("registry").map(|m| String::from(m.as_str())); let user = captures.name("user").map(|m| String::from(m.as_str())); let tag = captures.name("tag").map(|m| String::from(m.as_str())); Ok(Image::Named { image_repository: repo, registry, image_user: user, image_tag: tag, }) } } impl Display for Image { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match &self { Image::Digest { hash } => write!(f, "{}", hash), Image::Named { image_repository, registry, image_user, image_tag, } => { let registry = match &registry { None => String::from("docker.io"), Some(registry) => registry.clone(), }; let user = match &image_user { None => String::from("library"), Some(user) => user.clone(), }; let tag = match &image_tag { None => "latest".to_owned(), Some(tag) => tag.clone(), }; write!(f, "{}/{}/{}:{}", registry, user, image_repository, tag) } } } } impl<'de> Deserialize<'de> for Image { fn deserialize<D>(deserializer: D) -> Result<Image, D::Error> where D: Deserializer<'de>, { struct ImageVisitor; impl<'de> serde::de::Visitor<'de> for ImageVisitor { type Value = Image; fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(formatter, "a string containing a docker image reference") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(Image::from_str(v).map_err(serde::de::Error::custom)?) } } deserializer.deserialize_string(ImageVisitor) } } #[cfg(test)] mod tests { use super::*; use std::str::FromStr; #[test] fn should_parse_image_id_with_sha_prefix() { let image = Image::from_str( "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913", ) .unwrap(); assert_eq!( &image.to_string(), "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913" ); assert_eq!(image.name(), None); assert_eq!(image.tag(), None); } #[test] fn should_convert_to_string_for_named() { let image = Image::from_str("zammad/zammad-docker-compose").unwrap(); assert_eq!( &image.to_string(), "docker.io/zammad/zammad-docker-compose:latest" ); } #[test] fn should_convert_to_string_for_digest() { let image = Image::from_str( "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913", ) .unwrap(); assert_eq!( &
#[test] fn should_parse_image_id() { let image = Image::from_str("9895c9b90b58").unwrap(); assert_eq!(&image.to_string(), "9895c9b90b58"); assert_eq!(image.name(), None); assert_eq!(image.tag(), None); } #[test] fn should_parse_image_with_repo_and_user() { let image = Image::from_str("zammad/zammad-docker-compose").unwrap(); assert_eq!(&image.name().unwrap(), "zammad/zammad-docker-compose"); assert_eq!(&image.tag().unwrap(), "latest"); } #[test] fn should_parse_image_with_version() { let image = Image::from_str("mariadb:10.3").unwrap(); assert_eq!(&image.name().unwrap(), "library/mariadb"); assert_eq!(&image.tag().unwrap(), "10.3"); assert_eq!(&image.to_string(), "docker.io/library/mariadb:10.3"); } #[test] fn should_parse_image_with_latest_version() { let image = Image::from_str("nginx:latest").unwrap(); assert_eq!(&image.name().unwrap(), "library/nginx"); assert_eq!(&image.tag().unwrap(), "latest"); assert_eq!(&image.to_string(), "docker.io/library/nginx:latest"); } #[test] fn should_parse_image_with_all_information() { let image = Image::from_str("docker.io/library/nginx:latest").unwrap(); assert_eq!(&image.to_string(), "docker.io/library/nginx:latest"); } #[test] fn should_parse_image_from_localhost() { let image = Image::from_str("localhost:5000/library/nginx:latest").unwrap(); assert_eq!(&image.to_string(), "localhost:5000/library/nginx:latest"); assert_eq!(&image.registry().unwrap(), "localhost:5000"); } }
image.to_string(), "sha256:9895c9b90b58c9490471b877f6bb6a90e6bdc154da7fbb526a0322ea242fc913" ); }
function_block-function_prefix_line
[ { "content": "pub fn docker() -> Cli {\n\n if INIT_LOGGER.compare_and_swap(true, false, Ordering::Relaxed) {\n\n env_logger::from_env(env_logger::Env::default().default_filter_or(\"info\")).init();\n\n }\n\n\n\n Cli::default()\n\n}\n", "file_path": "api-tests/tests/common/mod.rs", "rank"...
Rust
rs/bitcoin/canister/src/main.rs
paulyoung/ic
661ae3e3472c6ac7c455c1b75fad3e2eebf8e86f
use bitcoin::{ blockdata::constants::genesis_block, util::psbt::serialize::Deserialize, Address, Network, Transaction, }; use candid::candid_method; use ic_btc_canister::{ proto::{GetSuccessorsRequest, GetSuccessorsResponse}, store::State, }; use ic_btc_types::{ GetBalanceError, GetBalanceRequest, GetUtxosError, GetUtxosRequest, GetUtxosResponse, OutPoint, SendTransactionError, SendTransactionRequest, Utxo, }; use prost::Message; use std::{cell::RefCell, collections::VecDeque, str::FromStr}; thread_local! { static STATE: RefCell<State> = RefCell::new(State::new(1, Network::Regtest, genesis_block(Network::Regtest))); static OUTGOING_TRANSACTIONS: RefCell<VecDeque<Vec<u8>>> = RefCell::new(VecDeque::new()); } #[candid_method(update)] pub fn get_balance(request: GetBalanceRequest) -> Result<u64, GetBalanceError> { if Address::from_str(&request.address).is_err() { return Err(GetBalanceError::MalformedAddress); } let min_confirmations = request.min_confirmations.unwrap_or(0); Ok(STATE.with(|s| s.borrow().get_balance(&request.address, min_confirmations))) } #[candid_method(update)] pub fn get_utxos(request: GetUtxosRequest) -> Result<GetUtxosResponse, GetUtxosError> { if Address::from_str(&request.address).is_err() { return Err(GetUtxosError::MalformedAddress); } let min_confirmations = request.min_confirmations.unwrap_or(0); STATE.with(|s| { let main_chain_height = s.borrow().main_chain_height(); let utxos: Vec<Utxo> = s .borrow() .get_utxos(&request.address, min_confirmations) .into_iter() .map(|(outpoint, txout, height)| Utxo { outpoint: OutPoint { txid: outpoint.txid.to_vec(), vout: outpoint.vout, }, value: txout.value, height, confirmations: main_chain_height - height + 1, }) .collect(); Ok(GetUtxosResponse { total_count: utxos.len() as u32, utxos, }) }) } #[candid_method(update)] pub fn send_transaction(request: SendTransactionRequest) -> Result<(), SendTransactionError> { if Transaction::deserialize(&request.transaction).is_err() { return Err(SendTransactionError::MalformedTransaction); } OUTGOING_TRANSACTIONS.with(|txs| { txs.borrow_mut().push_back(request.transaction); }); Ok(()) } pub fn get_successors_request() -> Vec<u8> { let block_hashes = STATE.with(|state| { let state = state.borrow(); state .get_unstable_blocks() .iter() .map(|b| b.block_hash().to_vec()) .collect() }); println!("block hashes: {:?}", block_hashes); GetSuccessorsRequest { block_hashes }.encode_to_vec() } pub fn has_outgoing_transaction() -> bool { OUTGOING_TRANSACTIONS.with(|txs| !txs.borrow_mut().is_empty()) } pub fn get_outgoing_transaction() -> Option<Vec<u8>> { OUTGOING_TRANSACTIONS.with(|txs| txs.borrow_mut().pop_front()) } pub fn get_successors_response(response_vec: Vec<u8>) -> u32 { let response = GetSuccessorsResponse::decode(&*response_vec).unwrap(); for block_proto in response.blocks { let block = ic_btc_canister::block::from_proto(&block_proto); println!("Processing block with hash: {}", block.block_hash()); STATE.with(|state| { let block_hash = block.block_hash(); if state.borrow_mut().insert_block(block).is_err() { println!( "Received block that doesn't extend existing blocks: {}", block_hash ); } }); } STATE.with(|state| state.borrow().main_chain_height()) } fn main() {} #[cfg(test)] mod test { use super::*; use bitcoin::secp256k1::rand::rngs::OsRng; use bitcoin::secp256k1::Secp256k1; use bitcoin::{Address, PublicKey}; use ic_btc_canister::test_builder::{BlockBuilder, TransactionBuilder}; #[test] fn check_candid_interface_compatibility() { use candid::types::subtype::{subtype, Gamma}; use candid::types::Type; use candid::{self}; use std::io::Write; use std::path::PathBuf; candid::export_service!(); let actual_interface = __export_service(); println!("Generated DID:\n {}", actual_interface); let mut tmp = tempfile::NamedTempFile::new().expect("failed to create a temporary file"); write!(tmp, "{}", actual_interface).expect("failed to write interface to a temporary file"); let (mut env1, t1) = candid::pretty_check_file(tmp.path()).expect("failed to check generated candid file"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("candid.did"); let (env2, t2) = candid::pretty_check_file(path.as_path()).expect("failed to open candid.did file"); let (t1_ref, t2) = match (t1.as_ref().unwrap(), t2.unwrap()) { (Type::Class(_, s1), Type::Class(_, s2)) => (s1.as_ref(), *s2), (Type::Class(_, s1), s2 @ Type::Service(_)) => (s1.as_ref(), s2), (s1 @ Type::Service(_), Type::Class(_, s2)) => (s1, *s2), (t1, t2) => (t1, t2), }; let mut gamma = Gamma::new(); let t2 = env1.merge_type(env2, t2); subtype(&mut gamma, &env1, t1_ref, &t2) .expect("bitcoin canister interface is not compatible with the candid.did file"); } #[test] fn get_utxos_from_existing_utxo_set() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address, 1000) .build(); let genesis_block = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); STATE.with(|s| s.replace(State::new(0, *network, genesis_block))); assert_eq!( get_utxos(GetUtxosRequest { address: address.to_string(), min_confirmations: None }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: coinbase_tx.txid().to_vec(), vout: 0 }, value: 1000, height: 1, confirmations: 1 }], total_count: 1 }) ); } } #[test] fn get_balance_malformed_address() { assert_eq!( get_balance(GetBalanceRequest { address: String::from("not an address"), min_confirmations: None }), Err(GetBalanceError::MalformedAddress) ); } #[test] fn get_utxos_malformed_address() { assert_eq!( get_utxos(GetUtxosRequest { address: String::from("not an address"), min_confirmations: None }), Err(GetUtxosError::MalformedAddress) ); } #[test] fn get_balance_test() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address_1 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let address_2 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address_1, 1000) .build(); let block_0 = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); let tx = TransactionBuilder::with_input(bitcoin::OutPoint::new(coinbase_tx.txid(), 0)) .with_output(&address_2, 1000) .build(); let block_1 = BlockBuilder::with_prev_header(block_0.header) .with_transaction(tx.clone()) .build(); STATE.with(|s| { s.replace(State::new(2, *network, block_0)); s.borrow_mut().insert_block(block_1).unwrap(); }); for min_confirmations in [None, Some(0), Some(1)].iter() { assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: *min_confirmations }), Ok(1000) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: *min_confirmations }), Ok(0) ); } assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: Some(2) }), Ok(0) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: Some(2) }), Ok(1000) ); for i in 3..10 { assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: Some(i) }), Ok(0) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: Some(i) }), Ok(0) ); } } } #[test] fn get_utxos_min_confirmations() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address_1 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let address_2 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address_1, 1000) .build(); let block_0 = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); let tx = TransactionBuilder::with_input(bitcoin::OutPoint::new(coinbase_tx.txid(), 0)) .with_output(&address_2, 1000) .build(); let block_1 = BlockBuilder::with_prev_header(block_0.header) .with_transaction(tx.clone()) .build(); STATE.with(|s| { s.replace(State::new(2, *network, block_0)); s.borrow_mut().insert_block(block_1).unwrap(); }); for min_confirmations in [None, Some(0), Some(1)].iter() { assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: *min_confirmations }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: tx.txid().to_vec(), vout: 0, }, value: 1000, height: 2, confirmations: 1, }], total_count: 1 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: *min_confirmations }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); } assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: Some(2) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: Some(2) }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: coinbase_tx.txid().to_vec(), vout: 0, }, value: 1000, height: 1, confirmations: 2, }], total_count: 1 }) ); for i in 3..10 { assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: Some(i) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: Some(i) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); } } } #[test] fn malformed_transaction() { assert_eq!( send_transaction(SendTransactionRequest { transaction: vec![1, 2, 3], }), Err(SendTransactionError::MalformedTransaction) ); } }
use bitcoin::{ blockdata::constants::genesis_block, util::psbt::serialize::Deserialize, Address, Network, Transaction, }; use candid::candid_method; use ic_btc_canister::{ proto::{GetSuccessorsRequest, GetSuccessorsResponse}, store::State, }; use ic_btc_types::{ GetBalanceError, GetBalanceRequest, GetUtxosError, GetUtxosRequest, GetUtxosResponse, OutPoint, SendTransactionError, SendTransactionRequest, Utxo, }; use prost::Message; use std::{cell::RefCell, collections::VecDeque, str::FromStr}; thread_local! { static STATE: RefCell<State> = RefCell::new(State::new(1, Network::Regtest, genesis_block(Network::Regtest))); static OUTGOING_TRANSACTIONS: RefCell<VecDeque<Vec<u8>>> = RefCell::new(VecDeque::new()); } #[candid_method(update)] pub fn get_balance(request: GetBalanceRequest) -> Result<u64, GetBalanceError> { if Address::from_str(&request.address).is_err() { return Err(GetBalanceError::MalformedAddress); } let min_confirmations = request.min_confirmations.unwrap_or(0); Ok(STATE.with(|s| s.borrow().get_balance(&request.address, min_confirmations))) } #[candid_method(update)] pub fn get_utxos(request: GetUtxosRequest) -> Result<GetUtxosResponse, GetUtxosError> { if Address::from_str(&request.address).is_err() { return Err(GetUtxosError::MalformedAddress); } let min_confirmations = request.min_confirmations.unwrap_or(0); STATE.with(|s| { let main_chain_height = s.borrow().main_chain_height(); let utxos: Vec<Utxo> = s .borrow() .get_utxos(&request.address, min_confirmations) .into_iter() .map(|(outpoint, txout, height)| Utxo { outpoint: OutPoint { txid: outpoint.txid.to_vec(), vout: outpoint.vout, }, value: txout.value, height, confirmations: main_chain_height - height + 1, }) .collect(); Ok(GetUtxosResponse { total_count: utxos.len() as u32, utxos, }) }) } #[candid_method(update)] pub fn send_transaction(request: SendTransactionRequest) -> Result<(), SendTransactionError> { if Transaction::deserialize(&request.transaction).is_err() { return Err(SendTransactionError::MalformedTransaction); } OUTGOING_TRANSACTIONS.with(|txs| { txs.borrow_mut().push_back(request.transaction); }); Ok(()) } pub fn get_successors_request() -> Vec<u8> { let block_hashes = STATE.with(|state| { let state = state.borrow(); state .get_unstable_blocks() .iter() .map(|b| b.block_hash().to_vec()) .collect() }); println!("block hashes: {:?}", block_hashes); GetSuccessorsRequest { block_hashes }.encode_to_vec() } pub fn has_outgoing_transaction() -> bool { OUTGOING_TRANSACTIONS.with(|txs| !txs.borrow_mut().is_empty()) } pub fn get_outgoing_transaction() -> Option<Vec<u8>> { OUTGOING_TRANSACTIONS.with(|txs| txs.borrow_mut().pop_front()) } pub fn get_successors_response(response_vec: Vec<u8>) -> u32 { let response = GetSuccessorsResponse::decode(&*response_vec).unwrap(); for block_proto in response.blocks { let block = ic_btc_canister::block::from_proto(&block_proto); println!("Processing block with hash: {}", block.block_hash()); STATE.with(|state| { let block_hash = block.block_hash(); if state.borrow_mut().insert_block(block).is_err() { println!( "Received block that doesn't extend existing blocks: {}", block_hash ); } }); } STATE.with(|state| state.borrow().main_chain_height()) } fn main() {} #[cfg(test)] mod test { use super::*; use bitcoin::secp256k1::rand::rngs::OsRng; use bitcoin::secp256k1::Secp256k1; use bitcoin::{Address, PublicKey}; use ic_btc_canister::test_builder::{BlockBuilder, TransactionBuilder}; #[test] fn check_candid_interface_compatibility() { use candid::types::subtype::{subtype, Gamma}; use candid::types::Type; use candid::{self}; use std::io::Write; use std::path::PathBuf; candid::export_service!(); let actual_interface = __export_service(); println!("Generated DID:\n {}", actual_interface); let mut tmp = tempfile::NamedTempFile::new().expect("failed to create a temporary file"); write!(tmp, "{}", actual_interface).expect("failed to write interface to a temporary file"); let (mut env1, t1) = candid::pretty_check_file(tmp.path()).expect("failed to check generated candid file"); let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("candid.did"); let (env2, t2) = candid::pretty_check_file(path.as_path()).expect("failed to open candid.did file"); let (t1_ref, t2) = match (t1.as_ref().unwrap(), t2.unwrap()) { (Type::Class(_, s1), Type::Class(_, s2)) => (s1.as_ref(), *s2), (Type::Class(_, s1), s2 @ Type::Service(_)) => (s1.as_ref(), s2), (s1 @ Type::Service(_), Type::Class(_, s2)) => (s1, *s2), (t1, t2) => (t1, t2), }; let mut gamma = Gamma::new(); let t2 = env1.merge_type(env2, t2); subtype(&mut gamma, &env1, t1_ref, &t2) .expect("bitcoin canister interface is not compatible with the candid.did file"); } #[test] fn get_utxos_from_existing_utxo_set() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address, 1000) .build(); let genesis_block = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); STATE.with(|s| s.replace(State::new(0, *network, genesis_block))); assert_eq!( get_utxos(GetUtxosRequest { address: address.to_string(), min_confirmations: None }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: coinbase_tx.txid().to_vec(), vout: 0 }, value: 1000, height: 1, confirmations: 1 }], total_count: 1 }) ); } } #[test] fn get_balance_malformed_address() { assert_eq!( get_balance(GetBalanceRequest { address: String::from("not an address"), min_confirmations: None }), Err(GetBalanceError::MalformedAddress) ); } #[test] fn get_utxos_malformed_address() { assert_eq!( get_utxos(GetUtxosRequest { address: String::from("not an address"), min_confirmations: None }), Err(GetUtxosError::MalformedAddress) ); } #[test] fn get_balance_test() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address_1 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let address_2 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address_1, 1000) .build(); let block_0 = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); let tx = TransactionBuilder::with_input(bitcoin::OutPoint::new(coinbase_tx.txid(), 0)) .with_output(&address_2, 1000) .build(); let block_1 = BlockBuilder::with_prev_header(block_0.header) .with_transaction(tx.clone()) .build(); STATE.with(|s| { s.replace(State::new(2, *network, block_0)); s.borrow_mut().insert_block(block_1).unwrap(); }); for min_confirmations in [None, Some(0), Some(1)].iter() { assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: *min_confirmations }), Ok(1000) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: *min_confirmations }), Ok(0) ); } assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: Some(2) }), Ok(0) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: Some(2) }), Ok(1000) ); for i in 3..10 { assert_eq!( get_balance(GetBalanceRequest { address: address_2.to_string(), min_confirmations: Some(i) }), Ok(0) ); assert_eq!( get_balance(GetBalanceRequest { address: address_1.to_string(), min_confirmations: Some(i) }), Ok(0) ); } } } #[test] fn get_utxos_min_confirmations() { for network in [ Network::Bitcoin, Network::Regtest, Network::Testnet, Network::Signet, ] .iter() { let address_1 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let address_2 = { let secp = Secp256k1::new(); let mut rng = OsRng::new().unwrap(); Address::p2pkh(&PublicKey::new(secp.generate_keypair(&mut rng).1), *network) }; let coinbase_tx = TransactionBuilder::coinbase() .with_output(&address_1, 1000) .build(); let bl
#[test] fn malformed_transaction() { assert_eq!( send_transaction(SendTransactionRequest { transaction: vec![1, 2, 3], }), Err(SendTransactionError::MalformedTransaction) ); } }
ock_0 = BlockBuilder::genesis() .with_transaction(coinbase_tx.clone()) .build(); let tx = TransactionBuilder::with_input(bitcoin::OutPoint::new(coinbase_tx.txid(), 0)) .with_output(&address_2, 1000) .build(); let block_1 = BlockBuilder::with_prev_header(block_0.header) .with_transaction(tx.clone()) .build(); STATE.with(|s| { s.replace(State::new(2, *network, block_0)); s.borrow_mut().insert_block(block_1).unwrap(); }); for min_confirmations in [None, Some(0), Some(1)].iter() { assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: *min_confirmations }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: tx.txid().to_vec(), vout: 0, }, value: 1000, height: 2, confirmations: 1, }], total_count: 1 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: *min_confirmations }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); } assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: Some(2) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: Some(2) }), Ok(GetUtxosResponse { utxos: vec![Utxo { outpoint: OutPoint { txid: coinbase_tx.txid().to_vec(), vout: 0, }, value: 1000, height: 1, confirmations: 2, }], total_count: 1 }) ); for i in 3..10 { assert_eq!( get_utxos(GetUtxosRequest { address: address_2.to_string(), min_confirmations: Some(i) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); assert_eq!( get_utxos(GetUtxosRequest { address: address_1.to_string(), min_confirmations: Some(i) }), Ok(GetUtxosResponse { utxos: vec![], total_count: 0 }) ); } } }
function_block-function_prefixed
[ { "content": "fn main() -> Result<()> {\n\n prost_build::compile_protos(&[\"src/proto.proto\"], &[\"src/\"])?;\n\n #[cfg(feature = \"tonic-build\")]\n\n tonic_build::compile_protos(\"src/proto.proto\")?;\n\n Ok(())\n\n}\n", "file_path": "rs/bitcoin/canister/build.rs", "rank": 3, "score":...
Rust
src/ast.rs
namachan10777/jubilant-octo-telegram
1978e5694a0e86d995f56e548095ff23bdcc3e10
use std::collections::HashMap; use yaml_rust::Yaml; #[derive(Debug, Clone, PartialEq)] pub enum Value { Int(i64), Real(f64), Str(String), Bool(bool), Array(Vec<Value>), Hash(HashMap<String, Value>), } #[derive(Debug)] pub enum ConvError { YamlAlias, YamlBadValue, YamlNull, YamlInvalidHashKey(Yaml), YamlCannotParseReal(String), } impl Value { pub fn from_yaml(yaml: Yaml) -> Result<Self, ConvError> { match yaml { Yaml::Alias(_) => Err(ConvError::YamlAlias), Yaml::Array(arr) => Ok(Value::Array( arr.into_iter() .map(Self::from_yaml) .collect::<Result<Vec<_>, _>>()?, )), Yaml::BadValue => Err(ConvError::YamlBadValue), Yaml::Boolean(b) => Ok(Value::Bool(b)), Yaml::Hash(hash) => Ok(Value::Hash( hash.into_iter() .map(|(key, val)| match key { Yaml::Boolean(b) => Ok((b.to_string(), Self::from_yaml(val)?)), Yaml::Integer(i) => Ok((i.to_string(), Self::from_yaml(val)?)), Yaml::Real(s) => Ok((s, Self::from_yaml(val)?)), Yaml::String(s) => Ok((s, Self::from_yaml(val)?)), Yaml::Null => Ok(("null".to_owned(), Self::from_yaml(val)?)), yaml => Err(ConvError::YamlInvalidHashKey(yaml)), }) .collect::<Result<HashMap<_, _>, _>>()?, )), Yaml::Integer(i) => Ok(Value::Int(i)), Yaml::Null => Err(ConvError::YamlNull), Yaml::Real(r) => Ok(Value::Real( r.parse().map_err(|_| ConvError::YamlCannotParseReal(r))?, )), Yaml::String(s) => Ok(Value::Str(s)), } } } impl Value { pub fn as_hash(&self) -> Option<&HashMap<String, Self>> { match &self { Value::Hash(h) => Some(h), _ => None, } } pub fn as_array(&self) -> Option<&Vec<Self>> { if let Value::Array(arr) = &self { Some(arr) } else { None } } pub fn as_str(&self) -> Option<&str> { if let Value::Str(s) = &self { Some(s) } else { None } } pub fn as_bool(&self) -> Option<bool> { if let Value::Bool(b) = &self { Some(*b) } else { None } } } fn not_allowed_member<'a, K, T>(map: &'a HashMap<K, T>, allowed: &[&K]) -> Vec<(&'a K, &'a T)> where K: PartialEq, { map.iter() .filter_map(|(key, val)| { if allowed.contains(&key) { None } else { Some((key, val)) } }) .collect::<Vec<_>>() } pub fn verify_hash( hash: &HashMap<String, Value>, allowed: &[&str], prefix: Option<&str>, ) -> Result<(), crate::Error> { let allowed = allowed.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(); let not_allowed = not_allowed_member(hash, allowed.iter().collect::<Vec<_>>().as_slice()); if !not_allowed.is_empty() { return Err(crate::Error::UnrecognizedMembers { prefix: prefix.map(|s| s.to_owned()), members: not_allowed .iter() .map(|(k, v)| ((*k).clone(), (*v).clone())) .collect::<Vec<_>>(), }); } else { Ok(()) } } #[cfg(test)] mod test { use super::*; use maplit::hashmap; #[test] fn test_not_allowed_member() { let map = hashmap! { "a" => 1, "b" => 2, "c" => 3, "d" => 4, }; let mut not_allowed = not_allowed_member(&map, &[&"a", &"c"]); not_allowed.sort_by(|(k1, _), (k2, _)| k1.cmp(&k2)); assert_eq!(not_allowed, vec![(&"b", &2), (&"d", &4)]); } }
use std::collections::HashMap; use yaml_rust::Yaml; #[derive(Debug, Clone, PartialEq)] pub enum Value { Int(i64), Real(f64), Str(String), Bool(bool), Array(Vec<Value>), Hash(HashMap<String, Value>), } #[derive(Debug)] pub enum ConvError { YamlAlias, YamlBadValue, YamlNull, YamlInvalidHashKey(Yaml), YamlCannotParseReal(String), } impl Value { pub fn from_yaml(yaml: Yaml) -> Result<Self, ConvError> { match yaml { Yaml::Alias(_) => Err(ConvError::YamlAlias), Yaml::Array(arr) => Ok(Value::Array( arr.into_iter() .map(Self::from_yaml) .collect::<Result<Vec<_>, _>>()?, )), Yaml::BadValue => Err(ConvError::YamlBadValue), Yaml::Boolean(b) => Ok(Value::Bool(b)), Yaml::Hash(hash) => Ok(Value::Hash( hash.into_iter() .map(|(key, val)| match key { Yaml::Boolean(b) => Ok((b.to_string(), Self::from_yaml(val)?)), Yaml::Integer(i) => Ok((i.to_string(), Self::from_yaml(val)?)), Yaml::Real(s) => Ok((s, Self::from_yaml(val)?)), Yaml::String(s) => Ok((s, Self::from_yaml(val)?)), Yaml::Null => Ok(("null".to_owned(), Self::from_yaml(val)?)), yaml => Err(ConvError::YamlInvalidHashKey(yaml)), }) .collect::<Result<HashMap<_, _>, _>>()?, )), Yaml::Integer(i) => Ok(Value::Int(i)), Yaml::Null => Err(ConvError::YamlNull), Yaml::Real(r) => Ok(Value::Real( r.parse().map_err(|_| ConvError::YamlCannotParseReal(r))?, )), Yaml::String(s) => Ok(Value::Str(s)), } } } impl Value { pub fn as_hash(&self) -> Option<&HashMap<String, Self>> { match &self { Value::Hash(h) => Some(h), _ => None, } } pub fn as_array(&self) -> Option<&Vec<Self>> { if let Value::Array(arr) = &self { Some(arr) } else { None } } pub fn as_str(&self) -> Option<&str> { if let Value::Str(s) = &self { Some(s) } else { None } } pub fn as_bool(&self) -> Option<bool> { if let Value::Bool(b) = &self { Some(*b) } else { None } } } fn not_allowed_member<'a, K, T>(map: &'a HashMap<K, T>, allowed: &[&K]) -> Vec<(&'a K, &'a T)> where K: PartialEq, { map.iter() .filter_map(|(key, val)| { if allowed.contains(&key) { None } else { Some((key, val)) } }) .collect::<Vec<_>>() } pub fn verify_hash( hash: &HashMap<String, Value>, allowed: &[&str], prefix: Option<&str>, ) -> Result<(), crate::Error> { let allowed = allowed.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>(); let not_allowed = not_allowed_member(hash, allowed.iter().collect::<Vec<_>>().as_slice()); if !not_allowed.is_empty() { return Err(crate::Error::UnrecognizedMembers { prefix: prefix.map(|s| s.to_owned()), members: not_allowed .iter() .map(|(k, v)| ((*k).clone(), (*v).clone())) .collect::<Vec<_>>(), }); } else { Ok(()) } } #[cfg(test)] mod test { use super::*; use maplit::hashmap; #[test]
}
fn test_not_allowed_member() { let map = hashmap! { "a" => 1, "b" => 2, "c" => 3, "d" => 4, }; let mut not_allowed = not_allowed_member(&map, &[&"a", &"c"]); not_allowed.sort_by(|(k1, _), (k2, _)| k1.cmp(&k2)); assert_eq!(not_allowed, vec![(&"b", &2), (&"d", &4)]); }
function_block-full_function
[ { "content": "fn yaml_to_str(yaml: &crate::ast::Value) -> Result<Option<String>, crate::Error> {\n\n match &yaml {\n\n crate::ast::Value::Str(s) => Ok(Some(s.clone())),\n\n crate::ast::Value::Real(r) => Ok(Some(r.to_string())),\n\n crate::ast::Value::Int(i) => Ok(Some(i.to_string())),\n\...
Rust
src/sys/pkg/bin/omaha-client/src/storage/stash.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use omaha_client::storage::Storage; use fidl::endpoints::create_proxy; use fidl_fuchsia_stash::{Store2Marker, StoreAccessorMarker, StoreAccessorProxy, Value}; use futures::future::BoxFuture; use futures::prelude::*; use log::{error, warn}; use thiserror::Error; type Result<T> = std::result::Result<T, StashError>; #[derive(Debug, Error)] pub enum StashError { #[error("generic error")] Failure(#[from] anyhow::Error), #[error("FIDL error")] FIDL(#[from] fidl::Error), #[error("Stash not available")] NotAvailable, } pub struct Stash { proxy: Option<StoreAccessorProxy>, } impl Stash { pub async fn new(identity: &str) -> Self { let proxy = Self::new_proxy(identity).await; if let Err(e) = &proxy { error!("Failed to connect to stash: {}", e); } Stash { proxy: proxy.ok() } } async fn new_proxy(identity: &str) -> Result<StoreAccessorProxy> { let stash_svc = fuchsia_component::client::connect_to_protocol::<Store2Marker>()?; stash_svc.identify(identity)?; let (proxy, server_end) = create_proxy::<StoreAccessorMarker>()?; stash_svc.create_accessor(false, server_end)?; Ok(proxy) } #[cfg(test)] fn new_mock() -> (Self, fidl_fuchsia_stash::StoreAccessorRequestStream) { let (proxy, server_end) = create_proxy::<StoreAccessorMarker>().unwrap(); (Stash { proxy: Some(proxy) }, server_end.into_stream().unwrap()) } async fn get_value<'a>(&'a self, key: &'a str) -> Option<Box<Value>> { let result = self.proxy.as_ref()?.get_value(key).await; match result { Ok(opt_value) => opt_value, Err(e) => { error!("Unable to read from stash for key: {}; {}", key, e); None } } } fn set_value<'a>(&'a self, key: &'a str, mut value: Value) -> Result<()> { let proxy = self.proxy.as_ref().ok_or(StashError::NotAvailable)?; match proxy.set_value(key, &mut value) { Ok(_) => Ok(()), Err(e) => { error!("Unable to write to stash for key: {}; {}", key, e); Err(e.into()) } } } } impl Storage for Stash { type Error = StashError; fn get_string<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<String>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Stringval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not a Stringval, is: {:?}", key, v) } None } .boxed() } fn get_int<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<i64>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Intval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not an Intval, is: {:?}", key, v) } None } .boxed() } fn get_bool<'a>(&'a self, key: &'a str) -> BoxFuture<'_, Option<bool>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Boolval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not a Boolval, is: {:?}", key, v) } None } .boxed() } fn set_string<'a>(&'a mut self, key: &'a str, value: &'a str) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Stringval(value.to_string()))).boxed() } fn set_int<'a>(&'a mut self, key: &'a str, value: i64) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Intval(value))).boxed() } fn set_bool<'a>(&'a mut self, key: &'a str, value: bool) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Boolval(value))).boxed() } fn remove<'a>(&'a mut self, key: &'a str) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.delete_value(key) { Ok(_) => Ok(()), Err(e) => { error!("Unable to write to stash for key: {}; {}", key, e); Err(e.into()) } }, None => Err(StashError::NotAvailable), }) .boxed() } fn commit(&mut self) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.commit() { Ok(_) => Ok(()), Err(e) => { error!("Unable to commit changes to stash! {}", e); Err(e.into()) } }, None => Err(StashError::NotAvailable), }) .boxed() } } #[cfg(test)] mod tests { use super::*; use fidl_fuchsia_stash::StoreAccessorRequest; use fuchsia_async as fasync; use omaha_client::storage::tests::*; #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_string() { let mut storage = Stash::new("test_set_get_remove_string").await; do_test_set_get_remove_string(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_int() { let mut storage = Stash::new("test_set_get_remove_int").await; do_test_set_get_remove_int(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_option_int() { let mut storage = Stash::new("test_set_option_int").await; do_test_set_option_int(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_bool() { let mut storage = Stash::new("test_set_get_remove_bool").await; do_test_set_get_remove_bool(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_time() { let mut storage = Stash::new("test_set_get_remove_time").await; do_test_set_get_remove_time(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_return_none_for_wrong_value_type() { let mut storage = Stash::new("test_return_none_for_wrong_value_type").await; do_return_none_for_wrong_value_type(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_ensure_no_error_remove_nonexistent_key() { let mut storage = Stash::new("test_ensure_no_error_remove_nonexistent_key").await; do_ensure_no_error_remove_nonexistent_key(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_commit() { let (mut storage, mut stream) = Stash::new_mock(); storage.commit().await.unwrap(); match stream.next().await.unwrap() { Ok(StoreAccessorRequest::Commit { .. }) => {} request => panic!("Unexpected request: {:?}", request), } } }
use omaha_client::storage::Storage; use fidl::endpoints::create_proxy; use fidl_fuchsia_stash::{Store2Marker, StoreAccessorMarker, StoreAccessorProxy, Value}; use futures::future::BoxFuture; use futures::prelude::*; use log::{error, warn}; use thiserror::Error; type Result<T> = std::result::Result<T, StashError>; #[derive(Debug, Error)] pub enum StashError { #[error("generic error")] Failure(#[from] anyhow::Error), #[error("FIDL error")] FIDL(#[from] fidl::Error), #[error("Stash not available")] NotAvailable, } pub struct Stash { proxy: Option<StoreAccessorProxy>, } impl Stash { pub async fn new(identity: &str) -> Self { let proxy = Self::new_proxy(identity).await; if let Err(e) = &proxy { error!("Failed to connect to stash: {}", e); } Stash { proxy: proxy.ok() } } async fn new_proxy(identity: &str) -> Result<StoreAccessorProxy> { let stash_svc = fuchsia_component::client::connect_to_protocol::<Store2Marker>()?; stash_svc.identify(identity)?; let (proxy, server_end) = create_proxy::<StoreAccessorMarker>()?; stash_svc.create_accessor(false, server_end)?; Ok(proxy) } #[cfg(test)] fn new_mock() -> (Self, fidl_fuchsia_stash::StoreAccessorRequestStream) { let (proxy, server_end) = create_proxy::<StoreAccessorMarker>().unwrap(); (Stash { proxy: Some(proxy) }, server_end.into_stream().unwrap()) } async fn get_value<'a>(&'a self, key: &'a str) -> Option<Box<Value>> { let result = self.proxy.as_ref()?.get_value(key).await; match result { Ok(opt_value) => opt_value, Err(e) => { error!("Unable to read from stash for key: {}; {}", key, e); None } } } fn set_value<'a>(&'a self, key: &'a str, mut value: Value) -> Result<()> { let proxy = self.proxy.as_ref().ok_or(StashError::NotAvailable)?; match proxy.set_value(key, &mut value) { Ok(_) => Ok(()), Err(e) => { error!("Unable to write to stash for key: {}; {}", key, e); Err(e.into()) } } } } impl Storage for Stash { type Error = StashError; fn get_string<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<String>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Stringval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not a Stringval, is: {:?}", key, v) } None } .boxed() } fn get_int<'a>(&'a self, key: &'a str) -> BoxFuture<'a, Option<i64>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Intval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not an Intval, is: {:?}", key, v) } None } .boxed() } fn get_bool<'a>(&'a self, key: &'a str) -> BoxFuture<'_, Option<bool>> { async move { if let Some(v) = self.get_value(key).await { if let Value::Boolval(s) = *v { return Some(s); } warn!("found key '{}' in stash, but it was not a Boolval, is: {:?}", key, v) } None } .boxed() } fn set_string<'a>(&'a mut self, key: &'a str, value: &'a str) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Stringval(value.to_string()))).boxed() } fn set_int<'a>(&'a mut self, key: &'a str, value: i64) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Intval(value))).boxed() } fn set_bool<'a>(&'a mut self, key: &'a str, value: bool) -> BoxFuture<'_, Result<()>> { future::ready(self.set_value(key, Value::Boolval(value))).boxed() }
fn commit(&mut self) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.commit() { Ok(_) => Ok(()), Err(e) => { error!("Unable to commit changes to stash! {}", e); Err(e.into()) } }, None => Err(StashError::NotAvailable), }) .boxed() } } #[cfg(test)] mod tests { use super::*; use fidl_fuchsia_stash::StoreAccessorRequest; use fuchsia_async as fasync; use omaha_client::storage::tests::*; #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_string() { let mut storage = Stash::new("test_set_get_remove_string").await; do_test_set_get_remove_string(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_int() { let mut storage = Stash::new("test_set_get_remove_int").await; do_test_set_get_remove_int(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_option_int() { let mut storage = Stash::new("test_set_option_int").await; do_test_set_option_int(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_bool() { let mut storage = Stash::new("test_set_get_remove_bool").await; do_test_set_get_remove_bool(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_set_get_remove_time() { let mut storage = Stash::new("test_set_get_remove_time").await; do_test_set_get_remove_time(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_return_none_for_wrong_value_type() { let mut storage = Stash::new("test_return_none_for_wrong_value_type").await; do_return_none_for_wrong_value_type(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_ensure_no_error_remove_nonexistent_key() { let mut storage = Stash::new("test_ensure_no_error_remove_nonexistent_key").await; do_ensure_no_error_remove_nonexistent_key(&mut storage).await; } #[fasync::run_singlethreaded(test)] async fn test_commit() { let (mut storage, mut stream) = Stash::new_mock(); storage.commit().await.unwrap(); match stream.next().await.unwrap() { Ok(StoreAccessorRequest::Commit { .. }) => {} request => panic!("Unexpected request: {:?}", request), } } }
fn remove<'a>(&'a mut self, key: &'a str) -> BoxFuture<'_, Result<()>> { future::ready(match &self.proxy { Some(proxy) => match proxy.delete_value(key) { Ok(_) => Ok(()), Err(e) => { error!("Unable to write to stash for key: {}; {}", key, e); Err(e.into()) } }, None => Err(StashError::NotAvailable), }) .boxed() }
function_block-full_function
[]
Rust
src/process/process_group.rs
krhancoc/fastfreeze
71435e7f2d7c01d81ce54aa28b5b28ccadeed748
use anyhow::{Result, Context}; use std::{ os::unix::io::AsRawFd, io::{ErrorKind, Read}, time::{Duration, Instant}, fs, iter, }; use nix::{ poll::{PollFd, PollFlags}, fcntl::OFlag, sys::signal, }; use crate::{ consts::*, util::{poll_nointr, Pipe}, }; use super::{Process, ProcessError, ProcessGroupError}; pub struct ProcessGroup { sigchld_pipe: fs::File, children: Vec<ProcessMembership>, kill_grace_period: Duration, sig_hook_id: Option<signal_hook::SigId>, } pub struct ProcessMembership { inner: Process, exited: bool, killable: bool, daemon: bool, } #[derive(Clone, Copy, Debug)] pub struct ProcessHandle(usize); impl From<Process> for ProcessMembership { fn from(inner: Process) -> Self { Self { inner, exited: false, killable: true, daemon: false } } } impl ProcessMembership { pub fn non_killable(self) -> Self { Self { killable: false, ..self } } pub fn daemon(self) -> Self { Self { daemon: true, ..self } } } impl ProcessGroup { pub fn new() -> Result<Self> { Self::with_kill_grace_period(Duration::from_secs(KILL_GRACE_PERIOD_SECS)) } pub fn with_kill_grace_period(kill_grace_period: Duration) -> Result<Self> { let pipe = Pipe::new(OFlag::O_CLOEXEC | OFlag::O_NONBLOCK)?; let sig_hook_id = Some(signal_hook::low_level::pipe::register( signal_hook::consts::SIGCHLD, pipe.write) .context("Failed to register signal")?); Ok(Self { sigchld_pipe: pipe.read, children: Vec::new(), kill_grace_period, sig_hook_id, }) } pub fn add(&mut self, proc: impl Into<ProcessMembership>) -> ProcessHandle { self.children.push(proc.into()); ProcessHandle(self.children.len() - 1) } pub fn get_mut(&mut self, id: ProcessHandle) -> &mut Process { &mut self.children[id.0].inner } fn drain_sigchld_pipe(&mut self) { let mut vec = Vec::new(); match self.sigchld_pipe.read_to_end(&mut vec) { Err(e) if e.kind() == ErrorKind::WouldBlock => {} result => { result.expect("SIGCHLD pipe has draining issues"); } } } pub fn try_wait_for_success(&mut self) -> Result<bool> { self.drain_sigchld_pipe(); let mut errors = Vec::new(); for child in &mut self.children { if child.inner.try_wait()?.is_some() { child.exited = true; if let Err(err) = child.inner.wait_for_success() { errors.push(err.downcast::<ProcessError>()?); } } } if !errors.is_empty() { bail!(ProcessGroupError { errors }); } Ok(self.children.iter().any(|c| !c.exited && !c.daemon)) } pub fn poll_fds(&self) -> Vec<PollFd> { self.children.iter() .filter_map(|c| c.inner.stderr_logger_fd()) .chain(iter::once(self.sigchld_pipe.as_raw_fd())) .map(|fd| PollFd::new(fd, PollFlags::POLLIN)) .collect() } pub fn wait_for_success(&mut self) -> Result<()> { while self.try_wait_for_success()? { let timeout = -1; poll_nointr(&mut self.poll_fds(), timeout) .context("Failed to poll()")?; } Ok(()) } pub fn terminate(&mut self) -> Result<()> { let mut killables = self.children.iter_mut() .filter(|c| c.killable && !c.exited) .collect::<Vec<_>>(); for child in &mut killables { if child.inner.try_wait()?.is_none() { child.inner.kill(signal::SIGTERM)?; } } let deadline = Instant::now() + self.kill_grace_period; for child in &mut killables { if child.inner.wait_timeout(deadline)?.is_none() { child.inner.kill(signal::SIGKILL)?; } } for child in &mut self.children { child.inner.wait()?; child.exited = true; } if let Some(sig_hook_id) = self.sig_hook_id.take() { ensure!(signal_hook::low_level::unregister(sig_hook_id), "signal_hook failed to unregister"); } Ok(()) } } impl Drop for ProcessGroup { fn drop(&mut self) { let _ = self.terminate() .map_err(|e| error!("Skipping children termination: {}", e)); } } pub trait ProcessExt { fn join(self, pgrp: &mut ProcessGroup) -> ProcessHandle; fn join_as_non_killable(self, pgrp: &mut ProcessGroup) -> ProcessHandle; fn join_as_daemon(self, pgrp: &mut ProcessGroup) -> ProcessHandle; } impl ProcessExt for Process { fn join(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(self) } fn join_as_non_killable(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(ProcessMembership::from(self).non_killable()) } fn join_as_daemon(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(ProcessMembership::from(self).daemon()) } } #[cfg(test)] mod test { use super::*; use super::super::*; use nix::sys::signal::Signal; fn new_process_group() -> Result<ProcessGroup> { let kill_grace_period = Duration::from_secs_f32(0.3); ProcessGroup::with_kill_grace_period(kill_grace_period) } #[test] fn test_basic_kill() -> Result<()> { let mut pgrp = new_process_group()?; Command::new(&["sleep", "1000"]) .spawn()? .join(&mut pgrp); Ok(()) } #[test] fn test_wait_success() -> Result<()> { let mut pgrp = new_process_group()?; pgrp.add(Command::new(&["true"]).spawn()?); pgrp.add(Command::new(&["sleep"]).arg("0.2").spawn()?); pgrp.wait_for_success() } #[test] fn test_exit_fail() -> Result<()> { let mut pgrp = new_process_group()?; pgrp.add(Command::new(&["true"]).spawn()?); pgrp.add(Command::new(&["sleep"]).arg("1000").spawn()?); pgrp.add(Command::new(&["false"]).spawn()?); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("false")); assert!(err_msg.contains("exit_code=1")); Ok(()) } #[test] fn test_exit_fail_multiple() -> Result<()> { let mut cmd1 = Command::new(&["bash", "-c", "exit 2"]).spawn()?; let mut cmd2 = Command::new(&["false"]).spawn()?; let cmd3 = Command::new(&["sleep"]).arg("1000").spawn()?; cmd1.wait()?; cmd2.wait()?; let mut pgrp = new_process_group()?; pgrp.add(cmd1); pgrp.add(cmd2); pgrp.add(cmd3); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("bash")); assert!(err_msg.contains("exit_code=2")); assert!(err_msg.contains("false")); assert!(err_msg.contains("exit_code=1")); Ok(()) } #[test] fn test_signaled() -> Result<()> { let cmd = Command::new(&["sleep", "1000"]).spawn()?; cmd.kill(Signal::SIGTERM)?; let mut pgrp = new_process_group()?; pgrp.add(cmd); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("sleep")); assert!(err_msg.contains("caught fatal SIGTERM")); Ok(()) } #[test] fn test_unkillable() -> Result<()> { let start_time = Instant::now(); let mut pgrp = new_process_group()?; Command::new(&["sleep", "1"]).spawn()? .join_as_non_killable(&mut pgrp); drop(pgrp); println!("elapsed time {}ms", start_time.elapsed().as_millis()); assert!(start_time.elapsed().as_millis() >= 1000); Ok(()) } #[test] fn test_daemon() -> Result<()> { let start_time = Instant::now(); let mut pgrp = new_process_group()?; Command::new(&["sleep", "1000"]).spawn()? .join_as_daemon(&mut pgrp); pgrp.wait_for_success()?; println!("elapsed time {}ms", start_time.elapsed().as_millis()); assert!(start_time.elapsed().as_secs() < 1000); Ok(()) } #[test] fn test_get_mut() -> Result<()> { let mut cmd1 = Command::new(&["bash", "-c", "exit 2"]).spawn()?; let mut cmd2 = Command::new(&["false"]).spawn()?; cmd1.wait()?; cmd2.wait()?; let mut pgrp = new_process_group()?; let ps1 = pgrp.add(cmd1); let ps2 = pgrp.add(cmd2); pgrp.terminate()?; assert_eq!(pgrp.get_mut(ps1).wait()?.code().unwrap(), 2); assert_eq!(pgrp.get_mut(ps2).wait()?.code().unwrap(), 1); Ok(()) } }
use anyhow::{Result, Context}; use std::{ os::unix::io::AsRawFd, io::{ErrorKind, Read}, time::{Duration, Instant}, fs, iter, }; use nix::{ poll::{PollFd, PollFlags}, fcntl::OFlag, sys::signal, }; use crate::{ consts::*, util::{poll_nointr, Pipe}, }; use super::{Process, ProcessError, ProcessGroupError}; pub struct ProcessGroup { sigchld_pipe: fs::File, children: Vec<ProcessMembership>, kill_grace_period: Duration, sig_hook_id: Option<signal_hook::SigId>, } pub struct ProcessMembership { inner: Process, exited: bool, killable: bool, daemon: bool, } #[derive(Clone, Copy, Debug)] pub struct ProcessHandle(usize); impl From<Process> for ProcessMembership { fn from(inner: Process) -> Self { Self { inner, exited: false, killable: true, daemon: false } } } impl ProcessMembership { pub fn non_killable(self) -> Self { Self { killable: false, ..self } } pub fn daemon(self) -> Self { Self { daemon: true, ..self } } } impl ProcessGroup { pub fn new() -> Result<Self> { Self::with_kill_grace_period(Duration::from_secs(KILL_GRACE_PERIOD_SECS)) } pub fn with_kill_grace_period(kill_grace_period: Duration) -> Result<Self> { let pipe = Pipe::new(OFlag::O_CLOEXEC | OFlag::O_NONBLOCK)?; let sig_hook_id = Some(signal_hook::low_level::pipe::register( signal_hook::consts::SIGCHLD, pipe.write) .context("Failed to register signal")?);
} pub fn add(&mut self, proc: impl Into<ProcessMembership>) -> ProcessHandle { self.children.push(proc.into()); ProcessHandle(self.children.len() - 1) } pub fn get_mut(&mut self, id: ProcessHandle) -> &mut Process { &mut self.children[id.0].inner } fn drain_sigchld_pipe(&mut self) { let mut vec = Vec::new(); match self.sigchld_pipe.read_to_end(&mut vec) { Err(e) if e.kind() == ErrorKind::WouldBlock => {} result => { result.expect("SIGCHLD pipe has draining issues"); } } } pub fn try_wait_for_success(&mut self) -> Result<bool> { self.drain_sigchld_pipe(); let mut errors = Vec::new(); for child in &mut self.children { if child.inner.try_wait()?.is_some() { child.exited = true; if let Err(err) = child.inner.wait_for_success() { errors.push(err.downcast::<ProcessError>()?); } } } if !errors.is_empty() { bail!(ProcessGroupError { errors }); } Ok(self.children.iter().any(|c| !c.exited && !c.daemon)) } pub fn poll_fds(&self) -> Vec<PollFd> { self.children.iter() .filter_map(|c| c.inner.stderr_logger_fd()) .chain(iter::once(self.sigchld_pipe.as_raw_fd())) .map(|fd| PollFd::new(fd, PollFlags::POLLIN)) .collect() } pub fn wait_for_success(&mut self) -> Result<()> { while self.try_wait_for_success()? { let timeout = -1; poll_nointr(&mut self.poll_fds(), timeout) .context("Failed to poll()")?; } Ok(()) } pub fn terminate(&mut self) -> Result<()> { let mut killables = self.children.iter_mut() .filter(|c| c.killable && !c.exited) .collect::<Vec<_>>(); for child in &mut killables { if child.inner.try_wait()?.is_none() { child.inner.kill(signal::SIGTERM)?; } } let deadline = Instant::now() + self.kill_grace_period; for child in &mut killables { if child.inner.wait_timeout(deadline)?.is_none() { child.inner.kill(signal::SIGKILL)?; } } for child in &mut self.children { child.inner.wait()?; child.exited = true; } if let Some(sig_hook_id) = self.sig_hook_id.take() { ensure!(signal_hook::low_level::unregister(sig_hook_id), "signal_hook failed to unregister"); } Ok(()) } } impl Drop for ProcessGroup { fn drop(&mut self) { let _ = self.terminate() .map_err(|e| error!("Skipping children termination: {}", e)); } } pub trait ProcessExt { fn join(self, pgrp: &mut ProcessGroup) -> ProcessHandle; fn join_as_non_killable(self, pgrp: &mut ProcessGroup) -> ProcessHandle; fn join_as_daemon(self, pgrp: &mut ProcessGroup) -> ProcessHandle; } impl ProcessExt for Process { fn join(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(self) } fn join_as_non_killable(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(ProcessMembership::from(self).non_killable()) } fn join_as_daemon(self, pgrp: &mut ProcessGroup) -> ProcessHandle { pgrp.add(ProcessMembership::from(self).daemon()) } } #[cfg(test)] mod test { use super::*; use super::super::*; use nix::sys::signal::Signal; fn new_process_group() -> Result<ProcessGroup> { let kill_grace_period = Duration::from_secs_f32(0.3); ProcessGroup::with_kill_grace_period(kill_grace_period) } #[test] fn test_basic_kill() -> Result<()> { let mut pgrp = new_process_group()?; Command::new(&["sleep", "1000"]) .spawn()? .join(&mut pgrp); Ok(()) } #[test] fn test_wait_success() -> Result<()> { let mut pgrp = new_process_group()?; pgrp.add(Command::new(&["true"]).spawn()?); pgrp.add(Command::new(&["sleep"]).arg("0.2").spawn()?); pgrp.wait_for_success() } #[test] fn test_exit_fail() -> Result<()> { let mut pgrp = new_process_group()?; pgrp.add(Command::new(&["true"]).spawn()?); pgrp.add(Command::new(&["sleep"]).arg("1000").spawn()?); pgrp.add(Command::new(&["false"]).spawn()?); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("false")); assert!(err_msg.contains("exit_code=1")); Ok(()) } #[test] fn test_exit_fail_multiple() -> Result<()> { let mut cmd1 = Command::new(&["bash", "-c", "exit 2"]).spawn()?; let mut cmd2 = Command::new(&["false"]).spawn()?; let cmd3 = Command::new(&["sleep"]).arg("1000").spawn()?; cmd1.wait()?; cmd2.wait()?; let mut pgrp = new_process_group()?; pgrp.add(cmd1); pgrp.add(cmd2); pgrp.add(cmd3); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("bash")); assert!(err_msg.contains("exit_code=2")); assert!(err_msg.contains("false")); assert!(err_msg.contains("exit_code=1")); Ok(()) } #[test] fn test_signaled() -> Result<()> { let cmd = Command::new(&["sleep", "1000"]).spawn()?; cmd.kill(Signal::SIGTERM)?; let mut pgrp = new_process_group()?; pgrp.add(cmd); let err_msg = pgrp .wait_for_success() .unwrap_err() .to_string(); dbg!(&err_msg); assert!(err_msg.contains("sleep")); assert!(err_msg.contains("caught fatal SIGTERM")); Ok(()) } #[test] fn test_unkillable() -> Result<()> { let start_time = Instant::now(); let mut pgrp = new_process_group()?; Command::new(&["sleep", "1"]).spawn()? .join_as_non_killable(&mut pgrp); drop(pgrp); println!("elapsed time {}ms", start_time.elapsed().as_millis()); assert!(start_time.elapsed().as_millis() >= 1000); Ok(()) } #[test] fn test_daemon() -> Result<()> { let start_time = Instant::now(); let mut pgrp = new_process_group()?; Command::new(&["sleep", "1000"]).spawn()? .join_as_daemon(&mut pgrp); pgrp.wait_for_success()?; println!("elapsed time {}ms", start_time.elapsed().as_millis()); assert!(start_time.elapsed().as_secs() < 1000); Ok(()) } #[test] fn test_get_mut() -> Result<()> { let mut cmd1 = Command::new(&["bash", "-c", "exit 2"]).spawn()?; let mut cmd2 = Command::new(&["false"]).spawn()?; cmd1.wait()?; cmd2.wait()?; let mut pgrp = new_process_group()?; let ps1 = pgrp.add(cmd1); let ps2 = pgrp.add(cmd2); pgrp.terminate()?; assert_eq!(pgrp.get_mut(ps1).wait()?.code().unwrap(), 2); assert_eq!(pgrp.get_mut(ps2).wait()?.code().unwrap(), 1); Ok(()) } }
Ok(Self { sigchld_pipe: pipe.read, children: Vec::new(), kill_grace_period, sig_hook_id, })
call_expression
[ { "content": "/// Kill an entire process group. It is not atomic.\n\n/// Tasks may appear while we are traversing the tree.\n\n/// This is mostly used to SIGSTOP/SIGCONT the entire application.\n\n/// TODO We could use the cgroup freezer if we have access to it.\n\npub fn kill_process_tree(root_pid: Pid, signal...
Rust
src/aggregation/segment_agg_result.rs
StyMaar/tantivy
458ed29a31d4a8929193ba4f41b83cd69eaac5f9
use std::fmt::Debug; use super::agg_req::MetricAggregation; use super::agg_req_with_accessor::{ AggregationsWithAccessor, BucketAggregationWithAccessor, MetricAggregationWithAccessor, }; use super::bucket::SegmentRangeCollector; use super::metric::{ AverageAggregation, SegmentAverageCollector, SegmentStatsCollector, StatsAggregation, }; use super::{Key, VecWithNames}; use crate::aggregation::agg_req::BucketAggregationType; use crate::DocId; pub(crate) const DOC_BLOCK_SIZE: usize = 256; pub(crate) type DocBlock = [DocId; DOC_BLOCK_SIZE]; #[derive(Clone, PartialEq)] pub(crate) struct SegmentAggregationResultsCollector { pub(crate) metrics: VecWithNames<SegmentMetricResultCollector>, pub(crate) buckets: VecWithNames<SegmentBucketResultCollector>, staged_docs: DocBlock, num_staged_docs: usize, } impl Debug for SegmentAggregationResultsCollector { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SegmentAggregationResultsCollector") .field("metrics", &self.metrics) .field("buckets", &self.buckets) .field("staged_docs", &&self.staged_docs[..self.num_staged_docs]) .field("num_staged_docs", &self.num_staged_docs) .finish() } } impl SegmentAggregationResultsCollector { pub(crate) fn from_req_and_validate(req: &AggregationsWithAccessor) -> crate::Result<Self> { let buckets = req .buckets .entries() .map(|(key, req)| { Ok(( key.to_string(), SegmentBucketResultCollector::from_req_and_validate(req)?, )) }) .collect::<crate::Result<_>>()?; let metrics = req .metrics .entries() .map(|(key, req)| { Ok(( key.to_string(), SegmentMetricResultCollector::from_req_and_validate(req)?, )) }) .collect::<crate::Result<_>>()?; Ok(SegmentAggregationResultsCollector { metrics: VecWithNames::from_entries(metrics), buckets: VecWithNames::from_entries(buckets), staged_docs: [0; DOC_BLOCK_SIZE], num_staged_docs: 0, }) } #[inline] pub(crate) fn collect( &mut self, doc: crate::DocId, agg_with_accessor: &AggregationsWithAccessor, ) { self.staged_docs[self.num_staged_docs] = doc; self.num_staged_docs += 1; if self.num_staged_docs == self.staged_docs.len() { self.flush_staged_docs(agg_with_accessor, false); } } #[inline(never)] pub(crate) fn flush_staged_docs( &mut self, agg_with_accessor: &AggregationsWithAccessor, force_flush: bool, ) { for (agg_with_accessor, collector) in agg_with_accessor .metrics .values() .zip(self.metrics.values_mut()) { collector.collect_block(&self.staged_docs[..self.num_staged_docs], agg_with_accessor); } for (agg_with_accessor, collector) in agg_with_accessor .buckets .values() .zip(self.buckets.values_mut()) { collector.collect_block( &self.staged_docs[..self.num_staged_docs], agg_with_accessor, force_flush, ); } self.num_staged_docs = 0; } } #[derive(Clone, Debug, PartialEq)] pub(crate) enum SegmentMetricResultCollector { Average(SegmentAverageCollector), Stats(SegmentStatsCollector), } impl SegmentMetricResultCollector { pub fn from_req_and_validate(req: &MetricAggregationWithAccessor) -> crate::Result<Self> { match &req.metric { MetricAggregation::Average(AverageAggregation { field: _ }) => { Ok(SegmentMetricResultCollector::Average( SegmentAverageCollector::from_req(req.field_type), )) } MetricAggregation::Stats(StatsAggregation { field: _ }) => { Ok(SegmentMetricResultCollector::Stats( SegmentStatsCollector::from_req(req.field_type), )) } } } pub(crate) fn collect_block(&mut self, doc: &[DocId], metric: &MetricAggregationWithAccessor) { match self { SegmentMetricResultCollector::Average(avg_collector) => { avg_collector.collect_block(doc, &metric.accessor); } SegmentMetricResultCollector::Stats(stats_collector) => { stats_collector.collect_block(doc, &metric.accessor); } } } } #[derive(Clone, Debug, PartialEq)] pub(crate) enum SegmentBucketResultCollector { Range(SegmentRangeCollector), } impl SegmentBucketResultCollector { pub fn from_req_and_validate(req: &BucketAggregationWithAccessor) -> crate::Result<Self> { match &req.bucket_agg { BucketAggregationType::Range(range_req) => { Ok(Self::Range(SegmentRangeCollector::from_req_and_validate( range_req, &req.sub_aggregation, req.field_type, )?)) } } } #[inline] pub(crate) fn collect_block( &mut self, doc: &[DocId], bucket_with_accessor: &BucketAggregationWithAccessor, force_flush: bool, ) { match self { SegmentBucketResultCollector::Range(range) => { range.collect_block(doc, bucket_with_accessor, force_flush); } } } } #[derive(Clone, PartialEq)] pub(crate) struct SegmentRangeBucketEntry { pub key: Key, pub doc_count: u64, pub sub_aggregation: Option<SegmentAggregationResultsCollector>, pub from: Option<f64>, pub to: Option<f64>, } impl Debug for SegmentRangeBucketEntry { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SegmentRangeBucketEntry") .field("key", &self.key) .field("doc_count", &self.doc_count) .field("from", &self.from) .field("to", &self.to) .finish() } }
use std::fmt::Debug; use super::agg_req::MetricAggregation; use super::agg_req_with_accessor::{ AggregationsWithAccessor, BucketAggregationWithAccessor, MetricAggregationWithAccessor, }; use super::bucket::SegmentRangeCollector; use super::metric::{ AverageAggregation, SegmentAverageCollector, SegmentStatsCollector, StatsAggregation, }; use super::{Key, VecWithNames}; use crate::aggregation::agg_req::BucketAggregationType; use crate::DocId; pub(crate) const DOC_BLOCK_SIZE: usize = 256; pub(crate) type DocBlock = [DocId; DOC_BLOCK_SIZE]; #[derive(Clone, PartialEq)] pub(crate) struct SegmentAggregationResultsCollector { pub(crate) metrics: VecWithNames<SegmentMetricResultCollector>, pub(crate) buckets: VecWithNames<SegmentBucketResultCollector>, staged_docs: DocBlock, num_staged_docs: usize, } impl Debug for SegmentAggregationResultsCollector { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SegmentAggregationResultsCollector") .field("metrics", &self.metrics) .field("buckets", &self.buckets) .field("staged_docs", &&self.staged_docs[..self.num_staged_docs]) .field("num_staged_docs", &self.num_staged_docs) .finish() } } impl SegmentAggregationResultsCollector { pub(crate) fn from_req_and_validate(req: &AggregationsWithAccessor) -> crate::Result<Self> { let buckets = req .buckets .entries() .map(|(key, req)| { Ok(( key.to_string(), SegmentBucketResultCollector::from_req_and_validate(req)?, )) }) .collect::<crate::Result<_>>()?; let metrics = req .metrics .entries() .map(|(key, req)| { Ok(( key.to_string(), SegmentMetricResultCollector::from_req_and_validate(req)?, )) }) .collect::<crate::Result<_>>()?; Ok(SegmentAggregationResultsCollector { metrics: VecWithNames::from_entries(metrics), buckets: VecWithNames::from_entries(buckets), staged_docs: [0; DOC_BLOCK_SIZE], num_staged_docs: 0, }) } #[inline] pub(crate) fn collect( &mut self, doc: crate::DocId, agg_with_accessor: &AggregationsWithAccessor, ) { self.staged_docs[self.num_staged_docs] = doc; self.num_staged_docs += 1; if self.num_staged_docs == self.staged_docs.len() { self.flush_staged_docs(agg_with_accessor, false); } } #[inline(never)] pub(crate) fn flush_staged_docs( &mut self, agg_with_accessor: &AggregationsWithAccessor, force_flush: bool, ) { for (agg_with_accessor, collector) in agg_with_accessor .metrics .values() .zip(self.metrics.values_mut()) { collector.collect_block(&self.staged_docs[..self.num_staged_docs], agg_with_accessor); } for (agg_with_accessor, collector) in agg_with_accessor .buckets .values() .zip(self.buckets.values_mut()) { collector.collect_block( &self.staged_docs[..self.num_staged_docs], agg_with_accessor, force_flush, ); } self.num_staged_docs = 0; } } #[derive(Clone, Debug, PartialEq)] pub(crate) enum SegmentMetricResultCollector { Average(SegmentAverageCollector), Stats(SegmentStatsCollector), } impl SegmentMetricResultCollector { pub fn from_req_and_validate(req: &MetricAggregationWithAccessor) -> crate::Result<Self> { match &req.metric { MetricAggregation::Average(AverageAggregation { field: _ }) => { Ok(SegmentMetricResultCollector::Average( SegmentAverageCollector::from_req(req.field_type), )) } MetricAggregation::Stats(StatsAggregation { field: _ }) => { Ok(SegmentMetricResultCollector::Stats( SegmentStatsCollector::from_req(req.field_type), )) } } } pub(crate) fn collect_block(&mut self, doc: &[DocId], metric: &MetricAggregationWithAccessor) { match self { SegmentMetricResultCollector::Average(avg_collector) => { avg_collector.collect_block(doc, &metric.accessor); } SegmentMetricResultCollector::Stats(stats_collector) => { stats_collector.collect_block(doc, &metric.accessor); } } } } #[derive(Clone, Debug, PartialEq)] pub
ketResultCollector::Range(range) => { range.collect_block(doc, bucket_with_accessor, force_flush); } } } } #[derive(Clone, PartialEq)] pub(crate) struct SegmentRangeBucketEntry { pub key: Key, pub doc_count: u64, pub sub_aggregation: Option<SegmentAggregationResultsCollector>, pub from: Option<f64>, pub to: Option<f64>, } impl Debug for SegmentRangeBucketEntry { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("SegmentRangeBucketEntry") .field("key", &self.key) .field("doc_count", &self.doc_count) .field("from", &self.from) .field("to", &self.to) .finish() } }
(crate) enum SegmentBucketResultCollector { Range(SegmentRangeCollector), } impl SegmentBucketResultCollector { pub fn from_req_and_validate(req: &BucketAggregationWithAccessor) -> crate::Result<Self> { match &req.bucket_agg { BucketAggregationType::Range(range_req) => { Ok(Self::Range(SegmentRangeCollector::from_req_and_validate( range_req, &req.sub_aggregation, req.field_type, )?)) } } } #[inline] pub(crate) fn collect_block( &mut self, doc: &[DocId], bucket_with_accessor: &BucketAggregationWithAccessor, force_flush: bool, ) { match self { SegmentBuc
random
[ { "content": "#[inline]\n\nfn is_within<TDocSetExclude: DocSet>(docset: &mut TDocSetExclude, doc: DocId) -> bool {\n\n docset.doc() <= doc && docset.seek(doc) == doc\n\n}\n\n\n\n/// Filters a given `DocSet` by removing the docs from a given `DocSet`.\n\n///\n\n/// The excluding docset has no impact on scorin...
Rust
src/devices/src/virtio/block/device.rs
lyuyuan/vmm-reference
6275fc099022c7fb6d62022a87c5686b2fbe0ba2
use std::borrow::{Borrow, BorrowMut}; use std::fs::OpenOptions; use std::ops::DerefMut; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use vm_device::bus::MmioAddress; use vm_device::device_manager::MmioManager; use vm_device::{DeviceMmio, MutDeviceMmio}; use vm_memory::GuestAddressSpace; use vm_virtio::block::stdio_executor::StdIoBackend; use vm_virtio::device::{VirtioConfig, VirtioDeviceActions, VirtioDeviceType, VirtioMmioDevice}; use vm_virtio::Queue; use crate::virtio::block::{BLOCK_DEVICE_ID, VIRTIO_BLK_F_RO}; use crate::virtio::{CommonConfig, Env, SingleFdSignalQueue, QUEUE_MAX_SIZE}; use super::inorder_handler::InOrderQueueHandler; use super::queue_handler::QueueHandler; use super::{build_config_space, BlockArgs, Error, Result}; pub struct Block<M: GuestAddressSpace> { cfg: CommonConfig<M>, file_path: PathBuf, read_only: bool, _root_device: bool, } impl<M> Block<M> where M: GuestAddressSpace + Clone + Send + 'static, { fn create_block<B>(env: &mut Env<M, B>, args: &BlockArgs) -> Result<Self> { let device_features = args.device_features(); let queues = vec![Queue::new(env.mem.clone(), QUEUE_MAX_SIZE)]; let config_space = build_config_space(&args.file_path)?; let virtio_cfg = VirtioConfig::new(device_features, queues, config_space); let common_cfg = CommonConfig::new(virtio_cfg, env).map_err(Error::Virtio)?; Ok(Block { cfg: common_cfg, file_path: args.file_path.clone(), read_only: args.read_only, _root_device: args.root_device, }) } pub fn new<B>(env: &mut Env<M, B>, args: &BlockArgs) -> Result<Arc<Mutex<Self>>> where B: DerefMut, B::Target: MmioManager<D = Arc<dyn DeviceMmio + Send + Sync>>, { let block = Arc::new(Mutex::new(Self::create_block(env, args)?)); env.register_mmio_device(block.clone()) .map_err(Error::Virtio)?; env.insert_cmdline_str(args.cmdline_config_substring()) .map_err(Error::Virtio)?; Ok(block) } } impl<M: GuestAddressSpace + Clone + Send + 'static> Borrow<VirtioConfig<M>> for Block<M> { fn borrow(&self) -> &VirtioConfig<M> { &self.cfg.virtio } } impl<M: GuestAddressSpace + Clone + Send + 'static> BorrowMut<VirtioConfig<M>> for Block<M> { fn borrow_mut(&mut self) -> &mut VirtioConfig<M> { &mut self.cfg.virtio } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioDeviceType for Block<M> { fn device_type(&self) -> u32 { BLOCK_DEVICE_ID } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioDeviceActions for Block<M> { type E = Error; fn activate(&mut self) -> Result<()> { let file = OpenOptions::new() .read(true) .write(!self.read_only) .open(&self.file_path) .map_err(Error::OpenFile)?; let mut features = self.cfg.virtio.driver_features; if self.read_only { features |= 1 << VIRTIO_BLK_F_RO; } let disk = StdIoBackend::new(file, features).map_err(Error::Backend)?; let driver_notify = SingleFdSignalQueue { irqfd: self.cfg.irqfd.clone(), interrupt_status: self.cfg.virtio.interrupt_status.clone(), }; let inner = InOrderQueueHandler { driver_notify, queue: self.cfg.virtio.queues[0].clone(), disk, }; let mut ioevents = self.cfg.prepare_activate().map_err(Error::Virtio)?; let handler = Arc::new(Mutex::new(QueueHandler { inner, ioeventfd: ioevents.remove(0), })); self.cfg.finalize_activate(handler).map_err(Error::Virtio) } fn reset(&mut self) -> Result<()> { Ok(()) } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioMmioDevice<M> for Block<M> {} impl<M: GuestAddressSpace + Clone + Send + 'static> MutDeviceMmio for Block<M> { fn mmio_read(&mut self, _base: MmioAddress, offset: u64, data: &mut [u8]) { self.read(offset, data); } fn mmio_write(&mut self, _base: MmioAddress, offset: u64, data: &[u8]) { self.write(offset, data); } } #[cfg(test)] mod tests { use vmm_sys_util::tempfile::TempFile; use crate::virtio::tests::EnvMock; use super::super::VIRTIO_BLK_F_FLUSH; use super::*; #[cfg_attr(target_arch = "aarch64", ignore)] #[test] fn test_device() { let tmp = TempFile::new().unwrap(); let mut mock = EnvMock::new(); let mut env = mock.env(); let args = BlockArgs { file_path: tmp.as_path().to_path_buf(), read_only: true, root_device: true, advertise_flush: true, }; let block_mutex = Block::new(&mut env, &args).unwrap(); let block = block_mutex.lock().unwrap(); assert_eq!(block.device_type(), BLOCK_DEVICE_ID); assert_eq!( mock.kernel_cmdline.as_str(), format!( "virtio_mmio.device=4K@0x{:x}:{} root=/dev/vda ro", mock.mmio_cfg.range.base().0, mock.mmio_cfg.gsi ) ); assert_ne!(block.cfg.virtio.device_features & (1 << VIRTIO_BLK_F_RO), 0); assert_ne!( block.cfg.virtio.device_features & (1 << VIRTIO_BLK_F_FLUSH), 0 ); } }
use std::borrow::{Borrow, BorrowMut}; use std::fs::OpenOptions; use std::ops::DerefMut; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use vm_device::bus::MmioAddress; use vm_device::device_manager::MmioManager; use vm_device::{DeviceMmio, MutDeviceMmio}; use vm_memory::GuestAddressSpace; use vm_virtio::block::stdio_executor::StdIoBackend; use vm_virtio::device::{VirtioConfig, VirtioDeviceActions, VirtioDeviceType, VirtioMmioDevice}; use vm_virtio::Queue; use crate::virtio::block::{BLOCK_DEVICE_ID, VIRTIO_BLK_F_RO}; use crate::virtio::{CommonConfig, Env, SingleFdSignalQueue, QUEUE_MAX_SIZE}; use super::inorder_handler::InOrderQueueHandler; use super::queue_handler::QueueHandler; use super::{build_config_space, BlockArgs, Error, Result}; pub struct Block<M: GuestAddressSpace> { cfg: CommonConfig<M>, file_path: PathBuf, read_only: bool, _root_device: bool, } impl<M> Block<M> where M: GuestAddressSpace + Clone + Send + 'static, { fn create_block<B>(env: &mut Env<M, B>, args: &BlockArgs) -> Result<Self> { let device_features = args.device_features(); let queues = vec![Queue::new(env.mem.clone(), QUEUE_MAX_SIZE)]; let config_space = build_config_space(&args.file_path)?; let virtio_cfg = VirtioConfig::new(device_features, queues, config_space); let common_cfg = CommonConfig::new(virtio_cfg, env).map_err(Error::Virtio)?; Ok(Block { cfg: common_cfg, file_path: args.file_path.clone(), read_only: args.read_only, _root_device: args.root_device, }) } pub fn new<B>(env: &mut Env<M, B>, args: &BlockArgs) -> Result<Arc<Mutex<Self>>> where B: DerefMut, B::Target: MmioManager<D = Arc<dyn DeviceMmio + Send + Sync>>, { let block = Arc::new(Mutex::new(Self::create_block(env, args)?)); env.register_mmio_device(block.clone()) .map_err(Error::Virtio)?; env.insert_cmdline_str(args.cmdline_config_substring()) .map_err(Error::Virtio)?; Ok(block) } } impl<M: GuestAddressSpace + Clone + Send + 'static> Borrow<VirtioConfig<M>> for Block<M> { fn borrow(&self) -> &VirtioConfig<M> { &self.cfg.virtio } } impl<M: GuestAddressSpace + Clone + Send + 'static> BorrowMut<VirtioConfig<M>> for Block<M> { fn borrow_mut(&mut self) -> &mut VirtioConfig<M> { &mut self.cfg.virtio } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioDeviceType for Block<M> { fn device_type(&self) -> u32 { BLOCK_DEVICE_ID } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioDeviceActions for Block<M> { type E = Error; fn activate(&mut self) -> Result<()> { let file = OpenOptions::new() .read(true) .write(!self.read_only) .open(&self.file_path) .map_err(Error::OpenFile)?; let mut features = self.cfg.virtio.driver_features; if self.read_only { features |= 1 << VIRTIO_BLK_F_RO; } let disk = StdIoBackend::new(file, features).map_err(Error::Backend)?; let driver_notify = SingleFdSignalQueue { irqfd: self.cfg.irqfd.clone(), interrupt_status: self.cfg.virtio.interrupt_status.clone(), }; let inner = InOrderQueueHandler { driver_notify, queue: self.cfg.virtio.queues[0].clone(), disk, }; let mut ioevents = self.cfg.prepare_activate().map_err(Error::Virtio)?; let handler = Arc::new(Mutex::new(QueueHandler { inner, ioeventfd: ioevents.remove(0), })); self.cfg.finalize_activate(handler).map_err(Error::Virtio) } fn reset(&mut self) -> Result<()> { Ok(()) } } impl<M: GuestAddressSpace + Clone + Send + 'static> VirtioMmioDevice<M> for Block<M> {} impl<M: GuestAddressSpace + Clone + Send + 'static> MutDeviceMmio for Block<M> { fn mmio_read(&mut self, _base: MmioAddress, offset: u64, data: &mut [u8]) { self.read(offset, data); } fn mmio_write(&mut self, _base: MmioAddress, offset: u64, data: &[u8]) { self.write(offset, data); } } #[cfg(test)] mod tests { use vmm_sys_util::tempfile::TempFile; use crate::virtio::tests::EnvMock; use super::super::VIRTIO_BLK_F_FLUSH; use super::*; #[cfg_attr(target_arch = "aarch64", ignore)] #[test]
}
fn test_device() { let tmp = TempFile::new().unwrap(); let mut mock = EnvMock::new(); let mut env = mock.env(); let args = BlockArgs { file_path: tmp.as_path().to_path_buf(), read_only: true, root_device: true, advertise_flush: true, }; let block_mutex = Block::new(&mut env, &args).unwrap(); let block = block_mutex.lock().unwrap(); assert_eq!(block.device_type(), BLOCK_DEVICE_ID); assert_eq!( mock.kernel_cmdline.as_str(), format!( "virtio_mmio.device=4K@0x{:x}:{} root=/dev/vda ro", mock.mmio_cfg.range.base().0, mock.mmio_cfg.gsi ) ); assert_ne!(block.cfg.virtio.device_features & (1 << VIRTIO_BLK_F_RO), 0); assert_ne!( block.cfg.virtio.device_features & (1 << VIRTIO_BLK_F_FLUSH), 0 ); }
function_block-full_function
[ { "content": "pub fn get_type(entry: u64) -> u8 {\n\n ((entry & 0x0000_0F00_0000_0000) >> 40) as u8\n\n}\n\n\n", "file_path": "src/vm-vcpu/src/vcpu/gdt.rs", "rank": 0, "score": 194121.65583323193 }, { "content": "type Result<T> = std::result::Result<T, Error>;\n\npub type Subscriber = Arc...
Rust
src/fonts/manifest/src/v2.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use { crate::serde_ext::*, anyhow::{ensure, Error}, char_set::CharSet, fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width, WEIGHT_NORMAL}, fuchsia_url::pkg_url::PkgUrl, itertools::Itertools, offset_string::OffsetString, serde::{ de::{Deserializer, Error as DeError}, ser::Serializer, }, serde::{Deserialize, Serialize}, std::{convert::TryFrom, iter, ops::Deref, path::PathBuf}, unicase::UniCase, }; #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct FontsManifest { pub families: Vec<Family>, pub fallback_chain: Vec<TypefaceId>, #[serde(default, skip_serializing_if = "Settings::is_empty")] pub settings: Settings, } impl FontsManifest { pub fn empty() -> Self { Self::default() } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Family { pub name: String, #[serde(skip_serializing_if = "Vec::is_empty", default)] pub aliases: Vec<FontFamilyAliasSet>, #[serde(with = "OptGenericFontFamily", default)] pub generic_family: Option<GenericFontFamily>, pub assets: Vec<Asset>, } #[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)] pub struct FontFamilyAliasSet { #[serde( deserialize_with = "FontFamilyAliasSet::deserialize_names", serialize_with = "FontFamilyAliasSet::serialize_names" )] names: Vec<UniCase<String>>, #[serde(flatten)] style: StyleOptions, #[serde(default, skip_serializing_if = "Vec::is_empty")] languages: Vec<String>, } impl FontFamilyAliasSet { pub fn new( names: impl IntoIterator<Item = impl AsRef<str>>, style: impl Into<StyleOptions>, languages: impl IntoIterator<Item = impl AsRef<str>>, ) -> Result<Self, Error> { let set = FontFamilyAliasSet { names: Self::preprocess_names(names), style: style.into(), languages: languages.into_iter().map(|s| s.as_ref().to_string()).collect_vec(), }; ensure!(!set.names.is_empty(), "Must contain at least one name"); Ok(set) } pub fn without_overrides( names: impl IntoIterator<Item = impl AsRef<str>>, ) -> Result<Self, Error> { Self::new(names, StyleOptions::default(), iter::empty::<String>()) } pub fn names(&self) -> impl Iterator<Item = &String> { (&self.names).iter().map(|uni| uni.deref()) } pub fn style_overrides(&self) -> &StyleOptions { &self.style } pub fn language_overrides(&self) -> impl Iterator<Item = &String> { (&self.languages).iter() } pub fn has_overrides(&self) -> bool { self.has_style_overrides() || self.has_language_overrides() } pub fn has_style_overrides(&self) -> bool { self.style != StyleOptions::default() } pub fn has_language_overrides(&self) -> bool { !self.languages.is_empty() } fn deserialize_names<'de, D>(deserializer: D) -> Result<Vec<UniCase<String>>, D::Error> where D: Deserializer<'de>, { let names: Vec<String> = Vec::deserialize(deserializer)?; Ok(Self::preprocess_names(names)) } fn serialize_names<S>(names: &Vec<UniCase<String>>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { names.iter().map(|u| u.deref().to_string()).collect_vec().serialize(serializer) } fn preprocess_names(names: impl IntoIterator<Item = impl AsRef<str>>) -> Vec<UniCase<String>> { names.into_iter().map(|name| UniCase::new(name.as_ref().to_string())).sorted().collect() } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Asset { pub file_name: String, pub location: AssetLocation, pub typefaces: Vec<Typeface>, } impl Asset { pub fn local_path(&self) -> Option<PathBuf> { match &self.location { AssetLocation::LocalFile(locator) => { Some(locator.directory.join(self.file_name.clone())) } _ => None, } } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum AssetLocation { #[serde(rename = "local")] LocalFile(LocalFileLocator), #[serde(rename = "package")] Package(PackageLocator), } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct LocalFileLocator { pub directory: PathBuf, } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct PackageLocator { pub url: PkgUrl, } #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Typeface { #[serde(default = "Typeface::default_index")] pub index: u32, #[serde(default = "Typeface::default_languages", skip_serializing_if = "Vec::is_empty")] pub languages: Vec<String>, #[serde(flatten)] pub style: Style, #[serde(with = "code_points_serde")] pub code_points: CharSet, #[serde(default)] pub postscript_name: Option<String>, #[serde(default)] pub full_name: Option<String>, } impl Typeface { fn default_index() -> u32 { 0 } fn default_languages() -> Vec<String> { vec![] } } #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Settings { #[serde(default)] pub cache_size_bytes: Option<u64>, } impl Settings { fn is_empty(&self) -> bool { self == &Settings::default() } } mod code_points_serde { use super::*; pub fn deserialize<'d, D>(deserializer: D) -> Result<CharSet, D::Error> where D: Deserializer<'d>, { let offset_string = OffsetString::deserialize(deserializer)?; CharSet::try_from(offset_string).map_err(|e| D::Error::custom(format!("{:?}", e))) } pub fn serialize<S>(code_points: &CharSet, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let offset_string: OffsetString = code_points.into(); offset_string.serialize(serializer) } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct TypefaceId { pub file_name: String, #[serde(default = "Typeface::default_index")] pub index: u32, } impl TypefaceId { pub fn new(file_name: impl Into<String>, index: u32) -> Self { TypefaceId { file_name: file_name.into(), index } } } #[allow(missing_docs)] #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Style { #[serde(default = "Style::default_slant", with = "SlantDef")] pub slant: Slant, #[serde(default = "Style::default_weight")] pub weight: u16, #[serde(default = "Style::default_width", with = "WidthDef")] pub width: Width, } impl Default for Style { fn default() -> Self { Self { slant: Style::default_slant(), weight: Style::default_weight(), width: Style::default_width(), } } } impl Style { fn default_slant() -> Slant { Slant::Upright } fn default_weight() -> u16 { WEIGHT_NORMAL } fn default_width() -> Width { Width::Normal } }
use { crate::serde_ext::*, anyhow::{ensure, Error}, char_set::CharSet, fidl_fuchsia_fonts::{GenericFontFamily, Slant, Width, WEIGHT_NORMAL}, fuchsia_url::pkg_url::PkgUrl, itertools::Itertools, offset_string::OffsetString, serde::{ de::{Deserializer, Error as DeError}, ser::Serializer, }, serde::{Deserialize, Serialize}, std::{convert::TryFrom, iter, ops::Deref, path::PathBuf}, unicase::UniCase, }; #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct FontsManifest { pub families: Vec<Family>, pub fallback_chain: Vec<TypefaceId>, #[serde(default, skip_serializing_if = "Settings::is_empty")] pub settings: Settings, } impl FontsManifest { pub fn empty() -> Self { Self::default() } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Family { pub name: String, #[serde(skip_serializing_if = "Vec::is_empty", default)] pub aliases: Vec<FontFamilyAliasSet>, #[serde(with = "OptGenericFontFamily", default)] pub generic_family: Option<GenericFontFamily>, pub assets: Vec<Asset>, } #[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)] pub struct FontFamilyAliasSet { #[serde( deserialize_with = "FontFamilyAliasSet::deserialize_names", serialize_with = "FontFamilyAliasSet::serialize_names" )] names: Vec<UniCase<String>>, #[serde(flatten)] style: StyleOptions, #[serde(default, skip_serializing_if = "Vec::is_empty")] languages: Vec<String>, } impl FontFamilyAliasSet { pub fn new( names: impl IntoIterator<Item = impl AsRef<str>>, style: impl Into<StyleOptions>, languages: impl IntoIterator<Item = impl AsRef<str>>, ) -> Result<Self, Error> { let set = FontFamilyAliasSet { names: Self::preprocess_names(names), style: style.into(), languages: languages.into_iter().map(|s| s.as_ref().to_string()).collect_vec(), }; ensure!(!set.names.is_empty(), "Must contain at least one name"); Ok(set) } pub fn without_overrides( names: impl IntoIterator<Item = impl AsRef<str>>, ) -> Result<Self, Error> { Self::new(names, StyleOptions::default(), iter::empty::<String>()) } pub fn names(&self) -> impl Iterator<Item = &String> { (&self.names).iter().map(|uni| uni.deref()) } pub fn style_overrides(&self) -> &StyleOptions { &self.style } pub fn language_overrides(&self) -> impl Iterator<Item = &String> { (&self.languages).iter() } pub fn has_overrides(&self) -> bool { self.has_style_overrides() || self.has_language_overrides() } pub fn has_style_overrides(&self) -> bool { self.style != StyleOptions::default() } pub fn has_language_overrides(&self) -> bool { !self.languages.is_empty() } fn deserialize_names<'de, D>(deserializer: D) -> Result<Vec<UniCase<String>>, D::Error> where D: Deserializer<'de>, { let names: Vec<String> = Vec::deserialize(deserializer)?; Ok(Self::preprocess_names(names)) } fn serialize_names<S>(names: &Vec<UniCase<String>>, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { names.iter().map(|u| u.deref().to_string()).collect_vec().serialize(serializer) } fn preprocess_names(names: impl IntoIterator<Item = impl AsRef<str>>) -> Vec<UniCase<String>> { names.into_iter().map(|name| UniCase::new(name.as_ref().to_string())).sorted().collect() } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Asset { pub file_name: String, pub location: AssetLocation, pub typefaces: Vec<Typeface>, } impl Asset { pub fn local_path(&self) -> Option<PathBuf> { match &self.location { AssetLocation::LocalFile(locator) => { Some(locator.directory.join(self.file_name.clone())) } _ => None, } } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum AssetLocation { #[serde(rename = "local")] LocalFile(LocalFileLocator), #[serde(rename = "package")] Package(PackageLocator), } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct LocalFileLocator { pub directory: PathBuf, } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct PackageLocator { pub url: PkgUrl, } #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Typeface { #[serde(default = "Typeface::default_index")] pub index: u32, #[serde(default = "Typeface::default_languages", skip_serializing_if = "Vec::is_empty")] pub languages: Vec<String>, #[serde(flatten)] pub style: Style, #[serde(with = "code_points_serde")] pub code_points: CharSet, #[serde(default)] pub postscript_name: Option<String>, #[serde(default)] pub full_name: Option<String>, } impl Typeface { fn default_index() -> u32 { 0 } fn default_languages() -> Vec<String> { vec![] } } #[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Settings { #[serde(default)] pub cache_size_bytes: Option<u64>, } impl Settings { fn is_empty(&self) -> bool { self == &Settings::default() } } mod code_points_serde { use super::*; pub fn deserialize<'d, D>(deserializer: D) -> Result<CharSet, D::Error> where D: Deserializer<'d>, { let offset_string = OffsetString::deserialize(deserializer)?; CharSet::try_from(offset_string).map_err(|e| D::Error::custom(format!("{:?}", e))) } pub fn serialize<S>(code_points: &CharSet, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let offset_string: OffsetString = code_points.into(); offset_string.serialize(serializer) } } #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct TypefaceId { pub file_name: String, #[serde(default = "Typeface::default_index")] pub index: u32, } impl TypefaceId { pub fn new(file_name: impl Into<String>, index: u32) -> Self { TypefaceId { file_name: file_name.into(), index } } } #[allow(missing_docs)] #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)] pub struct Style { #[serde(default = "Style::default_slant", with = "SlantDef")] pub slant: Slant, #[serde(default = "Style::default_weight")] pub weight: u16, #[serde(default = "Style::default_width", with = "WidthDef")] pub width: Width, } impl Default for Style { fn default() -> Self { Self { sla
} impl Style { fn default_slant() -> Slant { Slant::Upright } fn default_weight() -> u16 { WEIGHT_NORMAL } fn default_width() -> Width { Width::Normal } }
nt: Style::default_slant(), weight: Style::default_weight(), width: Style::default_width(), } }
function_block-function_prefixed
[]