repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
teenjuna/prae | https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/validate.rs | prae/tests/validate.rs | use assert_matches::assert_matches;
use prae::{MapOriginalError, Wrapper};
#[derive(Debug, PartialEq, Eq)]
pub struct UsernameError;
impl std::fmt::Display for UsernameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "username is empty")
}
}
prae::define! {
#[derive(Debug)]
pub Username: String;
validate(UsernameError) |u| {
if u.is_empty() {
Err(UsernameError{})
} else {
Ok(())
}
};
}
#[test]
fn construction_error_formats_correctly() {
let err = Username::new("").unwrap_err();
assert_eq!(
err.to_string(),
"failed to construct type Username from value \"\": username is empty"
);
}
#[test]
fn mutation_error_formats_correctly() {
let mut un = Username::new("user").unwrap();
let err = un.mutate(|u| *u = "".to_owned()).unwrap_err();
assert_eq!(
err.to_string(),
"failed to mutate type Username from value \"user\" to value \"\": username is empty"
);
}
#[test]
fn construction_error_can_be_transormed_into_inner() {
let _err = || -> Result<(), UsernameError> {
Username::new("").map_original()?;
Ok(())
}();
}
#[test]
fn mutation_error_can_be_transormed_into_inner() {
let _err = || -> Result<(), UsernameError> {
let mut un = Username::new("user").unwrap();
un.mutate(|u| *u = "".to_owned()).map_original()?;
Ok(())
}();
}
#[test]
fn construction_fails_for_invalid_data() {
assert_matches!(
Username::new(""),
Err(prae::ConstructionError { original, .. }) if original == UsernameError {}
);
}
#[test]
fn construction_succeeds_for_valid_data() {
let un = Username::new(" user ").unwrap();
assert_eq!(un.get(), " user ");
}
#[test]
fn mutation_fails_for_invalid_data() {
let mut un = Username::new("user").unwrap();
assert_matches!(
un.mutate(|u| *u = "".to_owned()),
Err(prae::MutationError { original, .. }) if original == UsernameError {}
);
}
#[test]
fn mutation_succeeds_for_valid_data() {
let mut un = Username::new("user").unwrap();
un.mutate(|u| *u = " new user ".to_owned()).unwrap();
assert_eq!(un.get(), " new user ");
}
| rust | Unlicense | bd2bfd476108ebcfcb91c2710fdf92eb123a169d | 2026-01-04T20:20:00.811147Z | false |
teenjuna/prae | https://github.com/teenjuna/prae/blob/bd2bfd476108ebcfcb91c2710fdf92eb123a169d/prae/tests/adjust.rs | prae/tests/adjust.rs | use prae::Wrapper;
prae::define! {
#[derive(Debug)]
Username: String;
adjust |u| *u = u.trim().to_owned();
}
#[test]
fn construction_adjusted() {
let u = Username::new(" ").unwrap();
assert_eq!(u.get(), "");
}
#[test]
fn mutation_adjusted() {
let mut u = Username::new("something").unwrap();
u.mutate(|u| *u = " something new ".to_owned()).unwrap();
assert_eq!(u.get(), "something new");
}
| rust | Unlicense | bd2bfd476108ebcfcb91c2710fdf92eb123a169d | 2026-01-04T20:20:00.811147Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d10p1.rs | 2024/d10p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let line_len = 1 + u8x64::from_slice(input.get_unchecked(..64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
let len = input.len() - 1;
let mut chunk_lens = [input.len() / 64 / par::NUM_THREADS * 64; par::NUM_THREADS];
for i in 0..input.len() / 64 % par::NUM_THREADS {
chunk_lens[i] += 64;
}
chunk_lens[par::NUM_THREADS - 1] += input.len() % 64;
let mut chunk_pos = [0; par::NUM_THREADS + 1];
for i in 0..par::NUM_THREADS {
chunk_pos[i + 1] = chunk_pos[i] + chunk_lens[i];
}
let acc = std::sync::atomic::AtomicU64::new(0);
par::par(|idx| {
let mut tot = 0;
let mut offset = chunk_pos[idx];
let end = chunk_pos[idx + 1];
loop {
let mut mask = if offset + 64 <= end {
let block = u8x64::from_slice(input.get_unchecked(offset..offset + 64));
block.simd_eq(u8x64::splat(b'9')).to_bitmask()
} else if offset < end {
let block = u8x64::from_slice(input.get_unchecked(input.len() - 64..));
block.simd_eq(u8x64::splat(b'9')).to_bitmask() >> (64 - (input.len() - offset))
} else {
break;
};
while mask != 0 {
let o = mask.trailing_zeros();
mask &= !(1 << o);
let mut seen = u16x16::from_slice(&[u16::MAX; 16]);
let mut seen_len = 0;
let mut stack = [MaybeUninit::uninit(); 16];
let mut stack_len = 0;
let mut curr_o = offset + o as usize;
let mut c = b'9';
loop {
if c == b'0' {
if seen.simd_ne(u16x16::splat(curr_o as u16)).all() {
*seen.as_mut_array().get_unchecked_mut(seen_len) = curr_o as u16;
seen_len += 1;
}
if stack_len == 0 {
break;
}
stack_len -= 1;
(curr_o, c) = stack.get_unchecked(stack_len).assume_init();
continue;
}
let l = curr_o.wrapping_sub(1);
let r = curr_o.wrapping_add(1);
let t = curr_o.wrapping_sub(line_len);
let b = curr_o.wrapping_add(line_len);
macro_rules! handle {
($new_o:expr) => {{
let new_o = $new_o;
if *input.get_unchecked(new_o) == c - 1 {
*stack.get_unchecked_mut(stack_len).as_mut_ptr() = (new_o, c - 1);
stack_len += 1;
}
}};
}
if t < len - 2 * line_len {
handle!(t);
handle!(b);
handle!(l);
} else {
if t < len {
handle!(t);
handle!(l);
if b < len {
handle!(b);
}
} else {
handle!(b);
if l < len {
handle!(l);
}
}
}
if *input.get_unchecked(r) == c - 1 {
(curr_o, c) = (r, c - 1);
} else if stack_len > 0 {
stack_len -= 1;
(curr_o, c) = stack.get_unchecked(stack_len).assume_init();
} else {
break;
}
}
tot += seen_len;
}
offset += 64;
}
acc.fetch_add(tot as u64, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d07p2.rs | 2024/d07p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(fn_align)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[inline(always)]
pub unsafe fn parse1(mut ptr: *const u8, buf: &mut [u32; 16], buf_len: &mut usize, goal: &mut u64) {
let mut acc = *ptr as u64 - b'0' as u64;
loop {
ptr = ptr.add(1);
let b = (*ptr as u64).wrapping_sub(b'0' as u64);
if b >= 10 {
break;
}
acc = 10 * acc + b;
}
*goal = acc;
ptr = ptr.add(1);
*buf_len = 0;
while *ptr != b'\n' {
ptr = ptr.add(1);
let mut acc = *ptr as u32 - b'0' as u32;
loop {
ptr = ptr.add(1);
let b = (*ptr as u32).wrapping_sub(b'0' as u32);
if b >= 10 {
break;
}
acc = 10 * acc + b;
}
*buf.get_unchecked_mut(*buf_len) = acc;
*buf_len += 1;
}
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 850];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let chunk_len = lines.len().div_ceil(par::NUM_THREADS);
par::par(|idx| {
let chunk = lines.get_unchecked(chunk_len * idx..);
let chunk = chunk.get_unchecked(..std::cmp::min(chunk.len(), chunk_len));
let mut tot = 0;
let mut max = [0; 16];
let mut buf = [0; 16];
let mut buf_len = 0;
let mut goal = 0;
let mut stack = [(0, 0); 32];
let mut stack_len;
for &i in chunk {
parse1(input.as_ptr().add(i), &mut buf, &mut buf_len, &mut goal);
let (add, mul) = (buf[0] + buf[1], buf[0] * buf[1]);
max[0] = buf[0] as u64;
max[1] = std::cmp::max(add, mul) as u64;
let min2 = std::cmp::min(add, mul) as u64;
for i in 2..buf_len {
*max.get_unchecked_mut(i) = std::cmp::max(
*max.get_unchecked(i - 1) + 1,
*max.get_unchecked(i - 1) * *buf.get_unchecked(i) as u64,
);
}
stack[0] = (goal, buf_len - 1);
stack_len = 1;
'outer: while stack_len != 0 {
let (mut local_goal, mut i) = *stack.get_unchecked(stack_len - 1);
stack_len -= 1;
loop {
if local_goal >= *max.get_unchecked(i) {
if local_goal == *max.get_unchecked(i) {
tot += goal;
break 'outer;
}
continue 'outer;
}
if i == 1 {
if local_goal == min2 {
tot += goal;
break 'outer;
}
continue 'outer;
}
let n = *buf.get_unchecked(i) as u64;
std::hint::assert_unchecked(n != 0);
if local_goal.wrapping_sub(n) <= *max.get_unchecked(i - 1) {
*stack.get_unchecked_mut(stack_len) = (local_goal - n, i - 1);
stack_len += 1;
}
if local_goal % n == 0 {
local_goal /= n;
i -= 1;
} else {
break;
}
}
}
}
sum.fetch_add(tot, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
#[inline(always)]
pub unsafe fn parse2(
mut ptr: *const u8,
buf: &mut [(u32, u32); 16],
buf_len: &mut usize,
goal: &mut u64,
) {
let mut acc = *ptr as u64 - b'0' as u64;
loop {
ptr = ptr.add(1);
let b = (*ptr as u64).wrapping_sub(b'0' as u64);
if b >= 10 {
break;
}
acc = 10 * acc + b;
}
*goal = acc;
ptr = ptr.add(1);
*buf_len = 0;
while *ptr != b'\n' {
ptr = ptr.add(1);
let mut acc = *ptr as u32 - b'0' as u32;
let mut pow10idx = 0;
loop {
ptr = ptr.add(1);
let b = (*ptr as u32).wrapping_sub(b'0' as u32);
if b >= 10 {
break;
}
acc = 10 * acc + b;
pow10idx += 1;
}
*buf.get_unchecked_mut(*buf_len) = (acc, pow10idx);
*buf_len += 1;
}
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 850];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let chunk_len = lines.len().div_ceil(par::NUM_THREADS);
par::par(|idx| {
let chunk = lines.get_unchecked(chunk_len * idx..);
let chunk = chunk.get_unchecked(..std::cmp::min(chunk.len(), chunk_len));
let mut tot = 0;
let mut max = [0; 16];
let mut buf = [(0, 0); 16];
let mut buf_len = 0;
let mut goal = 0;
let mut stack = [(0, 0); 32];
let mut stack_len;
for &i in chunk {
parse2(input.as_ptr().add(i), &mut buf, &mut buf_len, &mut goal);
max[0] = buf[0].0 as u64;
for i in 1..buf_len {
static LUT: [u64; 3] = [10, 100, 1000];
let (n, l) = *buf.get_unchecked(i);
let pow10 = *LUT.get_unchecked(l as usize);
*max.get_unchecked_mut(i) = *max.get_unchecked(i - 1) * pow10 + n as u64;
}
let a2 = (buf[0].0 + buf[1].0) as u64;
let m2 = (buf[0].0 * buf[1].0) as u64;
stack[0] = (goal, buf_len - 1);
stack_len = 1;
'outer: while stack_len > 0 {
let (mut local_goal, mut i) = *stack.get_unchecked(stack_len - 1);
stack_len -= 1;
loop {
if local_goal >= *max.get_unchecked(i) {
if local_goal == *max.get_unchecked(i) {
tot += goal;
break 'outer;
}
continue 'outer;
}
if i == 1 {
if local_goal == a2 || local_goal == m2 {
tot += goal;
break 'outer;
}
continue 'outer;
}
let (n, l) = *buf.get_unchecked(i);
let (n, l) = (n as u64, l as usize);
std::hint::assert_unchecked(n != 0);
if local_goal.wrapping_sub(n) <= *max.get_unchecked(i - 1) {
*stack.get_unchecked_mut(stack_len) = (local_goal - n, i - 1);
stack_len += 1;
}
use fastdiv::PrecomputedDivU64;
static LUT: [PrecomputedDivU64; 3] = [
PrecomputedDivU64::new(10),
PrecomputedDivU64::new(100),
PrecomputedDivU64::new(1000),
];
let pow10 = *LUT.get_unchecked(l);
if local_goal > n && PrecomputedDivU64::is_multiple_of(local_goal - n, pow10) {
*stack.get_unchecked_mut(stack_len) =
(PrecomputedDivU64::fast_div(local_goal - n, pow10), i - 1);
stack_len += 1;
}
if local_goal % n == 0 {
local_goal /= n;
i -= 1;
} else {
break;
}
}
}
}
sum.fetch_add(tot, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
mod fastdiv {
#[inline]
const fn mul128_u64(lowbits: u128, d: u64) -> u64 {
let mut bottom_half = (lowbits & 0xFFFFFFFFFFFFFFFF) * d as u128;
bottom_half >>= 64;
let top_half = (lowbits >> 64) * d as u128;
let both_halves = bottom_half + top_half;
(both_halves >> 64) as u64
}
#[inline]
const fn divide_128_max_by_64(divisor: u16) -> u128 {
let divisor = divisor as u64;
let quotient_hi = core::u64::MAX / divisor as u64;
let remainder_hi = core::u64::MAX - quotient_hi * divisor;
let quotient_lo = {
let numerator_mid = (remainder_hi << 32) | core::u32::MAX as u64;
let quotient_mid = numerator_mid / divisor;
let remainder_mid = numerator_mid - quotient_mid * divisor;
let numerator_lo = (remainder_mid << 32) | core::u32::MAX as u64;
let quotient_lo = numerator_lo / divisor;
(quotient_mid << 32) | quotient_lo
};
((quotient_hi as u128) << 64) | (quotient_lo as u128)
}
#[inline]
const fn compute_m_u64(d: u64) -> u128 {
divide_128_max_by_64(d as u16) + 1
}
// for d > 1
#[inline]
const fn fastdiv_u64(a: u64, m: u128) -> u64 {
mul128_u64(m, a)
}
#[inline]
const fn is_divisible_u64(n: u64, m: u128) -> bool {
(n as u128).wrapping_mul(m) <= m - 1
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct PrecomputedDivU64(u128);
impl PrecomputedDivU64 {
#[inline]
pub const fn new(n: u64) -> Self {
Self(compute_m_u64(n))
}
#[inline]
pub fn fast_div(n: u64, precomputed: Self) -> u64 {
fastdiv_u64(n, precomputed.0)
}
#[inline]
pub fn is_multiple_of(n: u64, precomputed: Self) -> bool {
is_divisible_u64(n, precomputed.0)
}
}
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d03p2.rs | 2024/d03p2.rs | // Original by: ameo
#![feature(array_chunks, array_windows, duration_constructors, portable_simd)]
use std::{
fmt::Display,
simd::{cmp::SimdPartialEq, u8x32, u8x64},
};
// pub const INPUT: &'static [u8] = include_bytes!("../inputs/day3.txt");
fn parse_digit(c: u8) -> usize {
(c - 48) as usize
}
#[inline(always)]
fn add_num(digits: &[usize]) -> usize {
match digits.len() {
0 => unreachable!(),
1 => unsafe { *digits.get_unchecked(0) },
2 => 10 * unsafe { *digits.get_unchecked(0) } + unsafe { *digits.get_unchecked(1) },
3 => {
100 * unsafe { *digits.get_unchecked(0) }
+ 10 * unsafe { *digits.get_unchecked(1) }
+ unsafe { *digits.get_unchecked(2) }
}
_ => unreachable!(),
}
}
const MUL: [u8; 4] = ['m' as u8, 'u' as u8, 'l' as u8, '(' as u8];
const DONT: [u8; 7] = [
'd' as u8, 'o' as u8, 'n' as u8, '\'' as u8, 't' as u8, '(' as u8, ')' as u8,
];
const DO: [u8; 4] = ['d' as u8, 'o' as u8, '(' as u8, ')' as u8];
// shortest valid mul is `mul(1,1)` so 8 chars
const MIN_VALID_MUL_LEN: usize = 8;
pub fn parse_and_compute<const ENABLE_DO_STATE: bool>(input: &[u8]) -> usize {
let mut sum = 0usize;
let mut do_state = true;
let mut char_ix = 0usize;
'outer: loop {
if char_ix >= input.len() - MIN_VALID_MUL_LEN {
return sum;
}
// For part 2, when the "do" mode is set to "don't", we only care about finding `d` characters.
//
// Since d's are so much sparser in the inputs than m's, there's a decent chance it will be more
// than 32 chars ahead and the overhead of reading further tends to be worth it.
if ENABLE_DO_STATE && !do_state && char_ix < input.len() - (64 + 1) {
let vector = unsafe {
u8x64::from_slice(std::slice::from_raw_parts(input.as_ptr().add(char_ix), 64))
};
let mask = vector.simd_eq(u8x64::splat('d' as u8));
let hit_ix = match mask.first_set() {
Some(hit_ix) => hit_ix,
None => {
// no hit in the entire window; skip it completely and move on to the next
char_ix += 64;
continue;
}
};
char_ix += hit_ix;
}
// Try to find the first relavant start character in the input by checking 32 at a time and then
// selecting the index of the first match
else if char_ix < input.len() - (32 + 1) {
let vector = unsafe {
u8x32::from_slice(std::slice::from_raw_parts(input.as_ptr().add(char_ix), 32))
};
// Same as before, if we're keeping track of do/don't state and the do flag is not set, we can
// avoid checking for `m` characters entirely and just scan for the next `d`.
let combined_mask = if ENABLE_DO_STATE {
let d_mask = vector.simd_eq(u8x32::splat('d' as u8));
if !do_state {
d_mask
} else {
let m_mask = vector.simd_eq(u8x32::splat('m' as u8));
m_mask | d_mask
}
} else {
vector.simd_eq(u8x32::splat('m' as u8))
};
let hit_ix = match combined_mask.first_set() {
Some(hit_ix) => hit_ix,
None => {
// no hit in the entire window; skip it completely and move on to the next
char_ix += 32;
continue;
}
};
char_ix += hit_ix;
}
// We use char-by-char checks for the remainder of the window
else {
let mut c = unsafe { *input.get_unchecked(char_ix) };
while c != 'm' as u8 && (!ENABLE_DO_STATE || c != 'd' as u8) {
char_ix += 1;
if char_ix >= input.len() {
return sum;
}
c = unsafe { *input.get_unchecked(char_ix) };
}
}
// don't bother parsing out this mul if we're not doing
if (!ENABLE_DO_STATE || do_state) && input.get(char_ix..char_ix + MUL.len()) == Some(&MUL) {
char_ix += MUL.len();
// try to fastpath consume nums
let first_num;
let second_num;
let mut d0;
let mut d1;
let mut d2;
// first char after `mul(` must be a digit
let mut c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
if c >= '0' as u8 && c <= '9' as u8 {
d0 = parse_digit(c);
} else {
continue;
}
// next char `mul(1_` can be either digit or comma
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
if c >= '0' as u8 && c <= '9' as u8 {
d1 = parse_digit(c);
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next char `mul(12_` can also be either digit or comma
if c >= '0' as u8 && c <= '9' as u8 {
d2 = parse_digit(c);
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next char `mul(123_` MUST be a comma if this mul is valid
if c != ',' as u8 {
continue 'outer;
}
first_num = add_num(&[d0, d1, d2]);
} else if c == ',' as u8 {
first_num = add_num(&[d0, d1]);
} else {
continue 'outer;
}
} else if c == ',' as u8 {
first_num = d0;
} else {
continue 'outer;
}
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next character `mul(123,_` must be a digit
if c >= '0' as u8 && c <= '9' as u8 {
d0 = parse_digit(c);
} else {
continue;
}
// finish parsing second arg. Assuming that args have at most 3 chars, so take at most two
// more digits followed by a `)`
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next character `mul(123,1_` can be either digit or `)`
if c >= '0' as u8 && c <= '9' as u8 {
d1 = parse_digit(c);
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next char `mul(123,12_` can also be either digit or `)`
if c >= '0' as u8 && c <= '9' as u8 {
d2 = parse_digit(c);
c = unsafe { *input.get_unchecked(char_ix) };
char_ix += 1;
// next char `mul(123,123_` MUST be a `)` if this mul is valid
if c != ')' as u8 {
continue 'outer;
}
second_num = add_num(&[d0, d1, d2]);
} else if c == ')' as u8 {
second_num = add_num(&[d0, d1]);
} else {
continue 'outer;
}
} else if c == ')' as u8 {
second_num = d0;
} else {
continue 'outer;
}
sum += first_num * second_num;
} else if ENABLE_DO_STATE
&& do_state
&& input.get(char_ix..char_ix + DONT.len()) == Some(&DONT)
{
do_state = false;
char_ix += DONT.len();
} else if ENABLE_DO_STATE
&& !do_state
&& input.get(char_ix..char_ix + DO.len()) == Some(&DO)
{
do_state = true;
char_ix += DO.len();
} else {
char_ix += 1;
}
}
}
// pub fn solve() {
// let out = parse_and_compute::<false>(INPUT);
// println!("Part 1: {out}");
// let out = parse_and_compute::<true>(INPUT);
// println!("Part 2: {out}");
// }
pub fn run(input: &[u8]) -> impl Display {
parse_and_compute::<true>(input)
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d16p2.rs | 2024/d16p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::mem::MaybeUninit;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u32 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u32 {
unsafe { inner_part2(input) }
}
const START: u32 = 142 * 139 + 1;
const END: u32 = 142 * 1 + 139;
const UP: usize = -142isize as _;
const DOWN: usize = 142;
const LEFT: usize = -1isize as _;
const RIGHT: usize = 1;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u32 {
let input = input.as_bytes();
let mut seen_h = [0u64; (2 * 141 * 142 + 63) / 64];
let mut seen_v = [0u64; (2 * 141 * 142 + 63) / 64];
let mut queue_h = [MaybeUninit::uninit(); 256];
let mut queue_v = [MaybeUninit::uninit(); 256];
let mut queue_h_len = 1;
let mut queue_v_len = 1;
*queue_h.get_unchecked_mut(0).as_mut_ptr() = (START, 0);
*queue_v.get_unchecked_mut(0).as_mut_ptr() = (START, 1000);
let mut end_cost = u32::MAX;
macro_rules! advance {
($pos:ident, $cost:ident, $dir:ident, $pdir1:ident, $pdir2:ident, $queue:ident, $queue_len:ident, $seen:ident) => {{
let mut next_pos = $pos as usize;
let mut next_cost = $cost;
'advance: loop {
next_pos = next_pos.wrapping_add($dir);
next_cost += 1;
if *input.get_unchecked(next_pos) != b'.' {
if next_pos as u32 == END {
end_cost = end_cost.min(next_cost);
}
break;
}
let up = next_pos.wrapping_add($pdir1);
let down = next_pos.wrapping_add($pdir2);
if *input.get_unchecked(up) != b'#' || *input.get_unchecked(down) != b'#' {
if *$seen.get_unchecked(next_pos / 64) & (1 << (next_pos % 64)) == 0 {
let idx = 2 * next_pos;
if $seen.get_unchecked(idx / 64) & (1 << (idx % 64)) != 0 {
for i in 0..$queue_len {
let (old_pos, old_cost) =
&mut *$queue.get_unchecked_mut(i).as_mut_ptr();
if *old_pos == next_pos as u32 {
*old_cost = (*old_cost).min(next_cost + 1000);
continue 'advance;
}
}
}
*$seen.get_unchecked_mut(idx / 64) |= 1 << (idx % 64);
let ptr = $queue.get_unchecked_mut($queue_len).as_mut_ptr();
*ptr = (next_pos as u32, next_cost + 1000);
$queue_len += 1;
}
}
}
}};
}
loop {
for i in 0..std::mem::take(&mut queue_h_len) {
let (pos, cost) = *queue_h.get_unchecked(i).as_ptr();
*seen_h.get_unchecked_mut(pos as usize / 64) |= 1 << (pos % 64);
advance!(pos, cost, LEFT, UP, DOWN, queue_v, queue_v_len, seen_v);
advance!(pos, cost, RIGHT, UP, DOWN, queue_v, queue_v_len, seen_v);
}
if end_cost != u32::MAX {
return end_cost;
}
for i in 0..std::mem::take(&mut queue_v_len) {
let (pos, cost) = *queue_v.get_unchecked(i).as_ptr();
*seen_v.get_unchecked_mut(pos as usize / 64) |= 1 << (pos % 64);
advance!(pos, cost, UP, LEFT, RIGHT, queue_h, queue_h_len, seen_h);
advance!(pos, cost, DOWN, LEFT, RIGHT, queue_h, queue_h_len, seen_h);
}
if end_cost != u32::MAX {
return end_cost;
}
}
}
const LEFT_ID: DirId = DirId(0b00);
const RIGHT_ID: DirId = DirId(0b11);
const UP_ID: DirId = DirId(0b10);
const DOWN_ID: DirId = DirId(0b01);
static DIR_MAP: [usize; 4] = {
let mut dirs = [0; 4];
dirs[LEFT_ID.idx()] = LEFT;
dirs[RIGHT_ID.idx()] = RIGHT;
dirs[UP_ID.idx()] = UP;
dirs[DOWN_ID.idx()] = DOWN;
dirs
};
#[derive(Copy, Clone)]
#[repr(transparent)]
struct DirId(u16);
impl DirId {
const fn parity(self) -> usize {
(self.0 & 1) as usize
}
const fn kind(self) -> u16 {
(self.0 ^ (self.0 >> 1)) & 1
}
const fn invert(self) -> DirId {
Self(self.0 ^ 0b11)
}
const fn perp1(self) -> DirId {
Self(self.0 ^ 0b01)
}
const fn perp2(self) -> DirId {
Self(self.0 ^ 0b10)
}
const fn idx(self) -> usize {
self.0 as usize
}
}
const START_H_ID: u16 = 0;
const START_V_ID: u16 = START_H_ID + 1;
const END_H_ID: u16 = 2;
const END_V_ID: u16 = END_H_ID + 1;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u32 {
let input = input.as_bytes();
let mut ids = [u16::MAX; 141 * 142];
ids[START as usize] = START_H_ID;
ids[END as usize] = END_H_ID;
let mut next_id = 4;
let mut moves = [MaybeUninit::<[(u16, u8, u8); 2]>::uninit(); 3000];
moves[START_H_ID as usize] = MaybeUninit::new([(u16::MAX, 0, 0); 2]);
moves[START_V_ID as usize] = MaybeUninit::new([(u16::MAX, 0, 0); 2]);
moves[END_H_ID as usize] = MaybeUninit::new([(u16::MAX, 0, 0); 2]);
moves[END_V_ID as usize] = MaybeUninit::new([(u16::MAX, 0, 0); 2]);
let mut queue = [MaybeUninit::uninit(); 512];
let mut queue_len = 0;
if *input.get_unchecked((START as usize).wrapping_add(RIGHT)) != b'#' {
*queue.get_unchecked_mut(queue_len).as_mut_ptr() = (START, RIGHT_ID, START_H_ID);
queue_len += 1;
}
if *input.get_unchecked((START as usize).wrapping_add(UP)) != b'#' {
*queue.get_unchecked_mut(queue_len).as_mut_ptr() = (START, UP_ID, START_V_ID);
queue_len += 1;
}
'queue: while queue_len != 0 {
queue_len -= 1;
let (pos, start_dir_id, start_id) = *queue.get_unchecked(queue_len).as_ptr();
let m = &*moves.get_unchecked(start_id as usize).as_ptr();
if m.get_unchecked(start_dir_id.parity() as usize).0 != u16::MAX {
continue;
}
let mut pos = pos as usize;
let mut dir_id = start_dir_id;
let mut turns = 0;
let mut tiles = 0;
let mut dir = *DIR_MAP.get_unchecked(dir_id.idx());
let mut dir1 = *DIR_MAP.get_unchecked(dir_id.perp1().idx());
let mut dir2 = *DIR_MAP.get_unchecked(dir_id.perp2().idx());
debug_assert_ne!(input[pos] as char, '#');
debug_assert_ne!(
input[pos.wrapping_add(dir)] as char,
'#',
"{} {}, {} {}, {}",
pos % 142,
pos / 142,
pos.wrapping_add(dir) % 142,
pos.wrapping_add(dir) / 142,
dir as isize
);
'inner: loop {
pos = pos.wrapping_add(dir);
tiles += 1;
let cont = *input.get_unchecked(pos.wrapping_add(dir)) != b'#';
let cont1 = *input.get_unchecked(pos.wrapping_add(dir1)) != b'#';
let cont2 = *input.get_unchecked(pos.wrapping_add(dir2)) != b'#';
debug_assert_ne!(input[pos] as char, '#', "{} {}", pos % 142, pos / 142);
if !cont1 && !cont2 {
if cont {
// go straight
continue 'inner;
} else if pos != START as usize && pos != END as usize {
// deadend
continue 'queue;
}
}
if cont || (cont1 && cont2) || pos == START as usize || pos == END as usize {
// new node
let mut dest_id = *ids.get_unchecked(pos) | dir_id.kind();
if dest_id == u16::MAX {
dest_id = next_id | dir_id.kind();
*ids.get_unchecked_mut(pos) = next_id;
*moves.get_unchecked_mut(next_id as usize).as_mut_ptr() = [(u16::MAX, 0, 0); 2];
*moves.get_unchecked_mut(next_id as usize + 1).as_mut_ptr() =
[(u16::MAX, 0, 0); 2];
debug_assert!(dest_id == next_id || dest_id == next_id + 1);
next_id += 2;
let m = &*moves.get_unchecked(dest_id as usize).as_ptr();
if cont {
debug_assert_eq!(m.get_unchecked(dir_id.invert().parity()).0, u16::MAX);
*queue.get_unchecked_mut(queue_len).as_mut_ptr() =
(pos as u32, dir_id, dest_id);
queue_len += 1;
}
let m = &*moves.get_unchecked(dest_id as usize ^ 1).as_ptr();
let dir1_id = dir_id.perp1();
if cont1 && m.get_unchecked(dir1_id.parity()).0 == u16::MAX {
*queue.get_unchecked_mut(queue_len).as_mut_ptr() =
(pos as u32, dir1_id, dest_id ^ 1);
queue_len += 1;
}
let dir2_id = dir_id.perp2();
if cont2 && m.get_unchecked(dir2_id.parity()).0 == u16::MAX {
*queue.get_unchecked_mut(queue_len).as_mut_ptr() =
(pos as u32, dir2_id, dest_id ^ 1);
queue_len += 1;
}
}
// if start_id & !1 == 0 && dest_id & !1 == 4 {
// println!(
// "setting! {start_id} -> {dest_id} [{} {}] {turns} {tiles}",
// dir_id.invert().parity(),
// dir_id.kind(),
// );
// }
// if start_id & !1 == 4 && dest_id & !1 == 10 {
// println!(
// "setting! {start_id} -> {dest_id} [{} {}] {turns} {tiles}",
// dir_id.invert().parity(),
// dir_id.kind(),
// );
// }
// if start_id & !1 == 10 && dest_id & !1 == 4 {
// println!(
// "setting! {start_id} -> {dest_id} [{} {}] {turns} {tiles}",
// dir_id.invert().parity(),
// dir_id.kind(),
// );
// }
*(*moves.get_unchecked_mut(start_id as usize).as_mut_ptr())
.get_unchecked_mut(start_dir_id.parity()) = (dest_id, turns, tiles);
*(*moves.get_unchecked_mut(dest_id as usize).as_mut_ptr())
.get_unchecked_mut(dir_id.invert().parity()) = (start_id, turns, tiles);
continue 'queue;
} else {
// turn
dir_id = if cont1 {
dir_id.perp1()
} else {
dir_id.perp2()
};
dir = *DIR_MAP.get_unchecked(dir_id.idx());
dir1 = *DIR_MAP.get_unchecked(dir_id.perp1().idx());
dir2 = *DIR_MAP.get_unchecked(dir_id.perp2().idx());
turns += 1;
continue 'inner;
}
}
}
// TODO reuse previous queue
let mut queue = MaybeUninit::<[u64; 128]>::uninit();
*queue.as_mut_ptr().cast::<[u32; 2]>().add(0) = [START_H_ID as u32, 0];
let mut queue_len = 1;
macro_rules! mk_queue_slice {
() => {{
debug_assert!(queue_len <= 128);
std::slice::from_raw_parts_mut(queue.as_mut_ptr().cast::<u64>(), queue_len)
}};
}
let (_, costs, _) = ids.align_to_mut::<u32>();
let costs = &mut costs[..next_id as usize];
costs.fill(u32::MAX / 2);
let end_cost = loop {
// TODO: Binary queue
let [id, cost] = *queue.as_ptr().cast::<[u32; 2]>();
bheap::pop(mk_queue_slice!());
queue_len -= 1;
// let pos = positions[id as usize / 2];
// let (x, y) = (pos % 142, pos / 142);
// println!("{id:>4}: {x:>3} {y:>3} | {cost}");
// println!("{:?}", mk_queue_slice!());
// println!("{id:>4} | {cost}");
// if cost > 10000 {
// panic!();
// }
let cost_ref = costs.get_unchecked_mut(id as usize);
if *cost_ref <= cost {
continue;
}
*cost_ref = cost;
let cost_swap = costs.get_unchecked_mut(id as usize ^ 1);
*cost_swap = (*cost_swap).min(cost + 1000);
if id as u16 & !1 == END_H_ID {
break cost;
}
let m = *moves.get_unchecked(id as usize).as_ptr();
let (next_id, turns, tiles) = m[0];
let next_cost = cost + turns as u32 * 1000 + tiles as u32;
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) > next_cost {
// TODO: insert with extra_cost
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
bheap::push(mk_queue_slice!());
}
let (next_id, turns, tiles) = m[1];
let next_cost = cost + turns as u32 * 1000 + tiles as u32;
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) > next_cost {
// TODO: insert with extra_cost
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
bheap::push(mk_queue_slice!());
}
// if *costs.get_unchecked(id as usize ^ 1) > cost + 1000 {
// *queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [id as u32 ^ 1, cost + 1000];
// queue_len += 1;
// bheap::push(mk_queue_slice!());
// }
let m = *moves.get_unchecked(id as usize ^ 1).as_ptr();
let (next_id, turns, tiles) = m[0];
let next_cost = cost + turns as u32 * 1000 + 1000 + tiles as u32;
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) > next_cost {
// TODO: insert with extra_cost + 1000
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
bheap::push(mk_queue_slice!());
}
let (next_id, turns, tiles) = m[1];
let next_cost = cost + turns as u32 * 1000 + 1000 + tiles as u32;
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) > next_cost {
// TODO: insert with extra_cost + 1000
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
bheap::push(mk_queue_slice!());
}
};
while queue_len != 0 {
let [id, cost] = *queue.as_ptr().cast::<[u32; 2]>();
if cost > end_cost {
break;
}
let cost_ref = costs.get_unchecked_mut(id as usize);
if *cost_ref > cost {
*cost_ref = cost;
let cost_swap = costs.get_unchecked_mut(id as usize ^ 1);
*cost_swap = (*cost_swap).min(cost + 1000);
}
bheap::pop(mk_queue_slice!());
queue_len -= 1;
}
queue_len = 0;
if *costs.get_unchecked(END_H_ID as usize) == end_cost {
*queue.as_mut_ptr().cast::<[u32; 2]>().add(0) = [END_H_ID as u32, end_cost];
queue_len += 1;
}
if *costs.get_unchecked(END_V_ID as usize) == end_cost {
*queue.as_mut_ptr().cast::<[u32; 2]>().add(0) = [END_V_ID as u32, end_cost];
queue_len += 1;
}
// println!("{:?} {:?}", costs[4], costs[5]);
// println!("{:?} {:?}", costs[0], costs[1]);
// println!("{:?} {:?}", moves[4].assume_init(), moves[5].assume_init());
// println!("{:?} {:?}", moves[0].assume_init(), moves[1].assume_init());
#[cfg(debug_assertions)]
let mut seen = std::collections::HashSet::new();
let mut count = 0;
while queue_len != 0 {
queue_len -= 1;
let [id, ex_cost] = *queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len);
// if id == START_H_ID as _ {
// println!("start h! 1");
// }
// if id == START_V_ID as _ {
// println!("start v! 1");
// }
const SMASK: u32 = 1 << 31;
let cost_ref = costs.get_unchecked_mut(id as usize);
if *cost_ref != ex_cost {
debug_assert!((*cost_ref > ex_cost && *cost_ref < end_cost) || *cost_ref & SMASK != 0);
continue;
}
*cost_ref |= SMASK;
// println!("{id}, {ex_cost}");
#[cfg(debug_assertions)]
debug_assert!(seen.insert(id));
if *costs.get_unchecked(id as usize ^ 1) & SMASK == 0 {
#[cfg(debug_assertions)]
debug_assert!(!seen.contains(&(id ^ 1)));
count += 1;
} else {
#[cfg(debug_assertions)]
debug_assert!(seen.contains(&(id ^ 1)));
}
// if id == START_H_ID as _ {
// println!("start h!");
// }
// if id == START_V_ID as _ {
// println!("start v!");
// }
let m = *moves.get_unchecked(id as usize).as_ptr();
let (next_id, turns, tiles) = m[0];
let next_cost = ex_cost.wrapping_sub(turns as u32 * 1000 + tiles as u32);
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) & !SMASK == next_cost {
// TODO: insert with extra_cost
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
count += tiles as u32 - 1;
}
let (next_id, turns, tiles) = m[1];
let next_cost = ex_cost.wrapping_sub(turns as u32 * 1000 + tiles as u32);
if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) & !SMASK == next_cost {
// TODO: insert with extra_cost
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
queue_len += 1;
count += tiles as u32 - 1;
}
let next_cost = ex_cost.wrapping_sub(1000);
if *costs.get_unchecked(id as usize ^ 1) & !SMASK == next_cost {
// TODO: insert with extra_cost + 1000
*queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [id as u32 ^ 1, next_cost];
queue_len += 1;
}
// let m = *moves.get_unchecked(id as usize ^ 1).as_ptr();
// let (next_id, turns, tiles) = m[0];
// let next_cost = ex_cost.wrapping_sub(turns as u32 * 1000 + 1000 + tiles as u32);
// if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) & !SMASK == next_cost {
// // TODO: insert with extra_cost + 1000
// *queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
// queue_len += 1;
// count += tiles as u32 - 1;
// }
// let (next_id, turns, tiles) = m[1];
// let next_cost = ex_cost.wrapping_sub(turns as u32 * 1000 + 1000 + tiles as u32);
// if next_id != u16::MAX && *costs.get_unchecked(next_id as usize) & !SMASK == next_cost {
// // TODO: insert with extra_cost + 1000
// *queue.as_mut_ptr().cast::<[u32; 2]>().add(queue_len) = [next_id as u32, next_cost];
// queue_len += 1;
// count += tiles as u32 - 1;
// }
}
// println!("{:?} {:?}", costs[4], costs[5]);
// println!("{:?} {:?}", costs[0], costs[1]);
count
}
mod bheap {
#[inline(always)]
pub unsafe fn pop<T: Copy + Ord>(heap: &mut [T]) {
if heap.len() > 1 {
// len = len - 1
//
// sift_down_to_bottom(0)
let start = 0;
let end = heap.len() - 1;
let hole = *heap.get_unchecked(heap.len() - 1);
let mut hole_pos = start;
let mut child = 2 * hole_pos + 1;
while child <= end.saturating_sub(2) {
child += (*heap.get_unchecked(child) >= *heap.get_unchecked(child + 1)) as usize;
*heap.get_unchecked_mut(hole_pos) = *heap.get_unchecked(child);
hole_pos = child;
child = 2 * hole_pos + 1;
}
if child == end - 1 {
*heap.get_unchecked_mut(hole_pos) = *heap.get_unchecked(child);
hole_pos = child;
}
// sift_up(start, hole_pos)
while hole_pos > start {
let parent = (hole_pos - 1) / 2;
if hole >= *heap.get_unchecked(parent) {
break;
}
*heap.get_unchecked_mut(hole_pos) = *heap.get_unchecked(parent);
hole_pos = parent;
}
*heap.get_unchecked_mut(hole_pos) = hole;
}
}
#[inline(always)]
pub unsafe fn push<T: Copy + Ord>(heap: &mut [T]) {
// sift_up(0, heap.len() - 1)
let start = 0;
let pos = heap.len() - 1;
let hole = *heap.get_unchecked(pos);
let mut hole_pos = pos;
while hole_pos > start {
let parent = (hole_pos - 1) / 2;
if hole >= *heap.get_unchecked(parent) {
break;
}
*heap.get_unchecked_mut(hole_pos) = *heap.get_unchecked(parent);
hole_pos = parent;
}
*heap.get_unchecked_mut(hole_pos) = hole;
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d04p1.rs | 2024/d04p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
use std::ops::Range;
use std::simd::cmp::SimdPartialEq;
use std::simd::u8x64;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
pub fn part1(input: &str) -> u32 {
let input = input.as_bytes();
const R1: Range<usize> = 0..64;
const R2: Range<usize> = 61..125;
const R3: Range<usize> = (140 - 64)..140;
const M2V: u64 = u64::MAX & (!0b111) & ((1 << 61) - 1);
const M3: u64 = !((1u64 << (64 - (140 - 122))) - 1);
#[inline(always)]
fn check_horiz<const N: usize>(mut x: u64, m: u64, a: u64, mut s: u64) -> u32 {
if N == 3 {
x &= M3;
s &= M3;
}
let mut tot = 0;
tot |= x & (m << 1) & (a << 2) & (s << 3);
tot |= s & (a << 1) & (m << 2) & (x << 3);
tot.count_ones()
}
#[inline(always)]
fn check_vert<const N: usize>(
pppx: u64,
ppps: u64,
ppm: u64,
ppa: u64,
pm: u64,
pa: u64,
mut cx: u64,
mut cs: u64,
) -> u32 {
if N == 2 {
cx &= M2V;
cs &= M2V;
} else if N == 3 {
cx &= M3;
cs &= M3;
}
((pppx & ppm & pa & cs) | (ppps & ppa & pm & cx)).count_ones()
}
#[inline(always)]
fn check_diag<const N: usize>(
mut pppx: u64,
mut ppps: u64,
ppm: u64,
ppa: u64,
pm: u64,
pa: u64,
mut cx: u64,
mut cs: u64,
) -> u32 {
if N == 3 {
pppx &= M3;
ppps &= M3;
cx &= M3;
cs &= M3;
}
let mut dl = 0;
dl |= cx & (pm << 1) & (ppa << 2) & (ppps << 3);
dl |= cs & (pa << 1) & (ppm << 2) & (pppx << 3);
let mut dr = 0;
dr |= cx & (pm >> 1) & (ppa >> 2) & (ppps >> 3);
dr |= cs & (pa >> 1) & (ppm >> 2) & (pppx >> 3);
dl.count_ones() + dr.count_ones()
}
let mut count = 0;
let line = &input[0 * 141..][..140];
let ppp1 = u8x64::from_slice(&line[R1]);
let mut pppx1 = ppp1.simd_eq(u8x64::splat(b'X')).to_bitmask();
let pppm1 = ppp1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let pppa1 = ppp1.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ppps1 = ppp1.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<1>(pppx1, pppm1, pppa1, ppps1);
let ppp2 = u8x64::from_slice(&line[R2]);
let mut pppx2 = ppp2.simd_eq(u8x64::splat(b'X')).to_bitmask();
let pppm2 = ppp2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let pppa2 = ppp2.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ppps2 = ppp2.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<2>(pppx2, pppm2, pppa2, ppps2);
let ppp3 = u8x64::from_slice(&line[R3]);
let mut pppx3 = ppp3.simd_eq(u8x64::splat(b'X')).to_bitmask();
let pppm3 = ppp3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let pppa3 = ppp3.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ppps3 = ppp3.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<3>(pppx3, pppm3, pppa3, ppps3);
let line = &input[1 * 141..][..140];
let pp1 = u8x64::from_slice(&line[R1]);
let mut ppx1 = pp1.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut ppm1 = pp1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ppa1 = pp1.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut pps1 = pp1.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<1>(ppx1, ppm1, ppa1, pps1);
let pp2 = u8x64::from_slice(&line[R2]);
let mut ppx2 = pp2.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut ppm2 = pp2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ppa2 = pp2.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut pps2 = pp2.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<2>(ppx2, ppm2, ppa2, pps2);
let pp3 = u8x64::from_slice(&line[R3]);
let mut ppx3 = pp3.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut ppm3 = pp3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ppa3 = pp3.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut pps3 = pp3.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<3>(ppx3, ppm3, ppa3, pps3);
let line = &input[2 * 141..][..140];
let p1 = u8x64::from_slice(&line[R1]);
let mut px1 = p1.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut pm1 = p1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pa1 = p1.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ps1 = p1.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<1>(px1, pm1, pa1, ps1);
let p2 = u8x64::from_slice(&line[R2]);
let mut px2 = p2.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut pm2 = p2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pa2 = p2.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ps2 = p2.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<2>(px2, pm2, pa2, ps2);
let p3 = u8x64::from_slice(&line[R3]);
let mut px3 = p3.simd_eq(u8x64::splat(b'X')).to_bitmask();
let mut pm3 = p3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pa3 = p3.simd_eq(u8x64::splat(b'A')).to_bitmask();
let mut ps3 = p3.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<3>(px3, pm3, pa3, ps3);
for line in input[3 * 141..].chunks_exact(141) {
let c1 = u8x64::from_slice(&line[R1]);
let cx1 = c1.simd_eq(u8x64::splat(b'X')).to_bitmask();
let cm1 = c1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let ca1 = c1.simd_eq(u8x64::splat(b'A')).to_bitmask();
let cs1 = c1.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<1>(cx1, cm1, ca1, cs1);
count += check_vert::<1>(pppx1, ppps1, ppm1, ppa1, pm1, pa1, cx1, cs1);
count += check_diag::<1>(pppx1, ppps1, ppm1, ppa1, pm1, pa1, cx1, cs1);
(pppx1, ppx1, px1) = (ppx1, px1, cx1);
(ppm1, pm1) = (pm1, cm1);
(ppa1, pa1) = (pa1, ca1);
(ppps1, pps1, ps1) = (pps1, ps1, cs1);
let c2 = u8x64::from_slice(&line[R2]);
let cx2 = c2.simd_eq(u8x64::splat(b'X')).to_bitmask();
let cm2 = c2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let ca2 = c2.simd_eq(u8x64::splat(b'A')).to_bitmask();
let cs2 = c2.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<2>(cx2, cm2, ca2, cs2);
count += check_vert::<2>(pppx2, ppps2, ppm2, ppa2, pm2, pa2, cx2, cs2);
count += check_diag::<2>(pppx2, ppps2, ppm2, ppa2, pm2, pa2, cx2, cs2);
(pppx2, ppx2, px2) = (ppx2, px2, cx2);
(ppm2, pm2) = (pm2, cm2);
(ppa2, pa2) = (pa2, ca2);
(ppps2, pps2, ps2) = (pps2, ps2, cs2);
let c3 = u8x64::from_slice(&line[R3]);
let cx3 = c3.simd_eq(u8x64::splat(b'X')).to_bitmask();
let cm3 = c3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let ca3 = c3.simd_eq(u8x64::splat(b'A')).to_bitmask();
let cs3 = c3.simd_eq(u8x64::splat(b'S')).to_bitmask();
count += check_horiz::<3>(cx3, cm3, ca3, cs3);
count += check_vert::<3>(pppx3, ppps3, ppm3, ppa3, pm3, pa3, cx3, cs3);
count += check_diag::<3>(pppx3, ppps3, ppm3, ppa3, pm3, pa3, cx3, cs3);
(pppx3, ppx3, px3) = (ppx3, px3, cx3);
(ppm3, pm3) = (pm3, cm3);
(ppa3, pa3) = (pa3, ca3);
(ppps3, pps3, ps3) = (pps3, ps3, cs3);
}
count
}
pub fn part2(input: &str) -> u32 {
let input = input.as_bytes();
let mut count = 0;
const R1: Range<usize> = 0..64;
const R2: Range<usize> = 62..126;
const R3: Range<usize> = (140 - 64)..140;
const MASK_A3: u64 = !((1u64 << (64 - (140 - 125))) - 1);
let line = &input[..140];
let pp1 = u8x64::from_slice(&line[R1]);
let mut ppm1 = pp1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pps1 = pp1.simd_eq(u8x64::splat(b'S')).to_bitmask();
let pp2 = u8x64::from_slice(&line[R2]);
let mut ppm2 = pp2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pps2 = pp2.simd_eq(u8x64::splat(b'S')).to_bitmask();
let pp3 = u8x64::from_slice(&line[R3]);
let mut ppm3 = pp3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut pps3 = pp3.simd_eq(u8x64::splat(b'S')).to_bitmask();
let line = &input[141..][..140];
let p1 = u8x64::from_slice(&line[R1]);
let mut pm1 = p1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ps1 = p1.simd_eq(u8x64::splat(b'S')).to_bitmask();
let mut pa1 = p1.simd_eq(u8x64::splat(b'A')).to_bitmask();
let p2 = u8x64::from_slice(&line[R2]);
let mut pm2 = p2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ps2 = p2.simd_eq(u8x64::splat(b'S')).to_bitmask();
let mut pa2 = p2.simd_eq(u8x64::splat(b'A')).to_bitmask();
let p3 = u8x64::from_slice(&line[R3]);
let mut pm3 = p3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let mut ps3 = p3.simd_eq(u8x64::splat(b'S')).to_bitmask();
let mut pa3 = p3.simd_eq(u8x64::splat(b'A')).to_bitmask();
#[inline(always)]
fn check_chunk(ppm: u64, pps: u64, pa: u64, cm: u64, cs: u64) -> u32 {
let mut tot = 0;
tot |= (ppm >> 1) & (pps << 1) & pa & (cm >> 1) & (cs << 1);
tot |= (ppm >> 1) & (ppm << 1) & pa & (cs >> 1) & (cs << 1);
tot |= (pps >> 1) & (ppm << 1) & pa & (cs >> 1) & (cm << 1);
tot |= (pps >> 1) & (pps << 1) & pa & (cm >> 1) & (cm << 1);
tot.count_ones()
}
for line in input[141 * 2..].chunks_exact(141) {
let c1 = u8x64::from_slice(&line[R1]);
let cm1 = c1.simd_eq(u8x64::splat(b'M')).to_bitmask();
let cs1 = c1.simd_eq(u8x64::splat(b'S')).to_bitmask();
let ca1 = c1.simd_eq(u8x64::splat(b'A')).to_bitmask();
count += check_chunk(ppm1, pps1, pa1, cm1, cs1);
(ppm1, pps1, pm1, ps1, pa1) = (pm1, ps1, cm1, cs1, ca1);
let c2 = u8x64::from_slice(&line[R2]);
let cm2 = c2.simd_eq(u8x64::splat(b'M')).to_bitmask();
let cs2 = c2.simd_eq(u8x64::splat(b'S')).to_bitmask();
let ca2 = c2.simd_eq(u8x64::splat(b'A')).to_bitmask();
count += check_chunk(ppm2, pps2, pa2, cm2, cs2);
(ppm2, pps2, pm2, ps2, pa2) = (pm2, ps2, cm2, cs2, ca2);
let c3 = u8x64::from_slice(&line[R3]);
let cm3 = c3.simd_eq(u8x64::splat(b'M')).to_bitmask();
let cs3 = c3.simd_eq(u8x64::splat(b'S')).to_bitmask();
let ca3 = c3.simd_eq(u8x64::splat(b'A')).to_bitmask();
count += check_chunk(ppm3, pps3, pa3 & MASK_A3, cm3, cs3);
(ppm3, pps3, pm3, ps3, pa3) = (pm3, ps3, cm3, cs3, ca3);
}
count
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d20p1.rs | 2024/d20p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::mem::transmute;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
const LEFT: usize = -1isize as usize;
const RIGHT: usize = 1isize as usize;
const UP: usize = -142isize as usize;
const DOWN: usize = 142isize as usize;
#[inline(always)]
unsafe fn find_start_end(input: &[u8]) -> (usize, usize) {
let mut offset = 0;
let p1 = loop {
let block = u8x64::from_slice(input.get_unchecked(offset..offset + 64));
let mask = block.simd_ge(u8x64::splat(b'E')).to_bitmask();
if mask != 0 {
break offset + mask.trailing_zeros() as usize;
}
offset += 64;
};
let b = (b'E' + b'S') - *input.get_unchecked(p1);
offset = p1 + 1;
let p2 = loop {
let block = u8x64::from_slice(input.get_unchecked(offset..offset + 64));
let mask = block.simd_eq(u8x64::splat(b)).to_bitmask();
if mask != 0 {
break offset + mask.trailing_zeros() as usize;
}
offset += 64;
};
let (s, e) = if b == b'S' { (p1, p2) } else { (p2, p1) };
(s, e)
}
unsafe fn part1_rec<const DIR: usize>(
input: &[u8; 141 * 142],
seen: &mut [u16; 142 * 143],
curr: usize,
mut n: u16,
mut count: u64,
) -> u64 {
macro_rules! count {
($($d:ident),*) => {$(
if $d != -(DIR as isize) as usize {
if *seen.get_unchecked((curr + 142).wrapping_add($d).wrapping_add($d)) >= n + 101 {
count += 1;
}
}
)*};
}
count!(LEFT, RIGHT, UP, DOWN);
*seen.get_unchecked_mut(curr + 142) = n;
n -= 1;
macro_rules! next {
($($d:ident),*) => {$(
if $d != -(DIR as isize) as usize {
let cand = curr.wrapping_add($d);
if *input.get_unchecked(cand) != b'#' {
// TODO: use become
return part1_rec::<$d>(input, seen, cand, n, count)
}
}
)*};
}
next!(LEFT, RIGHT, UP, DOWN);
count
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input: &[u8; 141 * 142] = input.as_bytes().try_into().unwrap_unchecked();
let (s, _e) = find_start_end(input);
let mut seen = [0; 142 * 143];
let mut n = u16::MAX - 102;
*seen.get_unchecked_mut(s + 142) = n;
n -= 1;
macro_rules! next {
($($d:ident),*) => {$(
let cand = s.wrapping_add($d);
if *input.get_unchecked(cand) != b'#' {
return part1_rec::<$d>(input, &mut seen, cand, n, 0);
}
)*};
}
next!(LEFT, RIGHT, UP, DOWN);
std::hint::unreachable_unchecked()
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
const SLINE: usize = 139 + 28;
#[inline(always)]
unsafe fn next(input: &[u8], iprev: usize, icurr: usize, scurr: usize) -> (usize, usize) {
const SUP: usize = -(SLINE as isize) as usize;
const SDOWN: usize = SLINE;
let mut inext = icurr.wrapping_add(LEFT);
let mut snext = scurr.wrapping_add(LEFT);
for (id, sd) in [(RIGHT, RIGHT), (UP, SUP), (DOWN, SDOWN)] {
let cand = icurr.wrapping_add(id);
if *input.get_unchecked(cand) != b'#' && cand != iprev {
inext = icurr.wrapping_add(id);
snext = scurr.wrapping_add(sd);
}
}
(inext, snext)
}
let input = input.as_bytes();
let (s, e) = find_start_end(input);
let mut seen = [0; 20 + (139 + 40) * SLINE];
let mut count = u32x16::splat(0);
let mut iprev = 0;
let mut icurr = s;
let mut scurr = 20 + SLINE * (s / 142 - 1 + 20) + (s % 142 - 1);
let mut n = u16::MAX / 2;
loop {
debug_assert_eq!(seen[scurr], 255);
*seen.get_unchecked_mut(scurr) = n;
(iprev, (icurr, scurr)) = (icurr, next(input, iprev, icurr, scurr));
n -= 1;
const DISTS: [[u16x16; 3]; 41] = {
let mut dists = [[u16::MAX / 2; 16 * 3]; 41];
let mut y = 0;
while y <= 40usize {
let dy = y.abs_diff(20);
let mut x = 0;
while x <= 40usize {
let dx = x.abs_diff(20);
if dx + dy <= 20 {
dists[y][x] = 100 + (dx + dy) as u16;
}
x += 1;
}
y += 1;
}
unsafe { transmute(dists) }
};
let mut offset = scurr - 20 - 20 * SLINE;
let mut tmp_count = u16x16::splat(0);
for line in 0..41 {
for i in 0..3 {
let b =
u16x16::from_slice(seen.get_unchecked(offset + 16 * i..offset + 16 * (i + 1)));
let m = b.simd_ge(u16x16::splat(n) + DISTS[line][i]);
tmp_count += m.to_int().cast::<u16>() & u16x16::splat(1);
}
offset += SLINE;
}
count += tmp_count.cast::<u32>();
if icurr == e {
break;
}
}
#[cfg(debug_assertions)]
for y in 0..139 {
for x in 0..139 {
if input[142 * (y + 1) + (x + 1)] == b'#' {
debug_assert_eq!(seen[20 + 20 * SLINE + SLINE * y + x], 0);
}
}
}
count.cast::<u64>().reduce_sum()
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d11p1.rs | 2024/d11p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u32 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static mut LUT: [u64; 10_000_000] = [0; 10_000_000];
#[cfg_attr(any(target_os = "linux"), link_section = ".text.startup")]
unsafe extern "C" fn __ctor() {
make_d11_lut();
}
#[used]
#[cfg_attr(target_os = "linux", link_section = ".init_array")]
#[cfg_attr(windows, link_section = ".CRT$XCU")]
static __CTOR: unsafe extern "C" fn() = __ctor;
fn make_d11_lut() {
use std::collections::HashMap;
let iters = 25;
let mut levels = vec![HashMap::new(); iters];
fn solve_rec(i: usize, j: usize, levels: &mut [HashMap<usize, usize>]) -> usize {
if i == 0 {
return 1;
}
if let Some(&res) = levels[i - 1].get(&j) {
return res;
}
let res = if j == 0 {
solve_rec(i - 1, 1, levels)
} else if j.ilog10() % 2 == 1 {
let pow10 = 10usize.pow((j.ilog10() + 1) / 2);
solve_rec(i - 1, j / pow10, levels) + solve_rec(i - 1, j % pow10, levels)
} else {
solve_rec(i - 1, j * 2024, levels)
};
levels[i - 1].insert(j, res);
res
}
for j in 0..10_000_000 {
(unsafe { &mut LUT })[j] = solve_rec(iters, j, &mut levels) as _;
}
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u32 {
type Ty = u64;
let mut tot = 0u64;
let lut = LUT.as_ptr().cast::<Ty>();
#[rustfmt::skip]
core::arch::asm!(
"2:",
"movzx {n}, byte ptr [{ptr}]",
"movzx {d}, byte ptr [{ptr} + 1]",
"sub {n}, {b0}",
"sub {d}, {b0}",
"add {ptr}, 2",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 9",
"ja 4f",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"4:",
"add {tot}, qword ptr [{lut} + {s}*{n}]",
"cmp {ptr}, {end}",
"jne 2b",
ptr = in(reg) input.as_ptr(),
end = in(reg) input.as_ptr().add(input.len()),
lut = in(reg) lut,
tot = inout(reg) tot,
n = out(reg) _,
d = out(reg) _,
s = const std::mem::size_of::<Ty>(),
b0 = const b'0' as u64
);
tot as u32
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
type Ty = u64;
let mut tot = 0;
let lut = LUT.as_ptr().cast::<Ty>();
#[rustfmt::skip]
core::arch::asm!(
"2:",
"movzx {n}, byte ptr [{ptr}]",
"movzx {d}, byte ptr [{ptr} + 1]",
"sub {n}, {b0}",
"sub {d}, {b0}",
"add {ptr}, 2",
"cmp {d}, 9",
"ja 4f",
"3:",
"lea {n}, [{n} + 4*{n}]",
"lea {n}, [{d} + 2*{n}]",
"movzx {d}, byte ptr [{ptr}]",
"sub {d}, {b0}",
"inc {ptr}",
"cmp {d}, 10",
"jb 3b",
"4:",
"add {tot}, qword ptr [{lut} + {s}*{n}]",
"cmp {ptr}, {end}",
"jne 2b",
ptr = in(reg) input.as_ptr(),
end = in(reg) input.as_ptr().add(input.len()),
lut = in(reg) lut,
tot = inout(reg) tot,
n = out(reg) _,
d = out(reg) _,
s = const std::mem::size_of::<Ty>(),
b0 = const b'0' as u64
);
tot
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d06p2.rs | 2024/d06p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
pub fn part2(input: &str) -> u32 {
unsafe { inner_part2(input) }
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u32 {
let input = input.as_bytes();
let mut start = 0;
let mut rocks_len = 0;
let mut rocks_x = const { [0; 1024] };
let mut rocks_y = const { [0; 1024] };
let mut rocksx_id = const { [[0; 16]; 130] };
let mut rocksx_len = const { [0; 130] };
let mut rocksy_id = const { [[0; 16]; 130] };
let mut rocksy_len = const { [0; 130] };
macro_rules! add_rock {
($rocks:ident, $rocks_id:ident, $rocks_len:ident, $main:ident, $cross:ident) => {{
*$rocks.get_unchecked_mut(rocks_len) = $main as u8;
let len = $rocks_len.get_unchecked_mut($main as usize);
let ids = $rocks_id.get_unchecked_mut($main as usize);
*ids.get_unchecked_mut(*len) = rocks_len as u16;
*len += 1;
}};
}
let mut offset = 0;
let mut block = u8x32::from_slice(input.get_unchecked(..32));
loop {
if let Some(pos) = block.simd_eq(u8x32::splat(b'^')).first_set() {
start = offset + pos;
}
let mut rocks_mask = block.simd_eq(u8x32::splat(b'#')).to_bitmask();
while rocks_mask != 0 {
let pos = rocks_mask.trailing_zeros();
rocks_mask &= !(1 << pos);
let pos = offset + pos as usize;
let x = pos % 131;
let y = pos / 131;
add_rock!(rocks_x, rocksx_id, rocksx_len, x, y);
add_rock!(rocks_y, rocksy_id, rocksy_len, y, x);
rocks_len += 1;
}
offset += 32;
if offset + 32 <= 130 * 131 {
block = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
} else if offset < 130 * 131 {
block = u8x32::load_or_default(input.get_unchecked((130 * 131) & !31..130 * 131));
} else {
break;
}
}
// A rock representing going out of bounds
let out_rock_idx = rocks_len as usize + 1;
// Map of moves.
// Each move is encoded as a rock idx left-shifted by 2, plus the
// position relative to the rock as the last 2 bits.
const BOT_M: usize = 0b00;
const TOP_M: usize = 0b01;
const LEFT_M: usize = 0b10;
const RIGHT_M: usize = 0b11;
let mut move_map_raw = [(out_rock_idx as u32) << 2; 1024 * 4];
let move_map = &mut move_map_raw[..(out_rock_idx + 1) << 2];
fn mov(pos: usize, mask: usize) -> usize {
(pos << 2) | mask
}
// Build next rock map for vertical-to-horizontal turns
for y in 0..130 - 1 {
let line1_ids = rocksy_id.get_unchecked(y as usize);
let line1_len = *rocksy_len.get_unchecked(y as usize);
let line2_ids = rocksy_id.get_unchecked(y as usize + 1);
let line2_len = *rocksy_len.get_unchecked(y as usize + 1);
let mut next1 = 0;
let mut next2 = 0;
let mut curr1i = out_rock_idx;
let mut next1i = *line1_ids.get_unchecked(next1) as usize;
let mut next2i = *line2_ids.get_unchecked(next2) as usize;
loop {
if next2 >= line2_len {
// Line 2 has no rocks left
while next1 < line1_len {
*move_map.get_unchecked_mut(mov(next1i, BOT_M)) =
mov(out_rock_idx, LEFT_M) as u32;
next1 += 1;
next1i = *line1_ids.get_unchecked(next1) as usize;
}
break;
}
while next1 < line1_len
&& rocks_x.get_unchecked(next1i) <= rocks_x.get_unchecked(next2i)
{
*move_map.get_unchecked_mut(mov(next1i, BOT_M)) = mov(next2i, LEFT_M) as u32;
curr1i = next1i;
next1 += 1;
next1i = *line1_ids.get_unchecked(next1) as usize;
}
if next1 >= line1_len {
// Line 1 has no rocks left
while next2 < line2_len {
*move_map.get_unchecked_mut(mov(next2i, TOP_M)) = mov(curr1i, RIGHT_M) as u32;
next2 += 1;
next2i = *line2_ids.get_unchecked(next2) as usize;
}
break;
}
while next2 < line2_len
&& rocks_x.get_unchecked(next2i) <= rocks_x.get_unchecked(next1i)
{
*move_map.get_unchecked_mut(mov(next2i, TOP_M)) = mov(curr1i, RIGHT_M) as u32;
next2 += 1;
next2i = *line2_ids.get_unchecked(next2) as usize;
}
}
}
// Build next rock map for horizontal-to-vertical turns
for x in 0..130 - 1 {
let line1_ids = rocksx_id.get_unchecked(x as usize);
let line1_len = *rocksx_len.get_unchecked(x as usize);
let line2_ids = rocksx_id.get_unchecked(x as usize + 1);
let line2_len = *rocksx_len.get_unchecked(x as usize + 1);
let mut next1 = 0;
let mut next2 = 0;
let mut curr2i = out_rock_idx;
let mut next1i = *line1_ids.get_unchecked(next1) as usize;
let mut next2i = *line2_ids.get_unchecked(next2) as usize;
loop {
if next2 >= line2_len {
// Line 2 has no rocks left
while next1 < line1_len {
*move_map.get_unchecked_mut(mov(next1i, RIGHT_M)) = mov(curr2i, BOT_M) as u32;
next1 += 1;
next1i = *line1_ids.get_unchecked(next1) as usize;
}
break;
}
while next1 < line1_len
&& rocks_y.get_unchecked(next1i) <= rocks_y.get_unchecked(next2i)
{
*move_map.get_unchecked_mut(mov(next1i, RIGHT_M)) = mov(curr2i, BOT_M) as u32;
next1 += 1;
next1i = *line1_ids.get_unchecked(next1) as usize;
}
if next1 >= line1_len {
// Line 1 has no rocks left
while next2 < line2_len {
*move_map.get_unchecked_mut(mov(next2i, LEFT_M)) =
mov(out_rock_idx, TOP_M) as u32;
next2 += 1;
next2i = *line2_ids.get_unchecked(next2) as usize;
}
break;
}
while next2 < line2_len
&& rocks_y.get_unchecked(next2i) <= rocks_y.get_unchecked(next1i)
{
*move_map.get_unchecked_mut(mov(next2i, LEFT_M)) = mov(next1i, TOP_M) as u32;
curr2i = next2i;
next2 += 1;
next2i = *line2_ids.get_unchecked(next2) as usize;
}
}
}
let mut pos = start as usize;
let mut seen = [0u64; (130 * 131 + 63) / 64];
seen[pos % 64] |= 1 << (pos % 64);
let mut next;
static mut TO_CHECK: [usize; 8000] = [0; 8000];
let mut to_check_len = 0;
'outer: loop {
macro_rules! move_and_check {
($dpos:expr, $cond:expr, $dir:ident) => {
loop {
next = pos.wrapping_add($dpos);
if $cond {
break 'outer;
}
if *input.get_unchecked(next) == b'#' {
break;
}
pos = next;
let seen_elem = seen.get_unchecked_mut(pos / 64);
let seen_mask = 1 << (pos % 64);
if *seen_elem & seen_mask == 0 {
*seen_elem |= seen_mask;
*TO_CHECK.get_unchecked_mut(to_check_len) = mov(pos, $dir);
to_check_len += 1;
}
}
};
}
move_and_check!(-131isize as usize, next >= 131 * 130, BOT_M);
move_and_check!(1, next % 131 == 130, LEFT_M);
move_and_check!(131, next >= 131 * 130, TOP_M);
move_and_check!(-1isize as usize, next % 131 == 130, RIGHT_M);
}
let sum = std::sync::atomic::AtomicU32::new(0);
let to_check = TO_CHECK.get_unchecked(..to_check_len);
let chunk_len = to_check_len.div_ceil(par::NUM_THREADS);
par::par(|idx| {
let chunk = to_check.get_unchecked(chunk_len * idx..);
let chunk = chunk.get_unchecked(..std::cmp::min(chunk.len(), chunk_len));
let mut move_map_raw = move_map_raw;
let move_map = &mut move_map_raw[..(out_rock_idx + 1) << 2];
let mut count = 0;
for &mov_pos in chunk {
let (pos, dir) = (mov_pos >> 2, mov_pos & 0b11);
let is_loop = check_loop(
&rocks_x,
&rocks_y,
&rocksx_id,
&rocksx_len,
&rocksy_id,
&rocksy_len,
rocks_len,
move_map,
pos,
dir,
);
if is_loop {
count += 1;
}
}
sum.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
return sum.into_inner();
#[inline(always)]
unsafe fn check_loop(
rocks_x: &[u8; 1024],
rocks_y: &[u8; 1024],
rocksx_id: &[[u16; 16]; 130],
rocksx_len: &[usize; 130],
rocksy_id: &[[u16; 16]; 130],
rocksy_len: &[usize; 130],
rocks_len: usize,
move_map: &mut [u32],
new_rock_pos: usize,
dir: usize,
) -> bool {
let new_rock_idx = rocks_len;
let out_rock_idx = rocks_len + 1;
let new_x = (new_rock_pos % 131) as u8;
let new_y = (new_rock_pos / 131) as u8;
// Update move_map
let (mut top_idx, mut top_old) = (usize::MAX, u32::MAX);
if new_y != 0 {
let len = *rocksy_len.get_unchecked(new_y as usize - 1);
let ids = rocksy_id
.get_unchecked(new_y as usize - 1)
.get_unchecked(..len);
let mut idx = ids
.iter()
.position(|&id| rocks_x[id as usize] > new_x)
.unwrap_or(ids.len());
if idx != 0 {
idx = idx - 1;
let mut id = *ids.get_unchecked(idx) as usize;
*move_map.get_unchecked_mut(mov(new_rock_idx, TOP_M)) = mov(id, RIGHT_M) as u32;
let prev_move = *move_map.get_unchecked(mov(id, BOT_M));
if prev_move >> 2 == out_rock_idx as u32
|| *rocks_x.get_unchecked(prev_move as usize >> 2) > new_x
{
loop {
*move_map.get_unchecked_mut(mov(id, BOT_M)) =
mov(new_rock_idx, LEFT_M) as u32;
if idx == 0 {
break;
}
id = *ids.get_unchecked(idx - 1) as usize;
if *move_map.get_unchecked(mov(id, BOT_M)) != prev_move {
break;
}
idx -= 1;
}
(top_idx, top_old) = (idx, prev_move);
}
} else {
*move_map.get_unchecked_mut(mov(new_rock_idx, TOP_M)) =
mov(out_rock_idx, RIGHT_M) as u32;
}
}
let (mut bot_idx, mut bot_old) = (usize::MAX, u32::MAX);
if new_y != 130 - 1 {
let len = *rocksy_len.get_unchecked(new_y as usize + 1);
let ids = rocksy_id
.get_unchecked(new_y as usize + 1)
.get_unchecked(..len);
let mut idx = ids
.iter()
.position(|&id| rocks_x[id as usize] > new_x)
.unwrap_or(ids.len());
if idx != ids.len() {
let mut id = *ids.get_unchecked(idx) as usize;
*move_map.get_unchecked_mut(mov(new_rock_idx, BOT_M)) = mov(id, LEFT_M) as u32;
let prev_move = *move_map.get_unchecked(mov(id, TOP_M));
if prev_move >> 2 == out_rock_idx as u32
|| *rocks_x.get_unchecked(prev_move as usize >> 2) < new_x
{
loop {
*move_map.get_unchecked_mut(mov(id, TOP_M)) =
mov(new_rock_idx, RIGHT_M) as u32;
if idx == ids.len() - 1 {
break;
}
id = *ids.get_unchecked(idx + 1) as usize;
if *move_map.get_unchecked(mov(id, TOP_M)) != prev_move {
break;
}
idx += 1;
}
(bot_idx, bot_old) = (idx, prev_move);
}
} else {
*move_map.get_unchecked_mut(mov(new_rock_idx, BOT_M)) =
mov(out_rock_idx, LEFT_M) as u32;
}
}
let (mut left_idx, mut left_old) = (usize::MAX, u32::MAX);
if new_x != 0 {
let len = *rocksx_len.get_unchecked(new_x as usize - 1);
let ids = rocksx_id
.get_unchecked(new_x as usize - 1)
.get_unchecked(..len);
let mut idx = ids
.iter()
.position(|&id| rocks_y[id as usize] > new_y)
.unwrap_or(ids.len());
if idx != ids.len() {
let mut id = *ids.get_unchecked(idx) as usize;
*move_map.get_unchecked_mut(mov(new_rock_idx, LEFT_M)) = mov(id, TOP_M) as u32;
let prev_move = *move_map.get_unchecked(mov(id, RIGHT_M));
if prev_move >> 2 == out_rock_idx as u32
|| *rocks_y.get_unchecked(prev_move as usize >> 2) < new_y
{
loop {
*move_map.get_unchecked_mut(mov(id, RIGHT_M)) =
mov(new_rock_idx, BOT_M) as u32;
if idx == ids.len() - 1 {
break;
}
id = *ids.get_unchecked(idx + 1) as usize;
if *move_map.get_unchecked(mov(id, RIGHT_M)) != prev_move {
break;
}
idx += 1;
}
(left_idx, left_old) = (idx, prev_move);
}
} else {
*move_map.get_unchecked_mut(mov(new_rock_idx, LEFT_M)) =
mov(out_rock_idx, TOP_M) as u32;
}
}
let (mut right_idx, mut right_old) = (usize::MAX, u32::MAX);
if new_x != 130 - 1 {
let len = *rocksx_len.get_unchecked(new_x as usize + 1);
let ids = rocksx_id
.get_unchecked(new_x as usize + 1)
.get_unchecked(..len);
let mut idx = ids
.iter()
.position(|&id| rocks_y[id as usize] > new_y)
.unwrap_or(ids.len());
if idx != 0 {
idx -= 1;
let mut id = *ids.get_unchecked(idx) as usize;
*move_map.get_unchecked_mut(mov(new_rock_idx, RIGHT_M)) = mov(id, BOT_M) as u32;
let prev_move = *move_map.get_unchecked(mov(id, LEFT_M));
if prev_move >> 2 == out_rock_idx as u32
|| *rocks_y.get_unchecked(prev_move as usize >> 2) > new_y
{
loop {
*move_map.get_unchecked_mut(mov(id, LEFT_M)) =
mov(new_rock_idx, TOP_M) as u32;
if idx == 0 {
break;
}
id = *ids.get_unchecked(idx - 1) as usize;
if *move_map.get_unchecked(mov(id, LEFT_M)) != prev_move {
break;
}
idx -= 1;
}
(right_idx, right_old) = (idx, prev_move);
}
} else {
*move_map.get_unchecked_mut(mov(new_rock_idx, RIGHT_M)) =
mov(out_rock_idx, BOT_M) as u32;
}
}
let mut pos = (new_rock_idx << 2) | dir;
let mut seen = [0u64; (1024 * 4) / 64];
let cycle = loop {
let seen_elem = seen.get_unchecked_mut(pos / 64);
let seen_mask = 1 << (pos % 64);
*seen_elem |= seen_mask;
pos = *move_map.get_unchecked(pos) as usize;
let seen_elem = seen.get_unchecked_mut(pos / 64);
let seen_mask = 1 << (pos % 64);
*seen_elem |= seen_mask;
pos = *move_map.get_unchecked(pos) as usize;
let seen_elem = seen.get_unchecked_mut(pos / 64);
let seen_mask = 1 << (pos % 64);
*seen_elem |= seen_mask;
pos = *move_map.get_unchecked(pos) as usize;
let seen_elem = seen.get_unchecked_mut(pos / 64);
let seen_mask = 1 << (pos % 64);
if *seen_elem & seen_mask != 0 {
break pos >> 2 != out_rock_idx;
}
*seen_elem |= seen_mask;
pos = *move_map.get_unchecked(pos) as usize;
};
// Reset move_map
if top_idx != usize::MAX {
let len = *rocksy_len.get_unchecked(new_y as usize - 1);
let ids = rocksy_id
.get_unchecked(new_y as usize - 1)
.get_unchecked(..len);
while top_idx < len
&& *move_map.get_unchecked(mov(*ids.get_unchecked(top_idx) as usize, BOT_M))
== mov(new_rock_idx, LEFT_M) as u32
{
*move_map.get_unchecked_mut(mov(*ids.get_unchecked(top_idx) as usize, BOT_M)) =
top_old;
top_idx += 1;
}
}
if bot_idx != usize::MAX {
let len = *rocksy_len.get_unchecked(new_y as usize + 1);
let ids = rocksy_id
.get_unchecked(new_y as usize + 1)
.get_unchecked(..len);
while bot_idx < len
&& *move_map.get_unchecked(mov(*ids.get_unchecked(bot_idx) as usize, TOP_M))
== mov(new_rock_idx, RIGHT_M) as u32
{
*move_map.get_unchecked_mut(mov(*ids.get_unchecked(bot_idx) as usize, TOP_M)) =
bot_old;
bot_idx = bot_idx.wrapping_sub(1);
}
}
if left_idx != usize::MAX {
let len = *rocksx_len.get_unchecked(new_x as usize - 1);
let ids = rocksx_id
.get_unchecked(new_x as usize - 1)
.get_unchecked(..len);
while left_idx < len
&& *move_map.get_unchecked(mov(*ids.get_unchecked(left_idx) as usize, RIGHT_M))
== mov(new_rock_idx, BOT_M) as u32
{
*move_map.get_unchecked_mut(mov(*ids.get_unchecked(left_idx) as usize, RIGHT_M)) =
left_old;
left_idx = left_idx.wrapping_sub(1);
}
}
if right_idx != usize::MAX {
let len = *rocksx_len.get_unchecked(new_x as usize + 1);
let ids = rocksx_id
.get_unchecked(new_x as usize + 1)
.get_unchecked(..len);
while right_idx < len
&& *move_map.get_unchecked(mov(*ids.get_unchecked(right_idx) as usize, LEFT_M))
== mov(new_rock_idx, TOP_M) as u32
{
*move_map.get_unchecked_mut(mov(*ids.get_unchecked(right_idx) as usize, LEFT_M)) =
right_old;
right_idx += 1;
}
}
cycle
}
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d08p2.rs | 2024/d08p2.rs | // Original by: bendn
#![allow(
confusable_idents,
uncommon_codepoints,
non_upper_case_globals,
internal_features,
mixed_script_confusables,
static_mut_refs,
incomplete_features
)]
#![feature(
slice_swap_unchecked,
generic_const_exprs,
iter_array_chunks,
get_many_mut,
maybe_uninit_uninit_array,
iter_collect_into,
hint_assert_unchecked,
let_chains,
anonymous_lifetime_in_impl_trait,
array_windows,
try_blocks,
slice_take,
portable_simd,
test,
slice_as_chunks,
array_chunks,
slice_split_once,
core_intrinsics
)]
mod util {
#![allow(non_snake_case, unused_macros)]
use rustc_hash::FxHashMap as HashMap;
use rustc_hash::FxHashSet as HashSet;
use std::{
cmp::Reverse,
collections::{hash_map::Entry, BinaryHeap},
fmt::{Debug, Display, Write},
hash::Hash,
mem::swap,
ops::RangeInclusive,
str::FromStr,
};
pub mod prelude {
#[allow(unused_imports)]
pub(crate) use super::{bits, dang, leek, mat, shucks, C};
pub use super::{
even, gcd, gt, l, lcm, lt, nail, pa, r, rand, reading, reading::Ext, sort, DigiCount,
Dir, FilterBy, FilterBy3, GreekTools, IntoCombinations, IntoLines, IterͶ,
NumTupleIterTools, ParseIter, Printable, Skip, TakeLine, TupleIterTools2,
TupleIterTools2R, TupleIterTools3, TupleUtils, UnifiedTupleUtils, UnsoundUtilities,
Widen, Ͷ, Α, Κ, Λ, Μ,
};
pub use itertools::izip;
pub use itertools::Itertools;
pub use rustc_hash::FxHashMap as HashMap;
pub use rustc_hash::FxHashSet as HashSet;
pub use std::{
cmp::Ordering::*,
cmp::{max, min},
collections::{hash_map::Entry, VecDeque},
fmt::{Debug, Display},
hint::black_box as boxd,
io::{self, Read, Write},
iter,
mem::{replace as rplc, swap, transmute as rint},
ops::Range,
};
}
macro_rules! C {
($obj:ident.$what:ident$($tt:tt)+) => {{
let x = &mut $obj.$what;
C!( x$($tt)+ )
}};
(&$buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked($n)
}
}};
($buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
*unsafe {
$buf.get_unchecked($n)
}
}};
(&mut $buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked_mut($n)
}
}};
($buf:ident[$a:expr] = $rbuf:ident[$b:expr]) => {
*unsafe { $buf.get_unchecked_mut($a) } = unsafe { *$rbuf.get_unchecked($b) }
};
($buf:ident[$n:expr] = $e:expr) => {
*unsafe { $buf.get_unchecked_mut($n) } = $e
};
($buf:ident[$a:expr][$b:expr]) => {
unsafe { *$buf.get_unchecked($a).get_unchecked($b) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr][$rb:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra).get_unchecked($rb) }
};
($buf:ident[$a:expr][$b:expr] = $c:expr) => {{
#[allow(unused_unsafe)]
{
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } = unsafe { $c }
}
}};
}
pub(crate) use C;
macro_rules! shucks {
() => {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
($fmt:literal $(, $args:expr)* $(,)?) => {
if cfg!(debug_assertions) {
unreachable!($fmt $(, $args)*);
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
(if $x:expr) => {
if $x {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
}
};
}
pub(crate) use shucks;
macro_rules! dang {
() => {
panic!()
};
}
pub(crate) use dang;
macro_rules! leek {
($($allocation:ident)+) => {
$(std::mem::forget($allocation);)+
};
}
pub(crate) use leek;
macro_rules! mat {
($thing:ident { $($what:pat => $b:expr,)+ }) => {
match $thing { $($what => { $b })+ _ => shucks!() }
};
}
pub(crate) use mat;
#[cfg(target_feature = "avx2")]
unsafe fn count_avx<const N: usize>(hay: &[u8; N], needle: u8) -> usize {
use std::arch::x86_64::*;
let find = _mm256_set1_epi8(needle as i8);
let mut counts = _mm256_setzero_si256();
for i in 0..(N / 32) {
counts = _mm256_sub_epi8(
counts,
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(i * 32) as *const _),
find,
),
);
}
const MASK: [u8; 64] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
counts = _mm256_sub_epi8(
counts,
_mm256_and_si256(
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(N - 32) as *const _),
find,
),
_mm256_loadu_si256(MASK.as_ptr().add(N % 32) as *const _),
),
);
let sums = _mm256_sad_epu8(counts, _mm256_setzero_si256());
(_mm256_extract_epi64(sums, 0)
+ _mm256_extract_epi64(sums, 1)
+ _mm256_extract_epi64(sums, 2)
+ _mm256_extract_epi64(sums, 3)) as usize
}
pub fn count<const N: usize>(hay: &[u8; N], what: u8) -> usize {
#[cfg(target_feature = "avx2")]
return unsafe { count_avx(hay, what) };
#[cfg(not(target_feature = "avx2"))]
hay.iter().filter(|&&x| x == what).count()
}
pub fn lcm(n: impl IntoIterator<Item = u64>) -> u64 {
let mut x = n.into_iter();
let mut lcm = x.by_ref().next().expect("cannot compute LCM of 0 numbers");
let mut gcd;
for x in x {
gcd = crate::util::gcd(x, lcm);
lcm = (lcm * x) / gcd;
}
lcm
}
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum Dir {
N = b'U',
E = b'R',
S = b'D',
W = b'L',
}
pub trait UnsoundUtilities<T> {
fn ψ(self) -> T;
}
impl<T> UnsoundUtilities<T> for Option<T> {
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_none() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
impl<T, E> UnsoundUtilities<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_err() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
pub struct LMap<K, V, F>(HashMap<K, V>, F)
where
F: Fn(K) -> Option<V>,
K: Eq + Hash + Copy;
impl<K: Eq + Hash + Copy, V, F> LMap<K, V, F>
where
F: Fn(K) -> Option<V>,
{
pub fn new(f: F) -> Self {
Self {
0: HashMap::default(),
1: f,
}
}
pub fn get(&mut self, k: K) -> Option<&mut V> {
match self.0.entry(k) {
Entry::Occupied(x) => Some(x.into_mut()),
Entry::Vacant(e) => match self.1(k) {
Some(v) => Some(e.insert(v)),
None => None,
},
}
}
}
pub fn countg<N: Debug + PartialEq + Hash + Eq + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
has: &mut HashSet<N>,
) {
if end(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if has.insert(x) {
countg(x, graph, sum, end, has);
}
})
.Θ();
}
}
// pub fn appearances(x: )
pub fn iterg<N: Debug + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
end: &mut impl Fn(N) -> bool,
finally: &mut impl FnMut(N),
) {
if end(start) {
finally(start);
} else {
graph(start).map(|x| iterg(x, graph, end, finally)).Θ();
};
}
pub fn show<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>, D: Display>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
name: impl Fn(N) -> D,
) {
println!("digraph {{");
let mut s = HashSet::default();
let mut q = BinaryHeap::new();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
println!("}}");
return;
}
if !s.insert(n) {
continue;
}
print!("\t{}", name(n));
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
print!(" -> {}", name(n));
q.push(Reverse((c + d, n)));
}
println!(";");
}
dang!();
}
pub fn dijkstra_h<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
h: impl Fn(N) -> u16,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((h(start), 0, start)));
while let Some(Reverse((_, c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((h(n) + c + d, c + d, n)));
}
}
dang!()
}
pub fn dijkstra<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((c + d, n)));
}
}
dang!()
}
impl std::ops::Add<(i64, i64)> for Dir {
type Output = (i64, i64);
fn add(self, (x, y): (i64, i64)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i32, i32)> for Dir {
type Output = (i32, i32);
fn add(self, (x, y): (i32, i32)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u16, u16)> for Dir {
type Output = (u16, u16);
fn add(self, (x, y): (u16, u16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i16, i16)> for Dir {
type Output = (i16, i16);
fn add(self, (x, y): (i16, i16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u8, u8)> for Dir {
type Output = Option<(u8, u8)>;
fn add(self, (x, y): (u8, u8)) -> Self::Output {
match self {
Dir::N => Some((x, y.checked_sub(1)?)),
Dir::E => Some((x + 1, y)),
Dir::S => Some((x, y + 1)),
Dir::W => Some((x.checked_sub(1)?, y)),
}
}
}
impl Dir {
pub fn turn_90(&mut self) {
match self {
Dir::N => *self = Dir::E,
Dir::E => *self = Dir::S,
Dir::S => *self = Dir::W,
Dir::W => *self = Dir::N,
}
}
}
pub fn pa<T: std::fmt::Debug>(a: &[T]) {
for e in a {
print!("{e:?}");
}
println!();
}
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
if a == 0 || b == 0 {
return a | b;
}
let shift = (a | b).trailing_zeros();
a >>= shift;
loop {
b >>= b.trailing_zeros();
if a > b {
swap(&mut a, &mut b);
}
b -= a;
if b == 0 {
break;
}
}
a << shift
}
pub trait Λ {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Λ for String {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
self.as_str().λ()
}
}
impl Λ for &[u8] {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).α().λ()
}
}
impl Λ for &str {
/// parse, unwrap
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
match self.parse() {
Ok(v) => v,
Err(e) => {
panic!(
"{e}: {self} should parse into {}",
std::any::type_name::<T>()
)
}
}
}
}
pub trait Κ {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Κ for &[u8] {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).unwrap().κ()
}
}
impl Κ for &str {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.split_ascii_whitespace().map(|x| x.λ())
}
}
pub trait Α<T> {
fn α(self) -> T;
}
impl<T, E: std::fmt::Display> Α<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Ok(v) => v,
Err(e) => {
panic!("unwrap failed: {e}");
}
}
}
}
impl<T> Α<T> for Option<T> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Some(v) => v,
None => panic!("nothingness!"),
}
}
}
pub trait DigiCount {
fn ͱ(self) -> u32;
}
pub const powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
// https://stackoverflow.com/a/9721570
impl DigiCount for u64 {
fn ͱ(self) -> u32 {
static powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
static mdigs: [u32; 65] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u32 {
fn ͱ(self) -> Self {
static powers: [u32; 10] = car::from_fn!(|x| 10u32.pow(x as u32));
static mdigs: [u32; 33] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u16 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
impl DigiCount for u8 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
pub trait Ͷ: DigiCount {
fn ͷ(self) -> impl Iterator<Item = u8>;
fn Ͷ(self, i: u8) -> u8;
}
macro_rules! digs {
($for:ty) => {
impl Ͷ for $for {
fn ͷ(self) -> impl Iterator<Item = u8> {
let digits = self.ͱ() as u8;
(0..digits).rev().map(move |n| self.Ͷ(n))
}
fn Ͷ(self, i: u8) -> u8 {
((self / (10 as $for).pow(i as _)) % 10) as u8
}
}
};
}
digs!(u64);
digs!(u32);
digs!(u16);
digs!(u8);
#[derive(Copy, Clone, PartialEq, PartialOrd)]
pub struct Ronge {
pub begin: u16,
pub end: u16,
}
impl Debug for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl Display for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl From<RangeInclusive<u16>> for Ronge {
fn from(value: RangeInclusive<u16>) -> Self {
Self {
begin: *value.start(),
end: *value.end(),
}
}
}
impl PartialEq<RangeInclusive<u16>> for Ronge {
fn eq(&self, other: &RangeInclusive<u16>) -> bool {
self == &Self::from(other.clone())
}
}
impl Ronge {
pub fn sane(self) -> bool {
self.end >= self.begin
}
pub fn checked_len(self) -> Option<u16> {
self.sane().then(|| self.len())
}
pub fn len(self) -> u16 {
self.end - self.begin
}
/// push up
pub fn pushu(&mut self, to: u16) {
self.begin = self.begin.max(to);
}
/// push down
pub fn pushd(&mut self, to: u16) {
self.end = self.end.min(to);
}
pub fn intersect(self, with: Self) -> Self {
Self {
begin: self.begin.max(with.begin),
end: self.end.min(with.end),
}
}
pub fn news(&self, begin: u16) -> Self {
Self {
begin,
end: self.end,
}
}
pub fn newe(&self, end: u16) -> Self {
Self {
begin: self.begin,
end,
}
}
pub fn shrink(&mut self, with: Ronge) {
self.pushu(with.begin);
self.pushd(with.end);
}
}
impl IntoIterator for Ronge {
type Item = u16;
type IntoIter = std::ops::Range<u16>;
fn into_iter(self) -> Self::IntoIter {
self.begin..self.end
}
}
pub trait Μ where
Self: Sized,
{
fn μ(self, d: char) -> (Self, Self);
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display;
fn μ1(self, d: char) -> Self {
self.μ(d).1
}
fn μ0(self, d: char) -> Self {
self.μ(d).0
}
fn between(self, a: char, b: char) -> Self {
self.μ1(a).μ0(b)
}
}
impl Μ for &[u8] {
fn μ(self, d: char) -> (Self, Self) {
let i = memchr::memchr(d as u8, self)
.unwrap_or_else(|| shucks!("{} should split at {d} fine", self.p()));
(&self[..i], &self[i + 1..])
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub fn gt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a > n
}
pub fn lt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a < n
}
impl Μ for &str {
fn μ(self, d: char) -> (Self, Self) {
self.split_once(d)
.unwrap_or_else(|| shucks!("{self} should split at {d} fine"))
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub trait IterͶ: Iterator {
fn ͷ(self) -> impl Iterator<Item = u8>;
}
impl<I: Iterator<Item = u64>> IterͶ for I {
fn ͷ(self) -> impl Iterator<Item = u8> {
self.flat_map(Ͷ::ͷ)
}
}
pub trait TupleIterTools3<T, U, V>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn m(self) -> impl Iterator<Item = U>;
fn r(self) -> impl Iterator<Item = V>;
fn lm(self) -> impl Iterator<Item = (T, U)>;
fn lr(self) -> impl Iterator<Item = (T, V)>;
fn mr(self) -> impl Iterator<Item = (U, V)>;
}
pub trait TupleIterTools2<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub trait TupleIterTools2R<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub fn l<R, T, U>(f: impl Fn(T) -> R) -> impl Fn((T, U)) -> R {
move |(x, _)| f(x)
}
pub fn r<R, T, U>(f: impl Fn(U) -> R) -> impl Fn((T, U)) -> R {
move |(_, x)| f(x)
}
pub trait FilterBy3<T, U, V>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)>;
}
impl<T: Copy, U: Copy, V: Copy, I: Iterator<Item = (T, U, V)>> FilterBy3<T, U, V> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(x, _, _)| f(*x))
}
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, x, _)| f(*x))
}
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, _, x)| f(*x))
}
}
pub trait FilterBy<T, U>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)>;
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)>;
}
impl<T: Copy, U: Copy, I: Iterator<Item = (T, U)>> FilterBy<T, U> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(x, _)| f(*x))
}
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(_, x)| f(*x))
}
}
pub trait NumTupleIterTools {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64;
}
impl<I: Iterator<Item = (u64, u64)>> NumTupleIterTools for I {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64 {
self.map(|(a, b)| a * b).sum()
}
}
impl<T, U, I: Iterator<Item = (T, U)>> TupleIterTools2<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|(_, x)| x)
}
}
impl<'a, T: Copy + 'a, U: Copy + 'a, I: Iterator<Item = &'a (T, U)>> TupleIterTools2R<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|&(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|&(_, x)| x)
}
}
impl<T, U, V, I: Iterator<Item = (T, U, V)>> TupleIterTools3<T, U, V> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _, _)| x)
}
fn m(self) -> impl Iterator<Item = U> {
self.map(|(_, x, _)| x)
}
fn r(self) -> impl Iterator<Item = V> {
self.map(|(_, _, x)| x)
}
fn lm(self) -> impl Iterator<Item = (T, U)> {
self.map(|(a, b, _)| (a, b))
}
fn lr(self) -> impl Iterator<Item = (T, V)> {
self.map(|(a, _, b)| (a, b))
}
fn mr(self) -> impl Iterator<Item = (U, V)> {
self.map(|(_, a, b)| (a, b))
}
}
pub trait GreekTools<T>: Iterator {
fn Δ(&mut self) -> T;
fn ι<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ι1<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ν<const N: usize>(&mut self, into: &mut [T; N]) -> usize;
fn Θ(&mut self);
}
pub trait ParseIter {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl<'x, I: Iterator<Item = &'x [u8]>> ParseIter for I {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.flat_map(|x| x.κ())
}
}
pub trait Ι<T, N>: Iterator {
fn ι(&mut self) -> impl Iterator<Item = (T, N)>;
fn ι1(&mut self) -> impl Iterator<Item = (T, N)>;
}
macro_rules! ι {
($t:ty) => {
impl<T, I: Iterator<Item = T>> Ι<T, $t> for I {
fn ι(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(0..)
}
fn ι1(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(1..)
}
}
};
}
ι!(i8);
ι!(u8);
ι!(u16);
ι!(u32);
ι!(u64);
ι!(usize);
pub fn nail<const N: usize, T: Copy>(x: &[T]) -> [T; N] {
unsafe { (x.as_ptr() as *const [T; N]).read() }
}
pub mod reading {
#[inline]
pub fn 八(n: u64) -> u64 {
// reinterpret as u64 ("92233721" => 92233721)
// let n = u64::from_le_bytes(s);
// combine 4 pairs of single digits:
// split pieces into odd and even
// 1_7_3_2_ (le repr)
// _2_3_2_9
// then combine
// _21_37_23_92 (le repr, each byte as 2 digits)
let n = ((n & 0x0f000f000f000f00) >> 8) + ((n & 0x000f000f000f000f) * 10);
// combine 2 pairs of 2 digits:
// split again
// _21___23__
// ___37___92
// then combine
// __14|137__36|7 (le repr, pipes separating bytes)
let n = ((n & 0x00ff000000ff0000) >> 16) + ((n & 0x000000ff000000ff) * 100);
// combine pair of 4 digits
// split again
// __14|137____ (then moved to ______14|137, as u64:3721)
// ______36|07 (as u64: 9223)
// then combine
((n & 0x0000ffff00000000) >> 32) + ((n & 0x000000000000ffff) * 10000)
}
use std::{
io::{self, Read},
ops::{Add, BitOrAssign, Shl},
};
pub trait Ext {
fn rd<const N: usize>(&mut self) -> io::Result<[u8; N]>;
fn by(&mut self) -> io::Result<u8> {
Ok(self.rd::<1>()?[0])
}
}
impl<T: Read> Ext for T {
fn rd<const N: usize>(&mut self) -> io::Result<[u8; N]> {
let mut buf = [0; N];
self.read_exact(&mut buf)?;
Ok(buf)
}
}
use crate::util::prelude::*;
pub fn κ<
T: Default
+ std::ops::Mul<T, Output = T>
+ Add<T, Output = T>
+ From<u8>
+ Copy
+ Ten
+ Debug,
>(
x: &[u8],
v: &mut [T],
) -> usize {
let mut n = 0;
let mut s = T::default();
for &b in x {
match b {
b' ' => {
C! { v[n] = s };
n += 1;
s = T::default();
}
b => {
s = s * T::ten() + T::from(b - b'0');
}
}
}
C! {v[n] = s};
n + 1
}
pub trait Ten {
fn ten() -> Self;
}
macro_rules! tenz {
($for:ty) => {
impl Ten for $for {
fn ten() -> $for {
10
}
}
};
}
tenz!(u8);
tenz!(u16);
tenz!(u32);
tenz!(u64);
tenz!(u128);
tenz!(i8);
tenz!(i16);
tenz!(i32);
tenz!(i64);
tenz!(i128);
const DIG: [u8; 256] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
pub fn hex_dig(b: u8) -> u8 {
DIG[b.nat()]
// (b & 0xF) + 9 * (b >> 6)
}
pub fn hexN<
T: From<u8> + TryFrom<usize> + Shl<T, Output = T> + BitOrAssign<T>,
const N: usize,
>(
a: [u8; N],
) -> T {
let mut c = T::from(hex_dig(a[0])) << T::try_from((N - 1) * 4).ψ();
for (&n, sh) in a[1..].iter().zip((0..N - 1).rev()) {
c |= T::from(hex_dig(n)) << T::try_from(sh * 4).ψ();
}
c
}
pub fn hex(mut d: &[u8]) -> Result<u32, ()> {
let &b = d.take_first().ok_or(())?;
let mut num = hex_dig(b) as u32;
while let Some(&b) = d.take_first() {
num = num * 16 + hex_dig(b) as u32;
}
Ok(num)
}
pub fn 迄または完了<
T: Default + std::ops::Mul<T, Output = T> + Add<T, Output = T> + From<u8> + Copy + Ten,
>(
x: &mut &[u8],
until: u8,
) -> T {
let mut n = T::default();
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | true |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d07p1.rs | 2024/d07p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(fn_align)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[inline(always)]
pub unsafe fn parse1(mut ptr: *const u8, buf: &mut [u32; 16], buf_len: &mut usize, goal: &mut u64) {
let mut acc = *ptr as u64 - b'0' as u64;
loop {
ptr = ptr.add(1);
let b = (*ptr as u64).wrapping_sub(b'0' as u64);
if b >= 10 {
break;
}
acc = 10 * acc + b;
}
*goal = acc;
ptr = ptr.add(1);
*buf_len = 0;
while *ptr != b'\n' {
ptr = ptr.add(1);
let mut acc = *ptr as u32 - b'0' as u32;
loop {
ptr = ptr.add(1);
let b = (*ptr as u32).wrapping_sub(b'0' as u32);
if b >= 10 {
break;
}
acc = 10 * acc + b;
}
*buf.get_unchecked_mut(*buf_len) = acc;
*buf_len += 1;
}
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 850];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let chunk_len = lines.len().div_ceil(par::NUM_THREADS);
par::par(|idx| {
let chunk = lines.get_unchecked(chunk_len * idx..);
let chunk = chunk.get_unchecked(..std::cmp::min(chunk.len(), chunk_len));
let mut tot = 0;
let mut max = [0; 16];
let mut buf = [0; 16];
let mut buf_len = 0;
let mut goal = 0;
let mut stack = [(0, 0); 32];
let mut stack_len;
for &i in chunk {
parse1(input.as_ptr().add(i), &mut buf, &mut buf_len, &mut goal);
let (add, mul) = (buf[0] + buf[1], buf[0] * buf[1]);
max[0] = buf[0] as u64;
max[1] = std::cmp::max(add, mul) as u64;
let min2 = std::cmp::min(add, mul) as u64;
for i in 2..buf_len {
*max.get_unchecked_mut(i) = std::cmp::max(
*max.get_unchecked(i - 1) + 1,
*max.get_unchecked(i - 1) * *buf.get_unchecked(i) as u64,
);
}
stack[0] = (goal, buf_len - 1);
stack_len = 1;
'outer: while stack_len != 0 {
let (mut local_goal, mut i) = *stack.get_unchecked(stack_len - 1);
stack_len -= 1;
loop {
if local_goal >= *max.get_unchecked(i) {
if local_goal == *max.get_unchecked(i) {
tot += goal;
break 'outer;
}
continue 'outer;
}
if i == 1 {
if local_goal == min2 {
tot += goal;
break 'outer;
}
continue 'outer;
}
let n = *buf.get_unchecked(i) as u64;
std::hint::assert_unchecked(n != 0);
if local_goal.wrapping_sub(n) <= *max.get_unchecked(i - 1) {
*stack.get_unchecked_mut(stack_len) = (local_goal - n, i - 1);
stack_len += 1;
}
if local_goal % n == 0 {
local_goal /= n;
i -= 1;
} else {
break;
}
}
}
}
sum.fetch_add(tot, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
#[inline(always)]
pub unsafe fn parse2(
input: &mut std::slice::Iter<u8>,
buf: &mut [(u32, u32); 16],
buf_len: &mut usize,
goal: &mut u64,
) -> bool {
if input.as_slice().len() > 0 {
let mut acc = 0;
while *input.as_slice().get_unchecked(0) != b':' {
acc = 10 * acc + (input.as_slice().get_unchecked(0) - b'0') as u64;
*input = input.as_slice().get_unchecked(1..).iter();
}
*input = input.as_slice().get_unchecked(1..).iter();
*goal = acc;
} else {
return false;
}
*buf_len = 0;
while *input.as_slice().get_unchecked(0) == b' ' {
*input = input.as_slice().get_unchecked(1..).iter();
let mut n = input.as_slice().get_unchecked(0).wrapping_sub(b'0') as u32;
let mut pow10idx = 0;
*input = input.as_slice().get_unchecked(1..).iter();
let d = input.as_slice().get_unchecked(0).wrapping_sub(b'0');
if d < 10 {
n = 10 * n + d as u32;
pow10idx = 1;
*input = input.as_slice().get_unchecked(1..).iter();
let d = input.as_slice().get_unchecked(0).wrapping_sub(b'0');
if d < 10 {
n = 10 * n + d as u32;
pow10idx = 2;
*input = input.as_slice().get_unchecked(1..).iter();
}
}
*buf.get_unchecked_mut(*buf_len) = (n, pow10idx);
*buf_len += 1;
}
*input = input.as_slice().get_unchecked(1..).iter();
true
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let mut tot = 0;
let mut max = [0; 16];
let mut buf = [(0, 0); 16];
let mut buf_len = 0;
let mut goal = 0;
let mut stack = [(0, 0); 32];
let mut stack_len;
let mut input = input.as_bytes().iter();
loop {
if !parse2(&mut input, &mut buf, &mut buf_len, &mut goal) {
break;
}
max[0] = buf[0].0 as u64;
for i in 1..buf_len {
static LUT: [u64; 3] = [10, 100, 1000];
let (n, l) = *buf.get_unchecked(i);
let pow10 = *LUT.get_unchecked(l as usize);
*max.get_unchecked_mut(i) = *max.get_unchecked(i - 1) * pow10 + n as u64;
}
let a2 = (buf[0].0 + buf[1].0) as u64;
let m2 = (buf[0].0 * buf[1].0) as u64;
stack[0] = (goal, buf_len - 1);
stack_len = 1;
'outer: while stack_len > 0 {
let (mut local_goal, mut i) = *stack.get_unchecked(stack_len - 1);
stack_len -= 1;
loop {
if local_goal >= *max.get_unchecked(i) {
if local_goal == *max.get_unchecked(i) {
tot += goal;
break 'outer;
}
continue 'outer;
}
if i == 1 {
if local_goal == a2 || local_goal == m2 {
tot += goal;
break 'outer;
}
continue 'outer;
}
let (n, l) = *buf.get_unchecked(i);
let (n, l) = (n as u64, l as usize);
std::hint::assert_unchecked(n != 0);
if local_goal.wrapping_sub(n) <= *max.get_unchecked(i - 1) {
*stack.get_unchecked_mut(stack_len) = (local_goal - n, i - 1);
stack_len += 1;
}
use fastdiv::PrecomputedDivU64;
static LUT: [PrecomputedDivU64; 3] = [
PrecomputedDivU64::new(10),
PrecomputedDivU64::new(100),
PrecomputedDivU64::new(1000),
];
let pow10 = *LUT.get_unchecked(l);
if local_goal > n && PrecomputedDivU64::is_multiple_of(local_goal - n, pow10) {
*stack.get_unchecked_mut(stack_len) =
(PrecomputedDivU64::fast_div(local_goal - n, pow10), i - 1);
stack_len += 1;
}
if local_goal % n == 0 {
local_goal /= n;
i -= 1;
} else {
break;
}
}
}
}
tot
}
mod fastdiv {
#[inline]
const fn mul128_u64(lowbits: u128, d: u64) -> u64 {
let mut bottom_half = (lowbits & 0xFFFFFFFFFFFFFFFF) * d as u128;
bottom_half >>= 64;
let top_half = (lowbits >> 64) * d as u128;
let both_halves = bottom_half + top_half;
(both_halves >> 64) as u64
}
#[inline]
const fn divide_128_max_by_64(divisor: u16) -> u128 {
let divisor = divisor as u64;
let quotient_hi = core::u64::MAX / divisor as u64;
let remainder_hi = core::u64::MAX - quotient_hi * divisor;
let quotient_lo = {
let numerator_mid = (remainder_hi << 32) | core::u32::MAX as u64;
let quotient_mid = numerator_mid / divisor;
let remainder_mid = numerator_mid - quotient_mid * divisor;
let numerator_lo = (remainder_mid << 32) | core::u32::MAX as u64;
let quotient_lo = numerator_lo / divisor;
(quotient_mid << 32) | quotient_lo
};
((quotient_hi as u128) << 64) | (quotient_lo as u128)
}
#[inline]
const fn compute_m_u64(d: u64) -> u128 {
divide_128_max_by_64(d as u16) + 1
}
// for d > 1
#[inline]
const fn fastdiv_u64(a: u64, m: u128) -> u64 {
mul128_u64(m, a)
}
#[inline]
const fn is_divisible_u64(n: u64, m: u128) -> bool {
(n as u128).wrapping_mul(m) <= m - 1
}
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct PrecomputedDivU64(u128);
impl PrecomputedDivU64 {
#[inline]
pub const fn new(n: u64) -> Self {
Self(compute_m_u64(n))
}
#[inline]
pub fn fast_div(n: u64, precomputed: Self) -> u64 {
fastdiv_u64(n, precomputed.0)
}
#[inline]
pub fn is_multiple_of(n: u64, precomputed: Self) -> bool {
is_divisible_u64(n, precomputed.0)
}
}
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d09p1.rs | 2024/d09p1.rs | // Original by: alion02
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m256i, _mm256_madd_epi16, _mm256_maddubs_epi16, _mm256_movemask_epi8,
_mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16, _mm_maddubs_epi16,
_mm_movemask_epi8, _mm_packus_epi32, _mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
fmt::Display,
mem::{offset_of, transmute, MaybeUninit},
simd::prelude::*,
};
unsafe fn inner1(s: &[u8]) -> usize {
let mut checksum = 0;
asm!(
"20:",
"movzx {len:e}, byte ptr[{s} + {left} * 2]",
"sub {len:e}, 48",
"lea {scratch:e}, [{len} + {disk_pos} * 2 - 1]",
"imul {scratch}, {left}",
"imul {scratch}, {len}",
"add {checksum}, {scratch}",
"add {disk_pos:e}, {len:e}",
"movzx {rem_dst:e}, byte ptr[{s} + {left} * 2 + 1]",
"inc {left:e}",
"sub {rem_dst:e}, 48",
"jz 20b",
"cmp {left:e}, {right:e}",
"je 50f",
"22:",
"dec {right:e}",
"movzx {rem_src:e}, byte ptr[{s} + {right} * 2]",
"sub {rem_src:e}, 48",
"cmp {rem_dst}, {rem_src}",
"ja 40f",
"21:",
"lea {scratch:e}, [{rem_dst} + {disk_pos} * 2 - 1]",
"jb 30f",
"imul {scratch}, {right}",
"imul {scratch}, {rem_dst}",
"add {checksum}, {scratch}",
"add {disk_pos:e}, {rem_dst:e}",
"cmp {left:e}, {right:e}",
"jne 20b",
"jmp 50f",
"30:",
"imul {scratch}, {right}",
"imul {scratch}, {rem_dst}",
"add {checksum}, {scratch}",
"add {disk_pos:e}, {rem_dst:e}",
"sub {rem_src:e}, {rem_dst:e}",
"31:",
"cmp {left:e}, {right:e}",
"je 60f",
"movzx {len:e}, byte ptr[{s} + {left} * 2]",
"sub {len:e}, 48",
"lea {scratch:e}, [{len} + {disk_pos} * 2 - 1]",
"imul {scratch}, {left}",
"imul {scratch}, {len}",
"add {checksum}, {scratch}",
"add {disk_pos:e}, {len:e}",
"movzx {rem_dst:e}, byte ptr[{s} + {left} * 2 + 1]",
"inc {left:e}",
"sub {rem_dst:e}, 48",
"jz 31b",
"cmp {rem_dst}, {rem_src}",
"jbe 21b",
"40:",
"lea {scratch:e}, [{rem_src} + {disk_pos} * 2 - 1]",
"imul {scratch}, {right}",
"imul {scratch}, {rem_src}",
"add {checksum}, {scratch}",
"add {disk_pos:e}, {rem_src:e}",
"sub {rem_dst:e}, {rem_src:e}",
"cmp {left:e}, {right:e}",
"jne 22b",
"jmp 50f",
"60:",
"lea {scratch:e}, [{rem_src} + {disk_pos} * 2 - 1]",
"imul {scratch}, {right}",
"imul {scratch}, {rem_src}",
"add {checksum}, {scratch}",
"50:",
"shr {checksum}",
checksum = inout(reg) checksum,
s = in(reg) s.as_ptr(),
left = inout(reg) 0usize => _,
right = inout(reg) s.len() / 2 => _,
disk_pos = inout(reg) 0usize => _,
rem_dst = out(reg) _,
rem_src = out(reg) _,
scratch = out(reg) _,
len = out(reg) _,
options(nostack, readonly),
);
checksum
}
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d21p1.rs | 2024/d21p1.rs | // Original by: bendn
#![allow(warnings)]
#![allow(
confusable_idents,
uncommon_codepoints,
non_upper_case_globals,
internal_features,
mixed_script_confusables,
static_mut_refs,
incomplete_features
)]
#![feature(
iter_repeat_n,
slice_swap_unchecked,
generic_const_exprs,
iter_array_chunks,
if_let_guard,
get_many_mut,
maybe_uninit_uninit_array,
once_cell_get_mut,
iter_collect_into,
hint_assert_unchecked,
let_chains,
anonymous_lifetime_in_impl_trait,
array_windows,
maybe_uninit_array_assume_init,
vec_into_raw_parts,
try_blocks,
slice_take,
portable_simd,
test,
slice_as_chunks,
array_chunks,
slice_split_once,
core_intrinsics
)]
use std::ops::Neg;
mod util {
#![allow(non_snake_case, unused_macros)]
use rustc_hash::FxHashMap as HashMap;
use rustc_hash::FxHashSet as HashSet;
use std::{
cmp::Reverse,
collections::{hash_map::Entry, BinaryHeap},
fmt::{Debug, Display, Write},
hash::Hash,
mem::swap,
ops::RangeInclusive,
str::FromStr,
};
pub mod prelude {
#[allow(unused_imports)]
pub(crate) use super::{bits, dang, leek, mat, shucks, C};
pub use super::{
even, gcd, gt, l, lcm, lt, nail, pa, r, rand, reading, reading::Ext, sort, DigiCount,
Dir, FilterBy, FilterBy3, GreekTools, IntoCombinations, IntoLines, IterͶ,
NumTupleIterTools, ParseIter, Printable, Skip, TakeLine, TupleIterTools2,
TupleIterTools2R, TupleIterTools3, TupleUtils, UnifiedTupleUtils, UnsoundUtilities,
Widen, Ͷ, Α, Κ, Λ, Μ,
};
pub use itertools::izip;
pub use itertools::Itertools;
pub use rustc_hash::FxHashMap as HashMap;
pub use rustc_hash::FxHashSet as HashSet;
pub use std::{
cmp::Ordering::*,
cmp::{max, min},
collections::{hash_map::Entry, VecDeque},
fmt::{Debug, Display},
hint::black_box as boxd,
io::{self, Read, Write},
iter,
mem::{replace as rplc, swap, transmute as rint},
ops::Range,
};
}
macro_rules! C {
($obj:ident.$what:ident$($tt:tt)+) => {{
let x = &mut $obj.$what;
C!( x$($tt)+ )
}};
(&$buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked($n)
}
}};
($buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
*unsafe {
$buf.get_unchecked($n)
}
}};
(&mut $buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked_mut($n)
}
}};
($buf:ident[$a:expr] = $rbuf:ident[$b:expr]) => {
*unsafe { $buf.get_unchecked_mut($a) } = unsafe { *$rbuf.get_unchecked($b) }
};
($buf:ident[$n:expr] = $e:expr) => {
*unsafe { $buf.get_unchecked_mut($n) } = $e
};
($buf:ident[$a:expr][$b:expr]) => {
unsafe { *$buf.get_unchecked($a).get_unchecked($b) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr][$rb:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra).get_unchecked($rb) }
};
($buf:ident[$a:expr][$b:expr] = $c:expr) => {{
#[allow(unused_unsafe)]
{
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } = unsafe { $c }
}
}};
}
pub(crate) use C;
macro_rules! shucks {
() => {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
($fmt:literal $(, $args:expr)* $(,)?) => {
if cfg!(debug_assertions) {
unreachable!($fmt $(, $args)*);
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
(if $x:expr) => {
if $x {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
}
};
}
pub(crate) use shucks;
macro_rules! dang {
() => {
panic!()
};
}
pub(crate) use dang;
macro_rules! leek {
($($allocation:ident)+) => {
$(std::mem::forget($allocation);)+
};
}
pub(crate) use leek;
macro_rules! mat {
($thing:ident { $($what:pat => $b:expr,)+ }) => {
match $thing { $($what => { $b })+ _ => shucks!() }
};
}
pub(crate) use mat;
#[cfg(target_feature = "avx2")]
unsafe fn count_avx<const N: usize>(hay: &[u8; N], needle: u8) -> usize {
use std::arch::x86_64::*;
let find = _mm256_set1_epi8(needle as i8);
let mut counts = _mm256_setzero_si256();
for i in 0..(N / 32) {
counts = _mm256_sub_epi8(
counts,
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(i * 32) as *const _),
find,
),
);
}
const MASK: [u8; 64] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
counts = _mm256_sub_epi8(
counts,
_mm256_and_si256(
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(N - 32) as *const _),
find,
),
_mm256_loadu_si256(MASK.as_ptr().add(N % 32) as *const _),
),
);
let sums = _mm256_sad_epu8(counts, _mm256_setzero_si256());
(_mm256_extract_epi64(sums, 0)
+ _mm256_extract_epi64(sums, 1)
+ _mm256_extract_epi64(sums, 2)
+ _mm256_extract_epi64(sums, 3)) as usize
}
pub fn count<const N: usize>(hay: &[u8; N], what: u8) -> usize {
#[cfg(target_feature = "avx2")]
return unsafe { count_avx(hay, what) };
#[cfg(not(target_feature = "avx2"))]
hay.iter().filter(|&&x| x == what).count()
}
pub fn lcm(n: impl IntoIterator<Item = u64>) -> u64 {
let mut x = n.into_iter();
let mut lcm = x.by_ref().next().expect("cannot compute LCM of 0 numbers");
let mut gcd;
for x in x {
gcd = crate::util::gcd(x, lcm);
lcm = (lcm * x) / gcd;
}
lcm
}
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum Dir {
N = b'U',
E = b'R',
S = b'D',
W = b'L',
}
pub struct UnionFind {
p: Vec<usize>,
s: Vec<usize>,
}
impl UnionFind {
pub fn new(size: usize) -> Self {
Self {
s: vec![1; size],
p: (0..size).collect(),
}
}
fn reset(&mut self) {
self.s.fill(1);
self.p
.iter_mut()
.enumerate()
.for_each(|(idx, val)| *val = idx);
}
pub fn find(&mut self, key: usize) -> usize {
if self.p[key] == key {
return key;
}
let parent = self.find(self.p[key]);
self.p[key] = parent;
parent
}
pub fn union(&mut self, a: usize, b: usize) -> bool {
let α = self.find(a);
let β = self.find(b);
if α == β {
return false;
}
let a = self.s[α];
let b = self.s[β];
if a >= b {
self.s[α] += b;
self.p[β] = α;
} else {
self.s[β] += a;
self.p[α] = β;
}
true
}
fn group_size(&self, group: usize) -> usize {
self.s[group]
}
}
pub trait UnsoundUtilities<T> {
fn ψ(self) -> T;
}
impl<T> UnsoundUtilities<T> for Option<T> {
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_none() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
impl<T, E> UnsoundUtilities<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_err() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
pub struct LMap<K, V>(HashMap<K, V>, fn(K) -> V)
where
K: Eq + Hash + Copy;
impl<K: Ord + Eq + Debug + Hash + Copy, V: Copy + Debug> LMap<K, V> {
pub fn new(f: fn(K) -> V) -> Self {
Self {
0: HashMap::default(),
1: f,
}
}
pub fn with_cap(f: fn(K) -> V, cap: usize) -> Self {
Self {
0: HashMap::with_capacity_and_hasher(cap, rustc_hash::FxBuildHasher::default()),
1: f,
}
}
pub fn get(&mut self, k: K) -> V {
if let Some(x) = self.0.get(&k) {
return *x;
}
// let mut ks = self.0.keys().collect::<Vec<_>>();
// ks.sort();
// println!("{ks:?}");
let elm = self.1(k);
self.0.insert(k, elm);
elm
}
}
macro_rules! memoize {
(|$pat:pat_param in $in:ty| -> $out:ty $body:block; $arg:expr) => {{
static mut MEMOIZER: std::sync::OnceLock<crate::util::LMap<$in, $out>> =
std::sync::OnceLock::new();
unsafe {
MEMOIZER.get_mut_or_init(|| crate::util::LMap::new(|$pat: $in| -> $out { $body }))
}
.get($arg)
}};
(|$pat:pat_param in $in:ty| -> $out:ty $body:block; $arg:expr; with cap $cap:literal) => {{
static mut MEMOIZER: std::sync::OnceLock<crate::util::LMap<$in, $out>> =
std::sync::OnceLock::new();
unsafe {
MEMOIZER.get_mut_or_init(|| {
crate::util::LMap::with_cap(|$pat: $in| -> $out { $body }, $cap)
})
}
.get($arg)
}};
}
pub(crate) use memoize;
pub fn countg_with_check<N: Debug + PartialEq + Hash + Eq + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
ok: &mut impl Fn(N, N) -> bool,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
) {
if end(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if ok(start, x) {
// println!("\"{start:?}\" -> \"{x:?}\"");
countg_with_check(x, graph, ok, sum, end);
}
})
.Θ();
}
}
pub fn countg_uniq_with_check<
N: Debug + PartialEq + Hash + Eq + Copy,
I: Iterator<Item = N>,
>(
start: N,
graph: &mut impl Fn(N) -> I,
ok: &mut impl Fn(N, N) -> bool,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
has: &mut HashSet<N>,
) {
if end(start) && has.insert(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if ok(start, x) {
countg_uniq_with_check(x, graph, ok, sum, end, has);
}
})
.Θ();
}
}
pub fn countg<N: Debug + PartialEq + Hash + Eq + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
has: &mut HashSet<N>,
) {
if end(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if has.insert(x) {
countg(x, graph, sum, end, has);
}
})
.Θ();
}
}
// pub fn appearances(x: )
pub fn iterg<N: Debug + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
end: &mut impl Fn(N) -> bool,
finally: &mut impl FnMut(N),
) {
if end(start) {
finally(start);
} else {
graph(start).map(|x| iterg(x, graph, end, finally)).Θ();
};
}
pub fn show<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>, D: Display>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
name: impl Fn(N) -> D,
) {
println!("digraph {{");
let mut s = HashSet::default();
let mut q = BinaryHeap::new();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
println!("}}");
return;
}
if !s.insert(n) {
continue;
}
print!("\t{}", name(n));
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
print!(" -> {}", name(n));
q.push(Reverse((c + d, n)));
}
println!(";");
}
dang!();
}
pub fn dijkstra_h<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
h: impl Fn(N) -> u16,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((h(start), 0, start)));
while let Some(Reverse((_, c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((h(n) + c + d, c + d, n)));
}
}
dang!()
}
pub fn dijkstra<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((c + d, n)));
}
}
dang!()
}
impl std::ops::Add<(i64, i64)> for Dir {
type Output = (i64, i64);
fn add(self, (x, y): (i64, i64)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(usize, usize)> for Dir {
type Output = (usize, usize);
fn add(self, (x, y): (usize, usize)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i32, i32)> for Dir {
type Output = (i32, i32);
fn add(self, (x, y): (i32, i32)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u16, u16)> for Dir {
type Output = (u16, u16);
fn add(self, (x, y): (u16, u16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i16, i16)> for Dir {
type Output = (i16, i16);
fn add(self, (x, y): (i16, i16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u8, u8)> for Dir {
type Output = Option<(u8, u8)>;
fn add(self, (x, y): (u8, u8)) -> Self::Output {
match self {
Dir::N => Some((x, y.checked_sub(1)?)),
Dir::E => Some((x + 1, y)),
Dir::S => Some((x, y + 1)),
Dir::W => Some((x.checked_sub(1)?, y)),
}
}
}
impl Dir {
pub fn turn_90(self) -> Self {
match self {
Dir::N => Dir::E,
Dir::E => Dir::S,
Dir::S => Dir::W,
Dir::W => Dir::N,
}
}
pub fn turn_90ccw(self) -> Self {
match self {
Dir::N => Dir::W,
Dir::E => Dir::N,
Dir::S => Dir::E,
Dir::W => Dir::S,
}
}
}
pub fn pa<T: std::fmt::Debug>(a: &[T]) {
for e in a {
print!("{e:?}");
}
println!();
}
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
if a == 0 || b == 0 {
return a | b;
}
let shift = (a | b).trailing_zeros();
a >>= shift;
loop {
b >>= b.trailing_zeros();
if a > b {
swap(&mut a, &mut b);
}
b -= a;
if b == 0 {
break;
}
}
a << shift
}
pub trait Λ {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Λ for String {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
self.as_str().λ()
}
}
impl Λ for &[u8] {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).α().λ()
}
}
impl Λ for &str {
/// parse, unwrap
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
match self.parse() {
Ok(v) => v,
Err(e) => {
panic!(
"{e}: {self} should parse into {}",
std::any::type_name::<T>()
)
}
}
}
}
pub trait Κ {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Κ for &[u8] {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).unwrap().κ()
}
}
impl Κ for &str {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.split_ascii_whitespace().map(|x| x.λ())
}
}
pub trait Α<T> {
fn α(self) -> T;
}
impl<T, E: std::fmt::Display> Α<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Ok(v) => v,
Err(e) => {
panic!("unwrap failed: {e}");
}
}
}
}
impl<T> Α<T> for Option<T> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Some(v) => v,
None => panic!("nothingness!"),
}
}
}
pub trait DigiCount {
fn ͱ(self) -> u32;
}
pub const powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
// https://stackoverflow.com/a/9721570
impl DigiCount for u64 {
fn ͱ(self) -> u32 {
static powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
static mdigs: [u32; 65] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u32 {
fn ͱ(self) -> Self {
static powers: [u32; 10] = car::from_fn!(|x| 10u32.pow(x as u32));
static mdigs: [u32; 33] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u16 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
impl DigiCount for u8 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
impl DigiCount for u128 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
pub trait Ͷ: DigiCount {
fn ͷ(self) -> impl Iterator<Item = u8>;
fn Ͷ(self, i: u8) -> u8;
}
macro_rules! digs {
($for:ty) => {
impl Ͷ for $for {
fn ͷ(self) -> impl Iterator<Item = u8> {
let digits = self.ͱ() as u8;
(0..digits).rev().map(move |n| self.Ͷ(n))
}
fn Ͷ(self, i: u8) -> u8 {
((self / (10 as $for).pow(i as _)) % 10) as u8
}
}
};
}
digs!(u128);
digs!(u64);
digs!(u32);
digs!(u16);
digs!(u8);
#[derive(Copy, Clone, PartialEq, PartialOrd)]
pub struct Ronge {
pub begin: u16,
pub end: u16,
}
impl Debug for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl Display for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl From<RangeInclusive<u16>> for Ronge {
fn from(value: RangeInclusive<u16>) -> Self {
Self {
begin: *value.start(),
end: *value.end(),
}
}
}
impl PartialEq<RangeInclusive<u16>> for Ronge {
fn eq(&self, other: &RangeInclusive<u16>) -> bool {
self == &Self::from(other.clone())
}
}
impl Ronge {
pub fn sane(self) -> bool {
self.end >= self.begin
}
pub fn checked_len(self) -> Option<u16> {
self.sane().then(|| self.len())
}
pub fn len(self) -> u16 {
self.end - self.begin
}
/// push up
pub fn pushu(&mut self, to: u16) {
self.begin = self.begin.max(to);
}
/// push down
pub fn pushd(&mut self, to: u16) {
self.end = self.end.min(to);
}
pub fn intersect(self, with: Self) -> Self {
Self {
begin: self.begin.max(with.begin),
end: self.end.min(with.end),
}
}
pub fn news(&self, begin: u16) -> Self {
Self {
begin,
end: self.end,
}
}
pub fn newe(&self, end: u16) -> Self {
Self {
begin: self.begin,
end,
}
}
pub fn shrink(&mut self, with: Ronge) {
self.pushu(with.begin);
self.pushd(with.end);
}
}
impl IntoIterator for Ronge {
type Item = u16;
type IntoIter = std::ops::Range<u16>;
fn into_iter(self) -> Self::IntoIter {
self.begin..self.end
}
}
pub trait Μ where
Self: Sized,
{
fn μ(self, d: char) -> (Self, Self);
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display;
fn μ1(self, d: char) -> Self {
self.μ(d).1
}
fn μ0(self, d: char) -> Self {
self.μ(d).0
}
fn between(self, a: char, b: char) -> Self {
self.μ1(a).μ0(b)
}
}
impl Μ for &[u8] {
fn μ(self, d: char) -> (Self, Self) {
let i = memchr::memchr(d as u8, self)
.unwrap_or_else(|| shucks!("{} should split at {d} fine", self.p()));
(&self[..i], &self[i + 1..])
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub fn gt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a > n
}
pub fn lt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a < n
}
impl Μ for &str {
fn μ(self, d: char) -> (Self, Self) {
self.split_once(d)
.unwrap_or_else(|| shucks!("{self} should split at {d} fine"))
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub trait IterͶ: Iterator {
fn ͷ(self) -> impl Iterator<Item = u8>;
}
impl<I: Iterator<Item = u64>> IterͶ for I {
fn ͷ(self) -> impl Iterator<Item = u8> {
self.flat_map(Ͷ::ͷ)
}
}
pub trait TupleIterTools3<T, U, V>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn m(self) -> impl Iterator<Item = U>;
fn r(self) -> impl Iterator<Item = V>;
fn lm(self) -> impl Iterator<Item = (T, U)>;
fn lr(self) -> impl Iterator<Item = (T, V)>;
fn mr(self) -> impl Iterator<Item = (U, V)>;
}
pub trait TupleIterTools2<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub trait TupleIterTools2R<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub fn l<R, T, U>(f: impl Fn(T) -> R) -> impl Fn((T, U)) -> R {
move |(x, _)| f(x)
}
pub fn r<R, T, U>(f: impl Fn(U) -> R) -> impl Fn((T, U)) -> R {
move |(_, x)| f(x)
}
pub trait FilterBy3<T, U, V>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)>;
}
impl<T: Copy, U: Copy, V: Copy, I: Iterator<Item = (T, U, V)>> FilterBy3<T, U, V> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(x, _, _)| f(*x))
}
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, x, _)| f(*x))
}
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, _, x)| f(*x))
}
}
pub trait FilterBy<T, U>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)>;
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)>;
}
impl<T: Copy, U: Copy, I: Iterator<Item = (T, U)>> FilterBy<T, U> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(x, _)| f(*x))
}
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(_, x)| f(*x))
}
}
pub trait NumTupleIterTools {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64;
}
impl<I: Iterator<Item = (u64, u64)>> NumTupleIterTools for I {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64 {
self.map(|(a, b)| a * b).sum()
}
}
impl<T, U, I: Iterator<Item = (T, U)>> TupleIterTools2<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|(_, x)| x)
}
}
impl<'a, T: Copy + 'a, U: Copy + 'a, I: Iterator<Item = &'a (T, U)>> TupleIterTools2R<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|&(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|&(_, x)| x)
}
}
impl<T, U, V, I: Iterator<Item = (T, U, V)>> TupleIterTools3<T, U, V> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _, _)| x)
}
fn m(self) -> impl Iterator<Item = U> {
self.map(|(_, x, _)| x)
}
fn r(self) -> impl Iterator<Item = V> {
self.map(|(_, _, x)| x)
}
fn lm(self) -> impl Iterator<Item = (T, U)> {
self.map(|(a, b, _)| (a, b))
}
fn lr(self) -> impl Iterator<Item = (T, V)> {
self.map(|(a, _, b)| (a, b))
}
fn mr(self) -> impl Iterator<Item = (U, V)> {
self.map(|(_, a, b)| (a, b))
}
}
pub trait GreekTools<T>: Iterator {
fn Δ(&mut self) -> T;
fn ι<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ι1<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ν<const N: usize>(&mut self, into: &mut [T; N]) -> usize;
fn Θ(&mut self);
}
pub trait ParseIter {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl<'x, I: Iterator<Item = &'x [u8]>> ParseIter for I {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.flat_map(|x| x.κ())
}
}
pub trait Ι<T, N>: Iterator {
fn ι(&mut self) -> impl Iterator<Item = (T, N)>;
fn ι1(&mut self) -> impl Iterator<Item = (T, N)>;
}
macro_rules! ι {
($t:ty) => {
impl<T, I: Iterator<Item = T>> Ι<T, $t> for I {
fn ι(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(0..)
}
fn ι1(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(1..)
}
}
};
}
ι!(i8);
ι!(u8);
ι!(u16);
ι!(u32);
ι!(u64);
ι!(usize);
pub fn nail<const N: usize, T: Copy>(x: &[T]) -> [T; N] {
unsafe { (x.as_ptr() as *const [T; N]).read() }
}
pub mod reading {
#[inline]
pub fn 八(n: u64) -> u64 {
// reinterpret as u64 ("92233721" => 92233721)
// let n = u64::from_le_bytes(s);
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | true |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d02p1.rs | 2024/d02p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(fn_align)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static LT_VALID: [bool; 256] = {
let mut out = [false; 256];
out[1] = true;
out[2] = true;
out[3] = true;
out
};
#[inline(always)]
fn lt_valid(diff: i8) -> bool {
LT_VALID[diff as u8 as usize]
}
static GT_VALID: [bool; 256] = {
let mut out = [false; 256];
out[253] = true;
out[254] = true;
out[255] = true;
out
};
#[inline(always)]
fn gt_valid(diff: i8) -> bool {
GT_VALID[diff as u8 as usize]
}
pub unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 1000];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let mut lens = [1000 / par1::NUM_THREADS; par1::NUM_THREADS];
for i in 0..1000 % par1::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par1::NUM_THREADS + 1];
for i in 0..par1::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let acc = std::sync::atomic::AtomicU64::new(0);
par1::par(|idx| {
unsafe fn read(input: &mut std::slice::Iter<u8>) -> (i8, u8) {
let d1 = *input.next().unwrap_unchecked();
let mut d2 = *input.next().unwrap_unchecked();
let mut n = d1 - b'0';
if d2 >= b'0' {
n = 10 * n + (d2 - b'0');
d2 = *input.next().unwrap_unchecked();
}
(n as i8, d2)
}
let mut count = 0;
for i in poss[idx]..poss[idx + 1] {
let l = *lines.get_unchecked(i);
let mut input = input.get_unchecked(l..).iter();
let (n1, _) = read(&mut input);
let (n2, c2) = read(&mut input);
let diff = n2 - n1;
static VALID: [bool; 256] = {
let mut out = [false; 256];
out[253] = true;
out[254] = true;
out[255] = true;
out[1] = true;
out[2] = true;
out[3] = true;
out
};
let mut prev = n2;
let mut ctrl = c2;
let mut valid = VALID[diff as u8 as usize];
if valid {
if diff > 0 {
while valid && ctrl != b'\n' {
let (n, c) = read(&mut input);
let new_diff = n - prev;
(prev, ctrl) = (n, c);
valid &= lt_valid(new_diff);
}
} else {
while valid && ctrl != b'\n' {
let (n, c) = read(&mut input);
let new_diff = n - prev;
(prev, ctrl) = (n, c);
valid &= gt_valid(new_diff);
}
}
}
if valid {
count += 1;
}
}
acc.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
pub unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 1000];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let mut lens = [1000 / par2::NUM_THREADS; par2::NUM_THREADS];
for i in 0..1000 % par2::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par2::NUM_THREADS + 1];
for i in 0..par2::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let acc = std::sync::atomic::AtomicU64::new(0);
par2::par(|idx| {
unsafe fn read(input: &mut std::slice::Iter<u8>) -> (i8, u8) {
let d1 = *input.next().unwrap_unchecked();
let mut d2 = *input.next().unwrap_unchecked();
let mut n = d1 - b'0';
if d2 >= b'0' {
n = 10 * n + (d2 - b'0');
d2 = *input.next().unwrap_unchecked();
}
(n as i8, d2)
}
let mut count = 0;
for i in poss[idx]..poss[idx + 1] {
let l = *lines.get_unchecked(i);
let mut input = input.get_unchecked(l..).iter();
let (n1, _) = read(&mut input);
let (n2, c2) = read(&mut input);
let diff = n2 - n1;
let mut prevprev = n1;
let mut prev = n2;
let mut ctrl = c2;
static STATE_MAP: [[u8; 4]; 4] =
[[2, 1, 0, 0], [4, 3, 3, 3], [4, 3, 4, 3], [4, 4, 3, 3]];
let mut lt_st = if lt_valid(diff) { 0 } else { 1 };
let mut gt_st = if gt_valid(diff) { 0 } else { 1 };
while lt_st != 4 && gt_st != 4 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
(prevprev, prev, ctrl) = (prev, n, c);
}
if lt_st != 4 {
while lt_st == 0 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !lt_valid(p_diff) {
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
}
(prevprev, prev, ctrl) = (prev, n, c);
}
if ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
(prev, ctrl) = (n, c);
}
while lt_st == 3 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !lt_valid(p_diff) {
lt_st = 4;
}
(prev, ctrl) = (n, c);
}
} else if gt_st != 4 {
while gt_st == 0 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !gt_valid(p_diff) {
let pp_diff = n - prevprev;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
}
(prevprev, prev, ctrl) = (prev, n, c);
}
if ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
(prev, ctrl) = (n, c);
}
while gt_st == 3 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !gt_valid(p_diff) {
gt_st = 4;
}
(prev, ctrl) = (n, c);
}
}
if lt_st != 4 || gt_st != 4 {
count += 1;
}
}
acc.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
mod par1 {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
mod par2 {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d14p1.rs | 2024/d14p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) as u64 }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
macro_rules! parse_pos {
($ptr:ident as $ty:ty) => {{
let mut n = *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
if *$ptr as $ty >= b'0' as $ty {
n = 10 * n + *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
if *$ptr as $ty >= b'0' as $ty {
n = 10 * n + *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
}
}
n
}};
}
macro_rules! parse {
($ptr:ident as $ty:ident - $m:expr) => {{
if *$ptr == b'-' {
$ptr = $ptr.add(1);
$m as $ty - parse_pos!($ptr as $ty)
} else {
parse_pos!($ptr as $ty)
}
}};
}
const W: i64 = 101;
const H: i64 = 103;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut counts = [[0; 2]; 2];
let mut ptr = input.as_ptr().wrapping_sub(1);
let end = ptr.add(input.len());
type Ty = u32;
loop {
ptr = ptr.add(3);
let px = parse_pos!(ptr as Ty);
ptr = ptr.add(1);
let py = parse_pos!(ptr as Ty);
ptr = ptr.add(3);
let vx = parse!(ptr as Ty - W);
ptr = ptr.add(1);
let vy = parse!(ptr as Ty - H);
let fx = fastdiv::fastmod_w((px + 100 * vx) as _) as Ty;
let fy = fastdiv::fastmod_h((py + 100 * vy) as _) as Ty;
if fx != W as Ty / 2 && fy != H as Ty / 2 {
counts[(fx < W as Ty / 2) as usize][(fy < H as Ty / 2) as usize] += 1;
}
if ptr == end {
break;
}
}
counts[0][0] * counts[0][1] * counts[1][0] * counts[1][1]
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
type Ty = u16;
#[repr(C, align(32))]
struct Aligned<T>(T);
let mut robots_x = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_y = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_vx = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_vy = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut offset = 0;
let mut ptr = input.as_ptr().wrapping_sub(1);
loop {
ptr = ptr.add(3);
let px = parse_pos!(ptr as Ty);
*robots_x.0.get_unchecked_mut(offset).as_mut_ptr() = px;
ptr = ptr.add(1);
let py = parse_pos!(ptr as Ty);
*robots_y.0.get_unchecked_mut(offset).as_mut_ptr() = py;
ptr = ptr.add(3);
let vx = parse!(ptr as Ty - W);
*robots_vx.0.get_unchecked_mut(offset).as_mut_ptr() = vx;
ptr = ptr.add(1);
let vy = parse!(ptr as Ty - H);
*robots_vy.0.get_unchecked_mut(offset).as_mut_ptr() = vy;
offset += 1;
if offset == 128 {
break;
}
}
macro_rules! run_loop {
($p:ident, $v:ident | $s:ident) => {{
let mut i = 0;
loop {
i += 1;
let mut sum = u16x16::splat(0);
let mut sum2 = u32x16::splat(0);
for offset in 0..128 / 16 {
let p = *$p.0.as_mut_ptr().cast::<u16x16>().add(offset);
let v = *$v.0.as_ptr().cast::<u16x16>().add(offset);
let np = p + v;
let np = np.simd_min(np - u16x16::splat($s as Ty));
sum += np;
sum2 += np.cast::<u32>() * np.cast::<u32>();
*$p.0.as_mut_ptr().cast::<u16x16>().add(offset) = np;
}
let sum = sum.reduce_sum() as u64;
let sum2 = sum2.reduce_sum() as u64;
let var = sum2 - (sum * sum / 128);
if var < 540 * 128 {
break i;
}
}
}};
}
let mut i = i64::MAX;
let j;
let mut p = &mut robots_x;
let mut v = &robots_vx;
let mut c = W;
loop {
let n = run_loop!(p, v | c);
if i == i64::MAX {
i = n;
p = &mut robots_y;
v = &robots_vy;
c = H;
} else {
j = n;
break;
}
}
(51 * (i * H + j * W) % (W * H)) as u64
}
mod fastdiv {
#[inline(always)]
const fn compute_m_u16(d: u16) -> u32 {
(u32::MAX / d as u32) + 1
}
#[inline(always)]
const fn mul64_u16(lowbits: u32, d: u16) -> u32 {
(lowbits as u64 * d as u64 >> 32) as u32
}
#[inline(always)]
const fn fastmod_u16(a: u16, m: u32, d: u16) -> u16 {
let lowbits = m.wrapping_mul(a as u32);
mul64_u16(lowbits, d) as u16
}
#[inline(always)]
pub fn fastmod_w(a: u16) -> u16 {
use super::W as D;
const M: u32 = compute_m_u16(D as _);
fastmod_u16(a, M, D as _)
}
#[inline(always)]
pub fn fastmod_h(a: u16) -> u16 {
use super::H as D;
const M: u32 = compute_m_u16(D as _);
fastmod_u16(a, M, D as _)
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d10p2.rs | 2024/d10p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let line_len = 1 + u8x64::from_slice(input.get_unchecked(..64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
let len = input.len() - 1;
let mut offset = 0;
let mut tot = 0;
loop {
let mut mask = if offset + 64 <= input.len() {
let block = u8x64::from_slice(input.get_unchecked(offset..offset + 64));
block.simd_eq(u8x64::splat(b'9')).to_bitmask()
} else if offset < input.len() {
let block = u8x64::from_slice(input.get_unchecked(input.len() - 64..));
block.simd_eq(u8x64::splat(b'9')).to_bitmask() >> (64 - (input.len() - offset))
} else {
break;
};
while mask != 0 {
let o = mask.trailing_zeros();
mask &= !(1 << o);
let mut seen = u16x16::from_slice(&[u16::MAX; 16]);
let mut seen_len = 0;
let mut stack = [MaybeUninit::uninit(); 16];
let mut stack_len = 0;
let mut curr_o = offset + o as usize;
let mut c = b'9';
loop {
if c == b'0' {
if seen.simd_ne(u16x16::splat(curr_o as u16)).all() {
*seen.as_mut_array().get_unchecked_mut(seen_len) = curr_o as u16;
seen_len += 1;
}
if stack_len == 0 {
break;
}
stack_len -= 1;
(curr_o, c) = stack.get_unchecked(stack_len).assume_init();
continue;
}
let l = curr_o.wrapping_sub(1);
let r = curr_o.wrapping_add(1);
let t = curr_o.wrapping_sub(line_len);
let b = curr_o.wrapping_add(line_len);
macro_rules! handle {
($new_o:expr) => {{
let new_o = $new_o;
if *input.get_unchecked(new_o) == c - 1 {
*stack.get_unchecked_mut(stack_len).as_mut_ptr() = (new_o, c - 1);
stack_len += 1;
}
}};
}
if t < len - 2 * line_len {
handle!(t);
handle!(b);
handle!(l);
} else {
if t < len {
handle!(t);
handle!(l);
if b < len {
handle!(b);
}
} else {
handle!(b);
if l < len {
handle!(l);
}
}
}
if *input.get_unchecked(r) == c - 1 {
(curr_o, c) = (r, c - 1);
} else if stack_len > 0 {
stack_len -= 1;
(curr_o, c) = stack.get_unchecked(stack_len).assume_init();
} else {
break;
}
}
tot += seen_len;
}
offset += 64;
}
tot as u64
}
const SWIZZLE_MAP: [usize; 32] = {
let mut mask = [0; 32];
let mut i = 0;
while i < 31 {
mask[i] = i + 1;
i += 1;
}
mask[31] = 31 + 32;
mask
};
const EXTRA_MASKS: [[i8; 32]; 32] = {
let mut masks = [[0; 32]; 32];
let mut i = 0;
while i < 32 {
let mut j = i;
while j < 32 {
masks[i][j] = -1;
j += 1;
}
i += 1;
}
masks
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let ll = 1 + u8x64::from_slice(input.get_unchecked(..64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
let mut count = MaybeUninit::<[u8; 64 * 64]>::uninit();
#[cfg(debug_assertions)]
let mut count2 = [0; 64 * 64];
{
let mut off = 0;
while off + 32 <= input.len() {
let block = u8x32::from_slice(input.get_unchecked(off..off + 32));
let mask0 = block.simd_eq(u8x32::splat(b'0'));
let b0 = mask0.to_int().cast() & u8x32::splat(1);
let mask9 = block.simd_eq(u8x32::splat(b'9'));
let b9 = mask9.to_int().cast() & u8x32::splat(1);
let s = count.as_mut_ptr().cast::<u8>().add(off);
*s.cast() = *(b0 | b9).as_array();
off += 32;
}
let extra = (off + 32) - input.len();
if extra != 32 {
debug_assert!(extra < 32);
off = input.len() - 32;
let block = u8x32::from_slice(input.get_unchecked(off..off + 32));
let mask0 = block.simd_eq(u8x32::splat(b'0'));
let b0 = mask0.to_int().cast() & u8x32::splat(1);
let mask9 = block.simd_eq(u8x32::splat(b'9'));
let b9 = mask9.to_int().cast() & u8x32::splat(1);
let s = count.as_mut_ptr().cast::<u8>().add(off);
*s.cast() = *(b0 | b9).as_array();
}
}
#[cfg(debug_assertions)]
{
for i in 0..input.len() {
if input[i] == b'0' || input[i] == b'9' {
count2[i] = 1;
}
}
println!("v1");
for i in 0..ll - 1 {
for j in 0..ll - 1 {
print!("{} ", count.assume_init_ref()[ll * i + j]);
}
println!();
}
println!("v2");
for i in 0..ll - 1 {
for j in 0..ll - 1 {
print!("{} ", count2[ll * i + j]);
}
println!();
}
for i in 0..input.len() {
assert_eq!(
count.assume_init_ref()[i],
count2[i],
"{} {} {}",
i,
i / ll,
i % ll
);
}
}
for c1 in b'0'..b'4' {
let c2 = c1 + 1;
let c3 = b'9' - (c1 - b'0');
let c4 = c3 - 1;
let cs1 = u8x32::splat(c1);
let cs2 = u8x32::splat(c2);
let cs3 = u8x32::splat(c3);
let cs4 = u8x32::splat(c4);
let mut off = 0;
while off + ll + 1 + 32 <= input.len() {
let oa = off;
let ob = off + 1;
let oc = off + ll;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let c = u8x32::from_slice(input.get_unchecked(oc..oc + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let a3 = a.simd_eq(cs3);
let a4 = a.simd_eq(cs4);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let b3 = b.simd_eq(cs3);
let b4 = b.simd_eq(cs4);
let c1 = c.simd_eq(cs1);
let c2 = c.simd_eq(cs2);
let c3 = c.simd_eq(cs3);
let c4 = c.simd_eq(cs4);
let mut xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let mut xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
let mut xc = u8x32::from_slice(count.get_unchecked(oc..oc + 32));
xa += a2.to_int().cast() & ((b1.to_int().cast() & xb) + (c1.to_int().cast() & xc));
xa += a4.to_int().cast() & ((b3.to_int().cast() & xb) + (c3.to_int().cast() & xc));
xb = simd_swizzle!(xa, xb, SWIZZLE_MAP);
xb += xa & a1.to_int().cast() & b2.to_int().cast();
xc += xa & a1.to_int().cast() & c2.to_int().cast();
xb += xa & a3.to_int().cast() & b4.to_int().cast();
xc += xa & a3.to_int().cast() & c4.to_int().cast();
*count.as_mut_ptr().cast::<u8>().add(oa) = xa[0];
xb.copy_to_slice(count.get_unchecked_mut(ob..ob + 32));
xc.copy_to_slice(count.get_unchecked_mut(oc..oc + 32));
off += 32;
}
let extra = (off + ll + 1 + 32) - input.len();
if extra != 32 {
let mask =
mask8x32::from_int_unchecked(i8x32::from_slice(EXTRA_MASKS.get_unchecked(extra)));
off = input.len() - (ll + 1 + 32);
let oa = off;
let ob = off + 1;
let oc = off + ll;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let c = u8x32::from_slice(input.get_unchecked(oc..oc + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let a3 = a.simd_eq(cs3);
let a4 = a.simd_eq(cs4);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let b3 = b.simd_eq(cs3);
let b4 = b.simd_eq(cs4);
let c1 = c.simd_eq(cs1);
let c2 = c.simd_eq(cs2);
let c3 = c.simd_eq(cs3);
let c4 = c.simd_eq(cs4);
let mut xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let mut xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
let mut xc = u8x32::from_slice(count.get_unchecked(oc..oc + 32));
xa += (mask & a2).to_int().cast()
& ((b1.to_int().cast() & xb) + (c1.to_int().cast() & xc));
xa += (mask & a4).to_int().cast()
& ((b3.to_int().cast() & xb) + (c3.to_int().cast() & xc));
xb = simd_swizzle!(xa, xb, SWIZZLE_MAP);
xb += xa & (a1 & mask).to_int().cast() & b2.to_int().cast();
xc += xa & (a1 & mask).to_int().cast() & c2.to_int().cast();
xb += xa & (a3 & mask).to_int().cast() & b4.to_int().cast();
xc += xa & (a3 & mask).to_int().cast() & c4.to_int().cast();
*count.as_mut_ptr().cast::<u8>().add(oa) = xa[0];
xb.copy_to_slice(count.get_unchecked_mut(ob..ob + 32));
xc.copy_to_slice(count.get_unchecked_mut(oc..oc + 32));
}
off = input.len() - ll;
while off + 1 + 32 <= input.len() {
let oa = off;
let ob = off + 1;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let a3 = a.simd_eq(cs3);
let a4 = a.simd_eq(cs4);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let b3 = b.simd_eq(cs3);
let b4 = b.simd_eq(cs4);
let mut xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let mut xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
xa += (a2 & b1).to_int().cast() & xb;
xa += (a4 & b3).to_int().cast() & xb;
xb = simd_swizzle!(xa, xb, SWIZZLE_MAP);
xb += (b2 & a1).to_int().cast() & xa;
xb += (b4 & a3).to_int().cast() & xa;
*count.as_mut_ptr().cast::<u8>().add(oa) = xa[0];
xb.copy_to_slice(count.get_unchecked_mut(ob..ob + 32));
off += 32;
}
let extra = (off + 1 + 32) - input.len();
if extra != 32 {
debug_assert!(extra < 32);
let mask =
mask8x32::from_int_unchecked(i8x32::from_slice(EXTRA_MASKS.get_unchecked(extra)));
off = input.len() - 32 - 1;
let oa = off;
let ob = off + 1;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let a3 = a.simd_eq(cs3);
let a4 = a.simd_eq(cs4);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let b3 = b.simd_eq(cs3);
let b4 = b.simd_eq(cs4);
let mut xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let mut xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
xa += (a2 & b1 & mask).to_int().cast() & xb;
xa += (a4 & b3 & mask).to_int().cast() & xb;
xb = simd_swizzle!(xa, xb, SWIZZLE_MAP);
xb += (b2 & a1 & mask).to_int().cast() & xa;
xb += (b4 & a3 & mask).to_int().cast() & xa;
*count.as_mut_ptr().cast::<u8>().add(oa) = xa[0];
xb.copy_to_slice(count.get_unchecked_mut(ob..ob + 32));
}
#[cfg(debug_assertions)]
{
println!(
"{}-{} + {}-{} v2",
c1 as char, c2 as char, c3 as char, c4 as char
);
for i in 0..input.len() {
if input[i] == c2 {
let j = i.wrapping_sub(1);
if j < input.len() && input[j] == c1 {
count2[i] += count2[j];
}
let j = i.wrapping_add(1);
if j < input.len() && input[j] == c1 {
count2[i] += count2[j];
}
let j = i.wrapping_sub(ll);
if j < input.len() && input[j] == c1 {
count2[i] += count2[j];
}
let j = i.wrapping_add(ll);
if j < input.len() && input[j] == c1 {
count2[i] += count2[j];
}
} else if input[i] == c4 {
let j = i.wrapping_sub(1);
if j < input.len() && input[j] == c3 {
count2[i] += count2[j];
}
let j = i.wrapping_add(1);
if j < input.len() && input[j] == c3 {
count2[i] += count2[j];
}
let j = i.wrapping_sub(ll);
if j < input.len() && input[j] == c3 {
count2[i] += count2[j];
}
let j = i.wrapping_add(ll);
if j < input.len() && input[j] == c3 {
count2[i] += count2[j];
}
}
}
println!("v1");
for i in 0..ll - 1 {
for j in 0..ll - 1 {
print!("{} ", count.assume_init_ref()[ll * i + j]);
}
println!();
}
println!("v2");
for i in 0..ll - 1 {
for j in 0..ll - 1 {
print!("{} ", count2[ll * i + j]);
}
println!();
}
for i in 0..input.len() {
assert_eq!(
count.assume_init_ref()[i],
count2[i],
"{} {} {}",
i,
i / ll,
i % ll
);
}
}
}
#[cfg(debug_assertions)]
let mut tot_exp = 0;
#[cfg(debug_assertions)]
{
for i in 0..input.len() {
if input[i] == b'4' {
let j = i.wrapping_sub(1);
if j < input.len() && input[j] == b'5' {
tot_exp += (count2[i] * count2[j]) as u16;
}
let j = i.wrapping_add(1);
if j < input.len() && input[j] == b'5' {
tot_exp += (count2[i] * count2[j]) as u16;
}
let j = i.wrapping_sub(ll);
if j < input.len() && input[j] == b'5' {
tot_exp += (count2[i] * count2[j]) as u16;
}
let j = i.wrapping_add(ll);
if j < input.len() && input[j] == b'5' {
tot_exp += (count2[i] * count2[j]) as u16;
}
}
}
}
{
let c1 = b'4';
let c2 = c1 + 1;
let cs1 = u8x32::splat(c1);
let cs2 = u8x32::splat(c2);
let mut off = 0;
let mut tot = u8x32::splat(0);
while off + ll + 1 + 32 <= input.len() {
let oa = off;
let ob = off + 1;
let oc = off + ll;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let c = u8x32::from_slice(input.get_unchecked(oc..oc + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let c1 = c.simd_eq(cs1);
let c2 = c.simd_eq(cs2);
let xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
let xc = u8x32::from_slice(count.get_unchecked(oc..oc + 32));
tot += (xa * xb) & b1.to_int().cast() & a2.to_int().cast();
tot += (xa * xc) & c1.to_int().cast() & a2.to_int().cast();
tot += (xa * xb) & a1.to_int().cast() & b2.to_int().cast();
tot += (xa * xc) & a1.to_int().cast() & c2.to_int().cast();
off += 32;
}
let extra = (off + ll + 1 + 32) - input.len();
if extra != 32 {
debug_assert!(extra < 32);
let mask =
mask8x32::from_int_unchecked(i8x32::from_slice(EXTRA_MASKS.get_unchecked(extra)));
off = input.len() - (ll + 1 + 32);
let oa = off;
let ob = off + 1;
let oc = off + ll;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let c = u8x32::from_slice(input.get_unchecked(oc..oc + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let c1 = c.simd_eq(cs1);
let c2 = c.simd_eq(cs2);
let xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
let xc = u8x32::from_slice(count.get_unchecked(oc..oc + 32));
tot += (xa * xb) & mask.to_int().cast() & b1.to_int().cast() & a2.to_int().cast();
tot += (xa * xc) & mask.to_int().cast() & c1.to_int().cast() & a2.to_int().cast();
tot += (xa * xb) & mask.to_int().cast() & a1.to_int().cast() & b2.to_int().cast();
tot += (xa * xc) & mask.to_int().cast() & a1.to_int().cast() & c2.to_int().cast();
}
off = input.len() - ll;
while off + 1 + 32 <= input.len() {
let oa = off;
let ob = off + 1;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
tot += (a2 & b1).to_int().cast() & (xa * xb);
tot += (b2 & a1).to_int().cast() & (xa * xb);
off += 32;
}
let extra = (off + 1 + 32) - input.len();
if extra != 32 {
debug_assert!(extra < 32);
let mask =
mask8x32::from_int_unchecked(i8x32::from_slice(EXTRA_MASKS.get_unchecked(extra)));
off = input.len() - 32 - 1;
let oa = off;
let ob = off + 1;
let a = u8x32::from_slice(input.get_unchecked(oa..oa + 32));
let b = u8x32::from_slice(input.get_unchecked(ob..ob + 32));
let a1 = a.simd_eq(cs1);
let a2 = a.simd_eq(cs2);
let b1 = b.simd_eq(cs1);
let b2 = b.simd_eq(cs2);
let xa = u8x32::from_slice(count.get_unchecked(oa..oa + 32));
let xb = u8x32::from_slice(count.get_unchecked(ob..ob + 32));
tot += (a2 & b1 & mask).to_int().cast() & (xa * xb);
tot += (b2 & a1 & mask).to_int().cast() & (xa * xb);
}
#[cfg(debug_assertions)]
debug_assert_eq!(tot_exp, tot.cast::<u16>().reduce_sum());
tot.cast::<u16>().reduce_sum() as u64
}
}
use std::ops::Range;
trait MUHelper<T> {
unsafe fn get_unchecked(&self, r: Range<usize>) -> &[T];
unsafe fn get_unchecked_mut(&mut self, r: Range<usize>) -> &mut [T];
}
impl<T, const N: usize> MUHelper<T> for MaybeUninit<[T; N]> {
unsafe fn get_unchecked(&self, r: Range<usize>) -> &[T] {
&*self.as_ptr().as_slice().get_unchecked(r)
}
unsafe fn get_unchecked_mut(&mut self, r: Range<usize>) -> &mut [T] {
&mut *self.as_mut_ptr().as_mut_slice().get_unchecked_mut(r)
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d23p1.rs | 2024/d23p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
// pub fn run(input: &str) -> &'static str {
// part2(input)
// }
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> &'static str {
unsafe { inner_part2(input) }
}
const L: usize = 11;
#[inline(always)]
unsafe fn parse(input: &str, sets: &mut [[u64; L]; 26 * 26 + 1]) {
let mut ptr = input.as_ptr();
let end = ptr.add(input.len() - 36);
loop {
let mut b = ptr.cast::<u8x16>().read_unaligned();
b[2] = *ptr.add(16);
let b = simd_swizzle!(b, [0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 2, 0, 0, 0, 0]);
let b = b - u8x16::splat(b'a');
let m = u8x16::from_array([26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 0, 0, 0, 0]);
let b = u16x8::from(_mm_maddubs_epi16(b.into(), m.into()));
let i = b * u16x8::splat(L as u16) + (simd_swizzle!(b, [1, 0, 3, 2, 5, 4, 7, 6]) >> 6);
let (x, y) = (0, 1);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (2, 3);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (4, 5);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
ptr = ptr.add(18);
let mut b = ptr.cast::<u8x16>().read_unaligned();
b[2] = *ptr.add(16);
let b = simd_swizzle!(b, [0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 2, 0, 0, 0, 0]);
let b = b - u8x16::splat(b'a');
let m = u8x16::from_array([26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 0, 0, 0, 0]);
let b = u16x8::from(_mm_maddubs_epi16(b.into(), m.into()));
let i = b * u16x8::splat(L as u16) + (simd_swizzle!(b, [1, 0, 3, 2, 5, 4, 7, 6]) >> 6);
let (x, y) = (0, 1);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (2, 3);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (4, 5);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
ptr = ptr.add(18);
if ptr > end {
break;
}
}
let end = input.as_ptr().add(input.len());
while ptr != end {
let b1 = *ptr.add(0) as usize - b'a' as usize;
let b2 = *ptr.add(1) as usize - b'a' as usize;
let b3 = *ptr.add(3) as usize - b'a' as usize;
let b4 = *ptr.add(4) as usize - b'a' as usize;
let n1 = 26 * b1 + b2;
let n2 = 26 * b3 + b4;
*sets.get_unchecked_mut(n1).get_unchecked_mut(n2 / 64) |= 1 << (n2 % 64);
*sets.get_unchecked_mut(n2).get_unchecked_mut(n1 / 64) |= 1 << (n1 % 64);
ptr = ptr.add(6);
}
}
static LUT1: [(u64, u64); 26] = {
let mut lut = [(u64::MAX, u64::MAX); 26];
let off = (26 * (b't' - b'a') as usize) % 64;
let mut i = 0;
while i < 26 {
let mut j = 0;
while j < i {
if off + j < 64 {
lut[i].0 &= !(1 << (off + j));
} else {
lut[i].1 &= !(1 << (off + j - 64));
}
j += 1;
}
i += 1;
}
lut
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut sets = [[0u64; L]; 26 * 26 + 1];
parse(input, &mut sets);
let mut count = u16x16::splat(0);
for b2 in 0..26 {
let i = 26 * (b't' - b'a') as usize + b2;
let mut s1 = sets.as_ptr().add(i).cast::<[u64; 12]>().read();
let (m1, m2) = LUT1[b2];
s1[7] &= m1;
s1[8] &= m2;
s1[11] = 0;
let mut acc = u64x4::splat(0);
for si in 0..L {
while s1[si] != 0 {
let o = s1[si].trailing_zeros() as usize;
let j = 64 * si + o;
s1[si] ^= 1 << o;
let s2 = sets.as_ptr().add(j).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
acc += tot8;
}
}
let mhhhh = u64x4::splat(0xFF00FF00FF00FF00);
let mllll = mhhhh >> 8;
let (acch, accl) = ((acc & mhhhh) >> 8, acc & mllll);
count += std::mem::transmute::<u64x4, u16x16>(acch + accl);
}
count.reduce_sum() as u64
}
static mut PART2_OUT: [u8; 13 * 2 + 12] = [b','; 13 * 2 + 12];
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> &'static str {
let mut sets = [[0u64; L]; 26 * 26 + 1];
parse(input, &mut sets);
for i in 0..26 * 26 {
let mut s1 = sets.as_ptr().add(i).cast::<[u64; 12]>().read();
s1[11] = 0;
if s1 == [0; 12] {
continue;
}
macro_rules! handle {
($other:expr) => {
'handle: {
let other = $other;
let s2 = sets.as_ptr().add(other).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
let count = std::mem::transmute::<_, u8x32>(tot8).reduce_sum();
if count != 11 {
break 'handle;
}
let mut common = std::mem::transmute::<_, [u64; 12]>([xa, xb, xc]);
for i in 0..L {
let mut b = common[i];
while b != 0 {
let o = b.trailing_zeros() as usize;
let j = 64 * i + o;
b ^= 1 << o;
let s2 = sets.as_ptr().add(j).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
let count = std::mem::transmute::<_, u8x32>(tot8).reduce_sum();
if count != 11 {
break 'handle;
}
}
}
*common.get_unchecked_mut(i / 64) |= 1 << (i % 64);
*common.get_unchecked_mut(other / 64) |= 1 << (other % 64);
let mut pos = 0;
for i in 0..L {
let mut b = common[i];
while b != 0 {
let o = b.trailing_zeros() as usize;
let j = 64 * i + o;
b ^= 1 << o;
*PART2_OUT.get_unchecked_mut(pos) = b'a' + (j / 26) as u8;
*PART2_OUT.get_unchecked_mut(pos + 1) = b'a' + (j % 26) as u8;
pos += 3;
}
}
return std::str::from_utf8_unchecked(&PART2_OUT);
}
};
}
let mut j = 0;
let mut b = *s1.get_unchecked(j);
while b == 0 {
j += 1;
b = *s1.get_unchecked(j);
}
handle!(64 * j + b.trailing_zeros() as usize);
b &= !(1 << b.trailing_zeros());
while b == 0 {
j += 1;
b = *s1.get_unchecked(j);
}
handle!(64 * j + b.trailing_zeros() as usize);
}
std::hint::unreachable_unchecked();
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d14p2.rs | 2024/d14p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) as u64 }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
macro_rules! parse_pos {
($ptr:ident as $ty:ty) => {{
let mut n = *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
if *$ptr as $ty >= b'0' as $ty {
n = 10 * n + *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
if *$ptr as $ty >= b'0' as $ty {
n = 10 * n + *$ptr as $ty - b'0' as $ty;
$ptr = $ptr.add(1);
}
}
n
}};
}
macro_rules! parse {
($ptr:ident as $ty:ident - $m:expr) => {{
if *$ptr == b'-' {
$ptr = $ptr.add(1);
$m as $ty - parse_pos!($ptr as $ty)
} else {
parse_pos!($ptr as $ty)
}
}};
}
const W: i64 = 101;
const H: i64 = 103;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut counts = [[0; 2]; 2];
let mut ptr = input.as_ptr().wrapping_sub(1);
let end = ptr.add(input.len());
type Ty = u32;
loop {
ptr = ptr.add(3);
let px = parse_pos!(ptr as Ty);
ptr = ptr.add(1);
let py = parse_pos!(ptr as Ty);
ptr = ptr.add(3);
let vx = parse!(ptr as Ty - W);
ptr = ptr.add(1);
let vy = parse!(ptr as Ty - H);
let fx = fastdiv::fastmod_w((px + 100 * vx) as _) as Ty;
let fy = fastdiv::fastmod_h((py + 100 * vy) as _) as Ty;
if fx != W as Ty / 2 && fy != H as Ty / 2 {
counts[(fx < W as Ty / 2) as usize][(fy < H as Ty / 2) as usize] += 1;
}
if ptr == end {
break;
}
}
counts[0][0] * counts[0][1] * counts[1][0] * counts[1][1]
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
type Ty = u16;
#[repr(C, align(32))]
struct Aligned<T>(T);
let mut robots_x = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_y = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_vx = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut robots_vy = Aligned([MaybeUninit::<Ty>::uninit(); 128]);
let mut offset = 0;
let mut ptr = input.as_ptr().wrapping_sub(1);
// let end = ptr.add(input.len());
loop {
ptr = ptr.add(3);
let px = parse_pos!(ptr as Ty);
*robots_x.0.get_unchecked_mut(offset).as_mut_ptr() = px;
ptr = ptr.add(1);
let py = parse_pos!(ptr as Ty);
*robots_y.0.get_unchecked_mut(offset).as_mut_ptr() = py;
ptr = ptr.add(3);
let vx = parse!(ptr as Ty - W);
*robots_vx.0.get_unchecked_mut(offset).as_mut_ptr() = vx;
ptr = ptr.add(1);
let vy = parse!(ptr as Ty - H);
*robots_vy.0.get_unchecked_mut(offset).as_mut_ptr() = vy;
offset += 1;
if offset == 128 {
break;
}
}
macro_rules! run_loop {
($p:ident, $v:ident | $s:ident) => {{
let mut i = 0;
loop {
i += 1;
let mut sum = u16x16::splat(0);
let mut sum2 = u32x16::splat(0);
for offset in 0..128 / 16 {
let p = *$p.0.as_mut_ptr().cast::<u16x16>().add(offset);
let v = *$v.0.as_ptr().cast::<u16x16>().add(offset);
let np = p + v;
let np = np.simd_min(np - u16x16::splat($s as Ty));
sum += np;
sum2 += np.cast::<u32>() * np.cast::<u32>();
*$p.0.as_mut_ptr().cast::<u16x16>().add(offset) = np;
}
let sum = sum.reduce_sum() as u64;
let sum2 = sum2.reduce_sum() as u64;
let var = sum2 - (sum * sum / 128);
if var < 540 * 128 {
break i;
}
}
}};
}
let mut i = i64::MAX;
let j;
let mut p = &mut robots_x;
let mut v = &robots_vx;
let mut c = W;
loop {
let n = run_loop!(p, v | c);
if i == i64::MAX {
i = n;
p = &mut robots_y;
v = &robots_vy;
c = H;
} else {
j = n;
break;
}
}
(51 * (i * H + j * W) % (W * H)) as u64
}
mod fastdiv {
#[inline(always)]
const fn compute_m_u16(d: u16) -> u32 {
(u32::MAX / d as u32) + 1
}
#[inline(always)]
const fn mul64_u16(lowbits: u32, d: u16) -> u32 {
(lowbits as u64 * d as u64 >> 32) as u32
}
#[inline(always)]
const fn fastmod_u16(a: u16, m: u32, d: u16) -> u16 {
let lowbits = m.wrapping_mul(a as u32);
mul64_u16(lowbits, d) as u16
}
#[inline(always)]
pub fn fastmod_w(a: u16) -> u16 {
use super::W as D;
const M: u32 = compute_m_u16(D as _);
fastmod_u16(a, M, D as _)
}
#[inline(always)]
pub fn fastmod_h(a: u16) -> u16 {
use super::H as D;
const M: u32 = compute_m_u16(D as _);
fastmod_u16(a, M, D as _)
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d18p2.rs | 2024/d18p2.rs | // Original by: caavik
use std::fmt;
pub fn run(input: &str) -> impl fmt::Display {
unsafe {
const GRID_WIDTH: usize = 71;
const PADDED_WIDTH: usize = GRID_WIDTH + 2; // Don't need bounds checks
const START_ID: usize = PADDED_WIDTH + 1;
const END_ID: usize = GRID_WIDTH * PADDED_WIDTH + GRID_WIDTH;
struct Coordinate {
x: usize,
y: usize,
}
impl fmt::Display for Coordinate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{},{}", self.x, self.y)
}
}
// Initialize data structures equivalent to the C# code
static mut byte_order: [u16; GRID_WIDTH * GRID_WIDTH] = [0u16; GRID_WIDTH * GRID_WIDTH];
byte_order.fill(0);
static mut order_lookup: [u16; PADDED_WIDTH * PADDED_WIDTH] =
[u16::MAX; PADDED_WIDTH * PADDED_WIDTH];
order_lookup.fill(u16::MAX);
// Mark borders as visited
static mut visited: [u64; (PADDED_WIDTH * PADDED_WIDTH + 63) / 64] =
[0u64; (PADDED_WIDTH * PADDED_WIDTH + 63) / 64];
visited.fill(0);
let visited_len = visited.len();
let overflow = visited_len * 64 - (PADDED_WIDTH * PADDED_WIDTH);
// mark borders as visited
*visited.get_unchecked_mut(0) = u64::MAX;
*visited.get_unchecked_mut(1) |= (1u64 << (PADDED_WIDTH - 64)) - 1;
*visited.get_unchecked_mut(visited_len - 1) = u64::MAX;
*visited.get_unchecked_mut(visited_len - 2) |=
u64::MAX << (128 - (PADDED_WIDTH + overflow));
for i in 1..PADDED_WIDTH - 1 {
let idx1 = (i * PADDED_WIDTH) / 64;
let bit1 = 1u64 << ((i * PADDED_WIDTH) % 64);
*visited.get_unchecked_mut(idx1) |= bit1;
let idx2 = (i * PADDED_WIDTH + PADDED_WIDTH - 1) / 64;
let bit2 = 1u64 << ((i * PADDED_WIDTH + PADDED_WIDTH - 1) % 64);
*visited.get_unchecked_mut(idx2) |= bit2;
}
static mut reachable: [u64; (GRID_WIDTH * GRID_WIDTH + 63) / 64] =
[0u64; (GRID_WIDTH * GRID_WIDTH + 63) / 64];
reachable.fill(0);
// Parse the input and populate byte_order and order_lookup arrays
let mut byte_count: u16 = 0;
let input_bytes = input.as_bytes();
let mut idx = 0;
while idx < input_bytes.len() {
let mut x = (input_bytes.get_unchecked(idx) - b'0') as usize;
idx += 1;
let mut c = *input_bytes.get_unchecked(idx);
idx += 1;
if c != b',' {
x = x * 10 + (c - b'0') as usize;
idx += 1; // Skip ','
}
let mut y = (*input_bytes.get_unchecked(idx) - b'0') as usize;
idx += 1;
c = *input_bytes.get_unchecked(idx);
idx += 1;
if c != b'\n' {
y = y * 10 + (c - b'0') as usize;
idx += 1; // Skip '\n'
}
x += 1;
y += 1;
let id = (y * PADDED_WIDTH + x) as u16;
*byte_order.get_unchecked_mut(byte_count as usize) = id;
*order_lookup.get_unchecked_mut(id as usize) = byte_count;
byte_count += 1;
}
// Mark the start position (0, 0) as the final fallen byte and mark it as reachable/visited
*byte_order.get_unchecked_mut(byte_count as usize) = START_ID as u16;
*order_lookup.get_unchecked_mut(START_ID) = byte_count;
*reachable.get_unchecked_mut((byte_count / 64) as usize) |= 1u64 << (byte_count % 64);
*visited.get_unchecked_mut(START_ID / 64) |= 1u64 << (START_ID % 64);
// Implement BFS using a manually managed stack
let mut bfs_stack = [0u16; 128];
let mut ptr = 0usize;
for i in (0..reachable.len()).rev() {
loop {
let reachable_i = *reachable.get_unchecked(i);
let leading_zeros = reachable_i.leading_zeros() as i32;
let next_in_reach = 63 - leading_zeros;
if next_in_reach == -1 {
break;
}
let max_reachable = 64 * i + next_in_reach as usize;
*reachable.get_unchecked_mut(i) ^= 1u64 << next_in_reach;
let max_byte = *byte_order.get_unchecked(max_reachable);
*bfs_stack.get_unchecked_mut(ptr) = max_byte;
ptr += 1;
while ptr > 0 {
ptr -= 1;
let next_byte = *bfs_stack.get_unchecked(ptr);
if next_byte as usize == END_ID {
let result_x = (max_byte as usize % PADDED_WIDTH) - 1;
let result_y = (max_byte as usize / PADDED_WIDTH) - 1;
return Coordinate {
x: result_x,
y: result_y,
};
}
// Neighboring positions
let neighbors = [
next_byte - PADDED_WIDTH as u16, // Up
next_byte - 1, // Left
next_byte + 1, // Right
next_byte + PADDED_WIDTH as u16, // Down
];
for &neighbor in &neighbors {
let bit = 1u64 << (neighbor as usize % 64);
let idx = neighbor as usize / 64;
if (*visited.get_unchecked(idx) & bit) == 0 {
*visited.get_unchecked_mut(idx) |= bit;
let neighbor_order = *order_lookup.get_unchecked(neighbor as usize);
if neighbor_order > max_reachable as u16 {
*bfs_stack.get_unchecked_mut(ptr) = neighbor;
ptr += 1;
} else {
let order_idx = (neighbor_order / 64) as usize;
*reachable.get_unchecked_mut(order_idx) |=
1u64 << (neighbor_order % 64);
}
}
}
}
}
}
// If not found, return a default coordinate
Coordinate { x: 0, y: 0 }
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d13p2.rs | 2024/d13p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) as u64 }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
macro_rules! parse2 {
($ptr:ident as $ty:ident) => {{
let n = (*$ptr as $ty - b'0' as $ty);
let d = (*$ptr.add(1) as $ty).wrapping_sub(b'0' as $ty);
$ptr = $ptr.add(2);
10 * n + d
}};
}
macro_rules! parse {
($ptr:ident as $ty:ident) => {{
// TODO: SWAR?
let mut n = 100 * (*$ptr as $ty - b'0' as $ty);
n += 10 * (*$ptr.add(1) as $ty - b'0' as $ty);
n += (*$ptr.add(2) as $ty - b'0' as $ty);
let d = *$ptr.add(3) as $ty;
$ptr = $ptr.add(4);
if d >= b'0' as $ty {
n = 10 * n + (d - b'0' as $ty);
let d = *$ptr as $ty;
$ptr = $ptr.add(1);
if d >= b'0' as $ty {
n = 10 * n + (d - b'0' as $ty);
$ptr = $ptr.add(1);
}
}
n
}};
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut ptr = input.as_ptr().wrapping_sub(1);
let end = input.as_ptr().add(input.len());
let mut tot = 0;
loop {
ptr = ptr.add(13);
let dxa = parse2!(ptr as u32) as i32;
ptr = ptr.add(4);
let dya = parse2!(ptr as u32) as i32;
ptr = ptr.add(13);
let dxb = parse2!(ptr as u32) as i32;
ptr = ptr.add(4);
let dyb = parse2!(ptr as u32) as i32;
ptr = ptr.add(10);
let x = parse!(ptr as u32) as i32;
ptr = ptr.add(3);
let y = parse!(ptr as u32) as i32;
let det = dxa * dyb - dxb * dya;
let d1 = x * dyb - dxb * y;
let q1 = std::intrinsics::unchecked_div(d1, det);
let r1 = std::intrinsics::unchecked_rem(d1, det);
if r1 == 0 {
let d2 = dxa * y - x * dya;
let q2 = std::intrinsics::unchecked_div(d2, det);
let r2 = std::intrinsics::unchecked_rem(d2, det);
if r2 == 0 {
tot += (3 * q1 + q2) as u64;
}
}
if ptr == end {
break;
}
}
tot
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let mut ptr = input.as_ptr().wrapping_sub(1);
let end = input.as_ptr().add(input.len());
let mut tot = 0;
loop {
ptr = ptr.add(13);
let dxa = parse2!(ptr as u64) as i64;
ptr = ptr.add(4);
let dya = parse2!(ptr as u64) as i64;
ptr = ptr.add(13);
let dxb = parse2!(ptr as u64) as i64;
ptr = ptr.add(4);
let dyb = parse2!(ptr as u64) as i64;
ptr = ptr.add(10);
let x = parse!(ptr as u64) as i64 + 10000000000000;
ptr = ptr.add(3);
let y = parse!(ptr as u64) as i64 + 10000000000000;
let det = dxa * dyb - dxb * dya;
let d1 = x * dyb - dxb * y;
let q1 = std::intrinsics::unchecked_div(d1, det);
let r1 = std::intrinsics::unchecked_rem(d1, det);
if r1 == 0 {
let d2 = dxa * y - x * dya;
let q2 = std::intrinsics::unchecked_div(d2, det);
let r2 = std::intrinsics::unchecked_rem(d2, det);
if r2 == 0 {
tot += (3 * q1 + q2) as u64;
}
}
if ptr == end {
break;
}
}
tot
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d11p2.rs | 2024/d11p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u32 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static mut LUT: [u64; 10_000_000] = [0; 10_000_000];
#[cfg_attr(any(target_os = "linux"), link_section = ".text.startup")]
unsafe extern "C" fn __ctor() {
make_d11_lut();
}
#[used]
#[cfg_attr(target_os = "linux", link_section = ".init_array")]
#[cfg_attr(windows, link_section = ".CRT$XCU")]
static __CTOR: unsafe extern "C" fn() = __ctor;
fn make_d11_lut() {
use std::collections::HashMap;
let iters = 75;
let mut levels = vec![HashMap::new(); iters];
fn solve_rec(i: usize, j: usize, levels: &mut [HashMap<usize, usize>]) -> usize {
if i == 0 {
return 1;
}
if let Some(&res) = levels[i - 1].get(&j) {
return res;
}
let res = if j == 0 {
solve_rec(i - 1, 1, levels)
} else if j.ilog10() % 2 == 1 {
let pow10 = 10usize.pow((j.ilog10() + 1) / 2);
solve_rec(i - 1, j / pow10, levels) + solve_rec(i - 1, j % pow10, levels)
} else {
solve_rec(i - 1, j * 2024, levels)
};
levels[i - 1].insert(j, res);
res
}
for j in 0..10_000_000 {
(unsafe { &mut LUT })[j] = solve_rec(iters, j, &mut levels) as _;
}
}
macro_rules! solve {
($input:ident, $lut:literal, $ty:ident) => {{
let lut = LUT.as_ptr();
let input = $input.as_bytes();
let mut ptr = input.as_ptr();
let end = ptr.add(input.len());
let mut tot = 0;
loop {
let mut n = (*ptr - b'0') as usize;
ptr = ptr.add(1);
loop {
let d = (*ptr).wrapping_sub(b'0');
ptr = ptr.add(1);
if d >= 10 {
break;
}
n = 10 * n + d as usize;
}
tot += lut.add(n).read_unaligned();
if ptr == end {
break tot;
}
}
}};
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u32 {
solve!(input, "/d11p1.lut", u32) as u32
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
solve!(input, "/d11p2.lut", u64)
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d17p2.rs | 2024/d17p2.rs | // Original by: alion02
// .
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32, _pext_u64,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
#[inline]
unsafe fn inner1(s: &[u8]) -> &str {
static mut BUF: u8x64 = Simd::from_array([
10,
1,
10,
1,
10,
1,
10,
1,
100,
0,
1,
0,
100,
0,
1,
0,
16,
39,
1,
0,
16,
39,
1,
0,
b'0'.wrapping_neg(),
0,
0,
0,
b'1',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
b',',
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]);
let r: *const u8;
asm!(
"vpbroadcastb {chunk}, [rip + {buf}+24]",
"vpaddb {chunk}, {chunk}, [{ptr} + 12]",
"vpmaddubsw {chunk}, {chunk}, [rip + {buf}]",
"vpmaddwd {chunk}, {chunk}, [rip + {buf}+8]",
"vpackusdw {chunk}, {chunk}, {chunk}",
"vpmaddwd {chunk}, {chunk}, [rip + {buf}+16]",
"vmovd edx, {chunk}",
"movzx {imm1:e}, byte ptr[{ptr} + 65]",
"sub {imm1:e}, {ascii0}",
"vpbroadcastd {chunk}, [rip + {buf}+25]",
"vpcmpeqb {chunk}, {chunk}, [{ptr} + 64]",
"vpmovmskb {imm2:e}, {chunk}",
"tzcnt {imm2:e}, {imm2:e}",
"movzx {imm2:e}, byte ptr[{ptr} + {imm2} + 66]",
"lea {out}, [rip + {buf}+29]",
"20:",
"bextr ecx, edx, {mask:e}",
"xor ecx, {imm1:e}",
"shrx {c:e}, edx, ecx",
"xor ecx, {c:e}",
"xor ecx, {imm2:e}",
"and ecx, 7",
"add ecx, 48",
"mov byte ptr[{out} + {len} - 91], cl",
"add {len:e}, 2",
"shr edx, 3",
"jnz 20b",
imm1 = out(reg) _,
imm2 = out(reg) _,
out("edx") _,
out("ecx") _,
c = out(reg) _,
mask = in(reg) 3 << 8,
chunk = out(xmm_reg) _,
buf = sym BUF,
ptr = inout(reg) s.as_ptr() => _,
len = inout(reg) s.len() => _,
ascii0 = const b'0',
out = out(reg) r,
options(nostack),
);
std::str::from_utf8_unchecked(std::slice::from_raw_parts(r, 17))
}
static LUT: [u64; 1 << 14] = {
let mut lut = [0; 1 << 14];
lut[11844] = 174271416563282;
lut[10364] = 202730212714147;
lut[1780] = 191025017546403;
lut[1428] = 202806544852643;
lut[6172] = 189432989771427;
lut[12228] = 259246506806003;
lut[11860] = 174271403980370;
lut[10492] = 202730346931875;
lut[10708] = 189120954525347;
lut[6868] = 189432876525219;
lut[3828] = 190992268420771;
lut[3476] = 202815134787235;
lut[6300] = 189171097429667;
lut[11532] = 174270842402386;
lut[10620] = 202730615367331;
lut[5876] = 202858726188707;
lut[5524] = 202832314656419;
lut[6428] = 189433392424611;
lut[12260] = 259234225883891;
lut[10748] = 202730883802787;
lut[6900] = 202744693548707;
lut[12020] = 203728106841763;
lut[7924] = 202743298942627;
lut[7572] = 202743898728099;
lut[12276] = 259246498679539;
lut[11916] = 174271345718866;
lut[11004] = 202730078496419;
lut[10644] = 189121157949091;
lut[6804] = 202744691451555;
lut[11924] = 203728104744611;
lut[11668] = 202797954918051;
lut[6812] = 189171231647395;
lut[11812] = 174271408174674;
lut[11132] = 202799737497251;
lut[11828] = 174271412368978;
lut[10676] = 190805422663331;
lut[16116] = 189136842548899;
lut[15764] = 189137442334371;
lut[7068] = 189433660860067;
lut[12212] = 259234217757427;
lut[12220] = 259233547193075;
lut[6725] = 202366621067818;
lut[1653] = 202356708354602;
lut[6157] = 203197932644906;
lut[6173] = 164541160582845;
lut[11293] = 164279024971453;
lut[12741] = 247839653009594;
lut[6741] = 202366625262122;
lut[6285] = 202992055757354;
lut[11421] = 164278764924605;
lut[6757] = 202366618446378;
lut[5749] = 202631586261546;
lut[11549] = 164278496489149;
lut[6773] = 202366623164970;
lut[7573] = 164542125272765;
lut[6557] = 164541017976509;
lut[11677] = 164278899142333;
lut[12797] = 247839539763386;
lut[6661] = 202991746427434;
lut[9845] = 202975183645226;
lut[6669] = 202991774214698;
lut[9621] = 164516454365621;
lut[6685] = 164540221058749;
lut[11805] = 164278228053693;
lut[8957] = 202404828555818;
lut[6677] = 202367015856682;
lut[11893] = 202322348616234;
lut[11653] = 202322936867370;
lut[6797] = 202992189975082;
lut[6813] = 164540892147389;
lut[11933] = 165522963263165;
lut[12693] = 247839661398202;
lut[8613] = 202972175280682;
lut[6693] = 202366627359274;
lut[13941] = 203181342075434;
lut[6941] = 164540489494205;
lut[12061] = 165523634351805;
lut[6709] = 202367025818154;
lut[7069] = 164540623711933;
lut[12189] = 164278630706877;
lut[13309] = 247839002892474;
lut[12725] = 247839648815290;
lut[11718] = 37221263785460;
lut[11390] = 37221871304180;
lut[11734] = 37221261688308;
lut[11518] = 37221468650996;
lut[4086] = 190615597431823;
lut[3510] = 190354906758159;
lut[11750] = 38886108872180;
lut[11646] = 37222005521908;
lut[14718] = 190384709385231;
lut[6462] = 190389435055119;
lut[11766] = 37221267979764;
lut[11774] = 37221334433268;
lut[14846] = 190626778856463;
lut[14838] = 190384609508367;
lut[6590] = 190389300050959;
lut[11902] = 37222273957364;
lut[14726] = 190384623401999;
lut[6718] = 190593310997519;
lut[11670] = 37221270076916;
lut[15102] = 190384433347599;
lut[14742] = 190384615275535;
lut[6846] = 190593446001679;
lut[11686] = 37221276368372;
lut[11702] = 37221274271220;
lut[12286] = 37221737086452;
lut[15358] = 190384113204239;
lut[16374] = 190624228719631;
lut[15798] = 190561065188367;
lut[1143] = 87765778397121;
lut[8319] = 266931276004369;
lut[1655] = 280189034740753;
lut[10367] = 236581377105517;
lut[3191] = 87800138135489;
lut[3703] = 266943355599889;
lut[10495] = 236581108670061;
lut[11991] = 233391028921023;
lut[3831] = 216148338630253;
lut[3479] = 216549846240877;
lut[383] = 87768596969409;
lut[5239] = 87815170521025;
lut[8575] = 266930722356241;
lut[5751] = 266960535469073;
lut[10727] = 236555995274861;
lut[5527] = 216584205979245;
lut[511] = 87768089491393;
lut[503] = 87768066086849;
lut[6263] = 87780816771009;
lut[7287] = 87782958266305;
lut[7799] = 266908995861521;
lut[10751] = 236580836040301;
lut[7575] = 236548287712877;
lut[8831] = 266930990791697;
lut[9847] = 266926175730705;
lut[10631] = 236556005760621;
lut[9975] = 236539226447469;
lut[11807] = 233390776344173;
lut[8599] = 266931037159697;
lut[11895] = 280206214609937;
lut[10647] = 236555999469165;
lut[12023] = 236556406316653;
lut[11935] = 233391044779629;
lut[895] = 87794366773185;
lut[10663] = 236556001566317;
lut[1023] = 87768372238273;
lut[15991] = 266932601404433;
lut[10679] = 236555997372013;
lut[12409] = 109019476330651;
lut[1905] = 105840740174234;
lut[1441] = 105843716614554;
lut[12537] = 109020013201563;
lut[6993] = 105734763776155;
lut[3953] = 105849330108826;
lut[3489] = 105981155568026;
lut[11433] = 107413700225434;
lut[6001] = 105832150239642;
lut[5537] = 106086382266778;
lut[11561] = 107416870455451;
lut[12793] = 109019619953050;
lut[7025] = 105734774294938;
lut[8049] = 105875099912602;
lut[7585] = 105706277661082;
lut[6569] = 105735268690330;
lut[11689] = 107416732707226;
lut[12921] = 109019205798043;
lut[6913] = 105734783666586;
lut[12033] = 108534028601754;
lut[10097] = 108056943298970;
lut[13049] = 109019742668955;
lut[12689] = 109019930331546;
lut[12145] = 105866509978010;
lut[11681] = 109541683456410;
lut[12705] = 109019846445466;
lut[6945] = 105734716557722;
lut[14193] = 109130685122970;
lut[13729] = 136904920099226;
lut[6953] = 136936180680859;
lut[6961] = 105734765873307;
lut[16241] = 109593014864282;
lut[15777] = 109550273391002;
lut[7081] = 105702138980762;
lut[12201] = 108399378442650;
lut[7122] = 47910082096018;
lut[4082] = 47951183653778;
lut[14842] = 47921188613010;
lut[7042] = 47910079998866;
lut[11810] = 90938893795561;
lut[11826] = 90938843463913;
lut[14459] = 258394985014171;
lut[2035] = 265660930925467;
lut[6203] = 258411949917083;
lut[11859] = 109685330781408;
lut[4083] = 265652340990875;
lut[3507] = 265601188299675;
lut[6331] = 258393608225691;
lut[14715] = 258400890594203;
lut[6459] = 258411144610715;
lut[11659] = 109552863562265;
lut[14971] = 267265166222235;
lut[9651] = 265618099733403;
lut[6715] = 258411681481627;
lut[15099] = 258395521885083;
lut[11699] = 265635548038043;
lut[6843] = 258411811505051;
lut[6971] = 265061364597659;
lut[7099] = 258411413046171;
lut
};
#[inline]
unsafe fn inner2(s: &[u8]) -> u64 {
let out: u64;
asm!(
"movzx {out:e}, byte ptr[{ptr} + 73]",
"shl {out:e}, 16",
"xor {out:l}, byte ptr[{ptr} + 65]",
"xor {out}, qword ptr[{ptr} + 74]",
"pext {out}, {out}, {mask}",
"mov {out}, qword ptr[rdx + {out} * 8]",
out = out(reg) out,
out("ecx") _,
inout("rdx") &LUT => _,
ptr = in(reg) s.as_ptr(),
options(nostack),
mask = in(reg) 0x07_00_04_00_07_07_04_07u64,
);
out
}
#[inline]
pub fn part1(s: &str) -> &str {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn run(s: &str) -> u64 {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d05p2.rs | 2024/d05p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
use std::simd::cmp::{SimdPartialEq, SimdPartialOrd};
use std::simd::num::SimdInt;
use std::simd::ptr::SimdMutPtr;
use std::simd::{simd_swizzle, u64x4, u8x32, u8x64, usizex4, Simd};
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
pub fn part1(input: &str) -> u32 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u32 {
unsafe { inner_part2(input) }
}
static NLMASK: [u8; 32] = {
let mut mask = [0; 32];
mask[0 * 6] = b'\n';
mask[1 * 6] = b'\n';
mask[2 * 6] = b'\n';
mask[3 * 6] = b'\n';
mask
};
static MUL_BLOCK: [u8; 32] = {
let mut block = [0; 32];
let mut i = 0;
while i < 4 {
block[6 * i] = 10;
block[6 * i + 1] = 1;
block[6 * i + 3] = 10;
block[6 * i + 4] = 1;
i += 1;
}
block
};
static SWIZZLE_BLOCK: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[6 * i] = 6 * i + 1;
block[6 * i + 3] = 6 * i + 4;
i += 1;
}
block
};
static SWIZZLE_LEFT: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[8 * i] = 6 * i;
i += 1;
}
block
};
static SWIZZLE_RIGHT: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[8 * i] = 6 * i + 3;
i += 1;
}
block
};
#[inline(always)]
unsafe fn read_rules(rules: &mut [u128; 100], iter: &mut std::slice::Iter<u8>) {
loop {
let block = u8x32::from_slice(iter.as_slice().get_unchecked(..32));
if block.simd_eq(u8x32::from_slice(&NLMASK)).any() {
break;
}
let digits = (block - u8x32::splat(b'0')) * u8x32::from_slice(&MUL_BLOCK);
let nums = digits + simd_swizzle!(digits, SWIZZLE_BLOCK);
let left = std::mem::transmute::<_, usizex4>(simd_swizzle!(nums, SWIZZLE_LEFT));
let right = std::mem::transmute::<_, u64x4>(simd_swizzle!(nums, SWIZZLE_RIGHT));
let right_big = right.simd_ge(u64x4::splat(64));
let idx = left * usizex4::splat(2) + (right_big.to_int().cast() & usizex4::splat(1));
let ptr = Simd::splat(rules.as_mut_ptr().cast::<u64>()).wrapping_add(idx);
let shift_amt = right & u64x4::splat(0b111111);
let to_store = u64x4::splat(1) << shift_amt;
for (&ptr, &to_store) in std::iter::zip(ptr.as_array(), to_store.as_array()) {
*ptr |= to_store;
}
*iter = iter.as_slice().get_unchecked(24..).iter();
}
while *iter.as_slice().get_unchecked(0) != b'\n' {
let c = iter.as_slice().get_unchecked(..5);
let d1 = ((c[0] - b'0') as usize * 10) + ((c[1] - b'0') as usize);
let d2 = ((c[3] - b'0') as usize * 10) + ((c[4] - b'0') as usize);
*rules.get_unchecked_mut(d1) |= 1 << d2;
*iter = iter.as_slice().get_unchecked(6..).iter();
}
*iter = iter.as_slice().get_unchecked(1..).iter();
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u32 {
let mut iter = input.as_bytes().iter();
let mut rules = [0u128; 100];
read_rules(&mut rules, &mut iter);
let mut tot = 0;
let mut buf = [0; 24];
let mut buf_len = 0;
let mut mask = 0u128;
'outer: while iter.len() >= 72 {
buf_len = 0;
mask = 0;
let len = 8 + u8x64::from_slice(iter.as_slice().get_unchecked(8..8 + 64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
let mut c_iter = iter.as_slice().get_unchecked(..len + 1).iter();
iter = iter.as_slice().get_unchecked(len + 1..).iter();
while !c_iter.as_slice().is_empty() {
let c = c_iter.as_slice();
let n = (*c.get_unchecked(0) - b'0') * 10 + (*c.get_unchecked(1) - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
if *rules.get_unchecked(n as usize) & mask != 0 {
continue 'outer;
}
mask |= 1 << n;
c_iter = c_iter.as_slice().get_unchecked(3..).iter();
}
tot += *buf.get_unchecked(buf_len / 2) as u32;
}
'outer: while !iter.as_slice().is_empty() {
let c = iter.as_slice();
let n = (*c.get_unchecked(0) - b'0') * 10 + (*c.get_unchecked(1) - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
if *rules.get_unchecked(n as usize) & mask != 0 {
while *iter.as_slice().get_unchecked(2) != b'\n' {
iter = iter.as_slice().get_unchecked(3..).iter();
}
iter = iter.as_slice().get_unchecked(3..).iter();
buf_len = 0;
mask = 0;
continue 'outer;
}
mask |= 1 << n;
if *c.get_unchecked(2) == b'\n' {
tot += *buf.get_unchecked(buf_len / 2) as u32;
buf_len = 0;
mask = 0;
}
iter = iter.as_slice().get_unchecked(3..).iter();
}
tot
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u32 {
let mut iter = input.as_bytes().iter();
let mut rules = [0u128; 100];
read_rules(&mut rules, &mut iter);
let mut tot = 0;
let mut buf = [0; 24];
let mut buf_len = 0;
let mut mask = 0u128;
let mut valid = true;
for c in iter.as_slice().chunks_exact(3) {
let n = (c[0] - b'0') * 10 + (c[1] - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
valid &= *rules.get_unchecked(n as usize) & mask == 0;
mask |= 1 << n;
if c[2] == b'\n' {
if !valid {
for i in 0..buf_len {
let succs = *rules.get_unchecked(*buf.get_unchecked(i) as usize) & mask;
if succs.count_ones() == buf_len as u32 / 2 {
tot += *buf.get_unchecked(i) as u32;
break;
}
}
}
buf_len = 0;
mask = 0;
valid = true;
}
}
tot
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d25p1.rs | 2024/d25p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(fn_align)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
#[repr(align(64))]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(_input: &str) -> u64 {
0
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
#[repr(align(64))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
#[repr(C, align(64))]
struct Data {
list0: [u32x8; 256 / 8],
list1: [u32x8; 256 / 8],
}
static mut DATA: Data = Data {
list0: [u32x8::from_array([u32::MAX; 8]); 256 / 8],
list1: [u32x8::from_array([u32::MAX; 8]); 256 / 8],
};
let data = &mut DATA;
let mut len0 = 0;
let mut len1 = 0;
let mut ptr = input.as_ptr().add(4);
let end = ptr.add(43 * 500);
loop {
let b = ptr.cast::<u8x32>().read_unaligned();
let m = b.simd_eq(u8x32::splat(b'#')).to_bitmask() as u32;
if *ptr == b'#' {
*data.list0.as_mut_ptr().cast::<u32>().add(len0) = m;
len0 += 1;
} else {
*data.list1.as_mut_ptr().cast::<u32>().add(len1) = m;
len1 += 1;
}
ptr = ptr.add(43);
if ptr == end {
break;
}
}
let mut count = i32x8::splat(0);
for i in 0..2 {
let bs = *data.list0.as_ptr().cast::<[u32x8; 12]>().add(i);
for i in 0..250 {
let m = *data.list1.as_ptr().cast::<u32>().add(i);
for b in bs {
count += (b & u32x8::splat(m)).simd_eq(u32x8::splat(0)).to_int();
}
}
}
let bs = *data.list0.as_ptr().cast::<[u32x8; 8]>().add(3);
for i in 0..250 {
let m = *data.list1.as_ptr().cast::<u32>().add(i);
for b in bs {
count += (b & u32x8::splat(m)).simd_eq(u32x8::splat(0)).to_int();
}
}
-count.reduce_sum() as u64
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d01p2.rs | 2024/d01p2.rs | // Original by: doge
const N: usize = 1000;
#[inline(always)]
fn parse_5b(s: &[u8]) -> u32 {
// Optimize by unrolling the loop and using direct subtraction to convert ASCII digits to numbers
unsafe {
let s0 = *s.get_unchecked(0) as u32;
let s1 = *s.get_unchecked(1) as u32;
let s2 = *s.get_unchecked(2) as u32;
let s3 = *s.get_unchecked(3) as u32;
let s4 = *s.get_unchecked(4) as u32;
(s0 * 10000 + s1 * 1000 + s2 * 100 + s3 * 10 + s4) - 533328
}
}
pub fn run(s: &[u8]) -> i64 {
let mut assoc = [0; 2048];
for i in 0..N {
let right = parse_5b(&s[i * 14 + 8..]);
let mut h = right & 2047;
loop {
let entry = &mut assoc[h as usize];
if *entry == 0 {
*entry = right | 1 << 20;
break;
}
if (*entry & 0xfffff) == right {
*entry += 1 << 20;
break;
}
h = (h + 1) & 2047;
}
}
let mut answer = 0;
for i in 0..N {
let left = parse_5b(&s[i * 14..]);
let mut h = left & 2047;
loop {
let entry = assoc[h as usize];
if entry == 0 {
break;
}
if (entry & 0xfffff) == left {
answer += left * (entry >> 20);
}
h = (h + 1) & 2047;
}
}
answer as i64
}
#[test]
fn d1p2() {
assert_eq!(run(include_bytes!("./../input/day1.txt")), 22962826);
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d09p2.rs | 2024/d09p2.rs | // Original by: ameo
#![feature(array_chunks, array_windows, portable_simd, pointer_is_aligned_to)]
// TRICKS:
//
// - Span structure to represent regions of the memory
// - Takes advantage of the fact that free space is always to the right of data in each slot.
// - Uses that trick of adding free space to previous span in the case that the first element is
// removed
// - Uses the fact that data will always be removed from the first element of the vector to make
// this possible
// - SoA for the spans
// - aligned input vector as well as data vectors for counts, free lists, and minivecs which
// facilitates:
// - SIMD parsing
// - de-interleaves sizes + free spaces into separate arrays and writes out with SIMD where
// possible
// - MiniVec; specialized capped-sized-vec that stores stuff inline.
// - uses uninitialized memory for elements that haven't been set
// - all methods custom-built and unsafe with no checks
// - TRIED the fancy const impl that pre-computes the vector here with lens and IDs pre-set, but
// memcpy overhead was greater than savings
// - `start_span_ix_by_needed_size` to keep track of the earliest possible location of a big enough
// free space for every size
// - TRIED the fancy impl. that max's the val of all larger buckets as well, but turned out to be
// way slower (especially when SIMD was enabled)
// - SIMD for finding the first free slot which is large enough
// - dubious benefit; within a few percent in any case.
// - target-cpu=znver3
// - constant-time checksumming
// - `max_unmoved_src_id` accounting
// - allows fully empty chunks at the end to be skipped during checksum computation
// - `finished_digit_count` bookkeeping
// - allows for early exit of the main loop after we've found a stopping place for every char
// - using smaller int sizes for data which allows more items to be considered by SIMD as well as
// reducing memory footprint and potentially reducing cache pressure
// - avoid storing counts inside the minivec at all. instead, reference back to main counts vec
// - this allows size of minivec to go from 32-16 bytes
// - this necessitates a change in a previous opt. instead of setting count to 0 to pop_front, we
// need allocate one extra slot in the counts vec and then set the id to that.
// - SIMD initialization for slot vectors. Amazing stuff. (this put me back in the lead from
// giooschi on the rust discord speed leaderboard)
// - made `start_span_ix_by_needed_size` `[u16; 10]` instead of `[usize; 10]`
// - switch `arr.get_unchecked_mut(x..).fill(u16::MAX)` to `for i in x.. { arr[i] = u16::MAX }`
// which... caused a 20% improvement on the bot??
// - (perhaps in combination with the previous optimization, but I don't think so)
// - micro-optim of the inner free space checking loop, shifting one pointer addition to happen
// lazily only in the case that the first check fails to find any hits in the first SIMD scan.
// - Essentially split the loop into a check start ptr -> (inc + check inc'd) loop instead of
// just an (inc + check) loop
// - Good 7% perf improvement over previous best on the bot. Interestingly, no perf gain
// locally.
// - removed every last bounds check with `get_unchecked/mut()`
// - Actually made things slightly slower on the benchbot, probably because the code seemed to get
// re-structured to be a bit less local, probably because the size of the code after the main
// loop went down after the bounds checks were removed.
// - tuning the vector size for the inner loop
// - turns out that u8x8 faster than u8x16 faster than u8x32
// - u8x8 is pretty slightly - but significantly - faster than u8x16 on both local and benchmark
// machine
// - the same SIMD instruction, operating on 128-bit XMM register, is used -
// - the overhead of fetching just 64 extra bytes seems to outweigh the cost of having less chance
// of finding the needle in the first vector
use std::{
fmt::Display,
simd::{cmp::SimdPartialOrd, u16x16, u16x32, u8x32, u8x64, u8x8},
};
#[cfg(feature = "local")]
pub const INPUT: &'static [u8] = include_bytes!("../inputs/day9.txt");
fn parse_digit(c: u8) -> u8 {
c - 48
}
fn parse_input(input: &[u8]) -> Vec<(u32, u32)> {
let mut it =
input[..input.len() - if input.len() % 2 == 0 { 1 } else { 0 }].array_chunks::<2>();
let mut out = Vec::with_capacity(20_002 / 2);
while let Some(&[size, free]) = it.next() {
out.push((parse_digit(size) as _, parse_digit(free) as _));
}
if let Some(remainder) = it.remainder().get(0) {
out.push((parse_digit(*remainder) as _, 0));
}
out
}
#[repr(C, align(64))]
struct AlignToSixtyFour([u8; 64]);
// adapted from: https://stackoverflow.com/a/60180226/3833068
fn aligned_vec<T>(n_bytes: usize) -> Vec<T> {
assert_eq!(
std::mem::size_of::<AlignToSixtyFour>() % std::mem::size_of::<T>(),
0,
"64 must be divisible by the size of `T` in bytes"
);
// Lazy math to ensure we always have enough.
let n_units = (n_bytes / std::mem::size_of::<AlignToSixtyFour>()) + 1;
let mut aligned: Vec<AlignToSixtyFour> = Vec::with_capacity(n_units);
let ptr = aligned.as_mut_ptr();
let len_units = aligned.len();
let cap_units = aligned.capacity();
std::mem::forget(aligned);
unsafe {
Vec::from_raw_parts(
ptr as *mut T,
(len_units * std::mem::size_of::<AlignToSixtyFour>()) / std::mem::size_of::<T>(),
(cap_units * std::mem::size_of::<AlignToSixtyFour>()) / std::mem::size_of::<T>(),
)
}
}
// sadly, the cost of copying all of the uninitialized bytes that we don't care about is higher than
// being able to set the lengths and indices up front.
// const fn build_empty_slots() -> [MiniVec; 10_000] {
// let mut arr: [MiniVec; 10_000] = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
// let mut i = 0usize;
// loop {
// arr[i].len = 1;
// arr[i].elements[0].id = i as u32;
// i += 1;
// if i == arr.len() {
// break;
// }
// }
// arr
// }
const MAX_ID: usize = 9_999;
fn parse_input_p2(input: &[u8]) -> (Vec<u8>, Vec<u8>, Vec<MiniVec>) {
let id_count = if input.len() % 2 == 1 {
input.len() / 2 + 1
} else {
input.len() / 2
};
let mut orig_counts: Vec<u8> = aligned_vec(id_count + 1);
unsafe { orig_counts.set_len(id_count + 1) };
unsafe { *orig_counts.get_unchecked_mut(MAX_ID + 1) = 0 };
let mut empty_spaces: Vec<u8> = aligned_vec(id_count);
unsafe { empty_spaces.set_len(id_count) };
let mut slots: Vec<MiniVec> = aligned_vec(id_count * std::mem::size_of::<MiniVec>()); // Vec::with_capacity(id_count);
unsafe { slots.set_len(id_count) };
// initialize the memory layout for the minivecs manually using SIMD.
//
// this sets them all up to have a length of one with a single element corresponding to file index
// `i` as the first and only element.
const CHUNK_SIZE: usize = 4;
debug_assert_eq!(slots.len() % CHUNK_SIZE, 0);
unsafe {
let data: [u16; 32] = std::mem::transmute([
MiniVec {
len: 1,
elements: [
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot { id: 1 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot { id: 2 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot { id: 3 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
]);
let mut data = u16x32::from_array(data);
let to_add: [u16; 32] = std::mem::transmute([
MiniVec {
len: 0,
elements: [
Slot {
id: CHUNK_SIZE as u16,
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 0,
elements: [
Slot {
id: CHUNK_SIZE as u16,
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 0,
elements: [
Slot {
id: CHUNK_SIZE as u16,
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 0,
elements: [
Slot {
id: CHUNK_SIZE as u16,
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
]);
assert_eq!(std::mem::size_of::<MiniVec>(), 16);
assert_eq!(
std::mem::size_of::<MiniVec>() * 2,
std::mem::size_of::<u16x16>()
);
assert_eq!(
std::mem::size_of::<MiniVec>() * 4,
std::mem::size_of::<u16x32>()
);
let to_add = u16x32::from_array(to_add);
let start = slots.as_mut_ptr() as *mut u16x32;
for chunk_ix in 0..(slots.len() / CHUNK_SIZE) {
let out_ptr = start.add(chunk_ix);
out_ptr.write(data);
data += to_add;
debug_assert_eq!(
&slots[chunk_ix * 2..chunk_ix * 2 + 4],
&[
MiniVec {
len: 1,
elements: [
Slot {
id: (chunk_ix * 2 + 0) as u16
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot {
id: (chunk_ix * 2 + 1) as u16
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot {
id: (chunk_ix * 2 + 2) as u16
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
},
MiniVec {
len: 1,
elements: [
Slot {
id: (chunk_ix * 2 + 3) as u16
},
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
Slot { id: 0 },
],
padding: 0,
}
]
)
}
// for i in 0..id_count {
// slots.get_unchecked_mut(i).len = 1;
// slots.get_unchecked_mut(i).elements[0].id = i as _;
// }
}
debug_assert!(input.as_ptr().is_aligned_to(std::mem::align_of::<u8x64>()));
const VECTOR_LEN: usize = 32;
const STORE_VECTOR_LEN: usize = VECTOR_LEN / 2;
let batch_count = input.len() / VECTOR_LEN;
for batch_ix in 0..batch_count {
let vec: u8x32 =
unsafe { std::ptr::read(input.as_ptr().add(batch_ix * VECTOR_LEN) as *const _) };
// convert from ascii digits to bytes representing the digit ('0' -> 0)
let converted = vec - u8x32::splat(48);
// split out from size,free,size,free to ([size,size], [free,free])
let (sizes, frees) = converted.deinterleave(converted);
// the de-interleave duplicates the results, so keeping only the first half is correct
let sizes = sizes.resize::<STORE_VECTOR_LEN>(STORE_VECTOR_LEN as u8);
let frees = frees.resize::<STORE_VECTOR_LEN>(STORE_VECTOR_LEN as u8);
unsafe {
let frees_ptr = empty_spaces.as_mut_ptr().add(batch_ix * STORE_VECTOR_LEN) as *mut _;
*frees_ptr = frees;
let orig_counts_ptr =
orig_counts.as_mut_ptr().add(batch_ix * STORE_VECTOR_LEN) as *mut _;
*orig_counts_ptr = sizes;
}
}
/*
if cfg!(feature = "local") && input.len() % 2 != 0 {
let batch_handled_count = batch_count * VECTOR_LEN;
let mut it = input[batch_handled_count..input.len() - if input.len() % 2 == 0 { 1 } else { 0 }]
.array_chunks::<2>();
let mut id = STORE_VECTOR_LEN * batch_count;
while let Some(&[size, free]) = it.next() {
let size = parse_digit(size);
let free = parse_digit(free);
unsafe {
*empty_spaces.get_unchecked_mut(id) = free;
*orig_counts.get_unchecked_mut(id) = size;
}
id += 1;
}
if let Some(remainder) = it.remainder().get(0) {
let size = parse_digit(*remainder);
unsafe {
*empty_spaces.get_unchecked_mut(id) = 0;
*orig_counts.get_unchecked_mut(id) = size;
}
}
} else if cfg!(feature = "local") {
assert!(input.len() % VECTOR_LEN == 0);
// we'd don't need to handle converting the newline that we parsed as the last character into a
// 0 to indicate that there are zero empty slots at the end.
//
// however, there is no situation where we'd need to move anything into the last slot, so who
// cares how big the empty space is.
// let last_id = empty_spaces.len() - 1;
// unsafe {
// *empty_spaces.get_unchecked_mut(last_id) = 0;
// }
}
*/
(orig_counts, empty_spaces, slots)
}
fn compute_fs(input: &[(u32, u32)]) -> Vec<Option<u32>> {
let mut fs = Vec::new();
for (id, (size, free)) in input.iter().enumerate() {
for _ in 0..*size {
fs.push(Some(id as u32));
}
for _ in 0..*free {
fs.push(None);
}
}
fs
}
pub fn part1(input: &[u8]) -> usize {
let input = parse_input(input);
let mut fs = compute_fs(&input);
let mut dst_ix = 0usize;
for src_ix in (0..fs.len()).rev() {
let Some(id) = fs[src_ix] else { continue };
if dst_ix >= src_ix {
break;
}
while fs[dst_ix].is_some() {
dst_ix += 1;
if dst_ix >= src_ix {
break;
}
}
fs[dst_ix] = Some(id);
fs[src_ix] = None;
dst_ix += 1;
if dst_ix >= src_ix {
break;
}
}
let mut out = 0usize;
for i in 0..fs.len() {
let Some(id) = fs[i] else {
continue;
};
out += i * id as usize;
}
out
}
#[repr(align(2))]
#[derive(Debug, Clone, Copy, PartialEq)]
struct Slot {
pub id: u16,
// count is elided here because it can be referred back to in the original counts array, saving
// space and work.
}
impl Slot {
pub fn count(&self, orig_counts: &[u8]) -> u8 {
unsafe { *orig_counts.get_unchecked(self.id as usize) }
}
}
#[repr(align(16))]
#[derive(Clone, Debug, PartialEq)]
struct MiniVec {
pub len: u16,
pub elements: [Slot; 6],
pub padding: u16,
}
impl MiniVec {
fn push(&mut self, item: Slot) {
unsafe {
*self.elements.get_unchecked_mut(self.len as usize) = item;
}
self.len += 1;
debug_assert!(self.len as usize <= self.elements.len());
}
fn pop_front(&mut self) {
// let out = self.elements[0];
// for i in 1..self.len {
// unsafe {
// *self.elements.get_unchecked_mut(i as usize - 1) = self.elements[i as usize];
// }
// }
// self.len -= 1;
// we should only ever mutate the vector once
debug_assert!(self.elements[0].id != MAX_ID as u16 + 1);
// this is a nice trick I came up with to accomplish the equivalent
self.elements[0].id = MAX_ID as u16 + 1;
}
fn as_slice(&self) -> &[Slot] {
unsafe { self.elements.get_unchecked(..self.len as usize) }
}
}
const ADD_FACTORIAL_LUT: [usize; 11] = [
0,
0,
1,
2 + 1,
3 + 2 + 1,
4 + 3 + 2 + 1,
5 + 4 + 3 + 2 + 1,
6 + 5 + 4 + 3 + 2 + 1,
7 + 6 + 5 + 4 + 3 + 2 + 1,
8 + 7 + 6 + 5 + 4 + 3 + 2 + 1,
9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1,
];
impl Slot {
fn checksum(&self, total_prev: &mut usize, orig_counts: &[u8]) -> usize {
// naive impl:
// (0..self.count)
// .map(|i| (total_prev + i as usize) * self.id as usize)
// .sum::<usize>()
// So, this condenses down to a sum of the following:
//
// (total_prev + 0) * id
// (total_prev + 1) * id
// (total_prev + 2) * id
// ...
// (total_prev + (count - 1)) * id
//
// the `total_prev` part can be split out:
// total_prev * self.count * id
//
// leaving that base plus a sum of the following:
//
// 0 * id
// 1 * id
// 2 * id
// ...
// (count - 1) * id
//
// this reduces to (0 + 1 + 2 + ... + (count - 1)) * id
//
// and since count is always [0,9], we can use a tiny LUT for this which makes this whole
// checksum essentially constant time
let count = self.count(orig_counts) as usize;
let checksum = *total_prev * count * self.id as usize
+ unsafe { *ADD_FACTORIAL_LUT.get_unchecked(count) } * self.id as usize;
*total_prev += count;
checksum
}
}
pub fn part2(raw_input: &[u8]) -> usize {
let (counts, mut empty_spaces, mut slots) = parse_input_p2(raw_input);
fn checksum(
slots: &[Slot],
empty_space: u8,
total_prev: &mut usize,
orig_counts: &[u8],
) -> usize {
let mut sum = 0usize;
for slot in slots {
sum += slot.checksum(total_prev, orig_counts);
}
*total_prev += empty_space as usize;
sum
}
let mut start_span_ix_by_needed_size: [u16; 10] = [0; 10];
let mut finished_digit_count = 0usize;
// we keep track of the highest span that still has a value in it.
//
// this allows us to skip iterating over fully empty spans at the end when computing the checksum
let mut max_unmoved_src_id = 0;
'outer: for src_id in (0..=MAX_ID).rev() {
let src_count = unsafe { *counts.get_unchecked(src_id) };
let start_ix =
unsafe { *start_span_ix_by_needed_size.get_unchecked(src_count as usize) } as usize;
// we can only move elements to the left
if start_ix >= src_id {
if start_ix != u16::MAX as usize {
max_unmoved_src_id = max_unmoved_src_id.max(src_id);
debug_assert!(slots[max_unmoved_src_id + 1..].iter().all(|s| s
.as_slice()
.is_empty()
|| s.as_slice()
.iter()
.all(|s| s.id == 0 || s.count(&counts) == 0)));
finished_digit_count += 1;
if finished_digit_count == 9 {
debug_assert_eq!(
start_span_ix_by_needed_size[0], 0,
"there are never zero-size files in the inputs apparently"
);
break;
}
// mark this finished and all bigger digits too
// unsafe {
// start_span_ix_by_needed_size
// .get_unchecked_mut(src_count as usize..10)
// .fill(u16::MAX);
// }
// this is faster than above and creates huge diff in the resulting assembly across the
// whole binary, although the callsite looks almost identical with a `memset` still getting
// generated.
//
// also, `get_unchecked_mut` generates idential code; bounds checks are elided automatically
// somehow
for i in src_count as usize..10 {
start_span_ix_by_needed_size[i] = u16::MAX;
}
}
continue;
}
let src_id = src_id as u16;
let start_ptr = unsafe { empty_spaces.as_ptr().add(start_ix) };
let mut cur_ptr = start_ptr;
let mut cur_offset = 0usize;
let mut dst_span_ix = loop {
const VEC_SIZE: usize = 8usize;
// let end_ix = start_ix + cur_offset + VEC_SIZE;
// same caveat as before. For a 100% correct implementation for all possible inputs, we'd
// need to handle manually checking the tail here but I'm leaving that out
//
// I could leave this off if I wanted to and it wouldn't be an issue...
// if end_ix > input.len() - VEC_SIZE {
// start_span_ix_by_needed_size[src_count as usize] = usize::MAX;
// finished_digit_count += 1;
// max_unmoved_src_id = max_unmoved_src_id.max(src_id as usize);
// continue 'outer;
// }
let empty_spaces_v: u8x8 = unsafe { std::ptr::read_unaligned(cur_ptr as *const _) };
debug_assert_eq!(empty_spaces_v.len(), VEC_SIZE);
let mask = empty_spaces_v.simd_ge(u8x8::splat(src_count));
match mask.first_set() {
Some(i) => {
let dst_span_ix = start_ix + cur_offset + i;
if dst_span_ix >= src_id as usize {
unsafe {
*start_span_ix_by_needed_size.get_unchecked_mut(src_count as usize) =
u16::MAX
};
finished_digit_count += 1;
max_unmoved_src_id = max_unmoved_src_id.max(src_id as usize);
continue 'outer;
}
debug_assert!(empty_spaces[dst_span_ix] >= src_count);
break dst_span_ix;
}
None => {
cur_ptr = unsafe { cur_ptr.add(VEC_SIZE) };
cur_offset += VEC_SIZE
}
}
};
let dst_slots: &mut MiniVec = unsafe { slots.get_unchecked_mut(dst_span_ix) };
max_unmoved_src_id = max_unmoved_src_id.max(dst_span_ix);
dst_slots.push(Slot { id: src_id });
let new_empty_space = unsafe { *empty_spaces.get_unchecked(dst_span_ix) - src_count };
unsafe { *empty_spaces.get_unchecked_mut(dst_span_ix) = new_empty_space };
// no way we could fit more of this size into this span, so might as well move on to the next
// one before continuing to loop
if new_empty_space < src_count {
dst_span_ix += 1;
}
unsafe {
*start_span_ix_by_needed_size.get_unchecked_mut(src_count as usize) = dst_span_ix as u16
};
// \/ this code uses the fact that if a span of size `src_count` can't fit before `dst_span_ix`,
// then no bigger span could either.
//
// However, it turns out to make things slower - especially when compiling with
// `target-cpu=native`. That causes some fancy SIMD that performs this operation using masks
// and whatnot to be emitted, but that turns out to be way slower than the scalar version.
//
// Anyway, just skipping all this work here seems to be the fastest method of them all, probably
// because our SIMD free slot search is fast enough to make up for the savings of doing the more
// fancy accounting after the bookkeeping overhead.
//
// for i in src_count as usize..10 {
// start_span_ix_by_needed_size[i] = start_span_ix_by_needed_size[i].max(dst_span_ix);
// }
// the element we're removing is at the first index of the array since any others added to this
// span will have been put after it
let src_slots = unsafe { slots.get_unchecked_mut(src_id as usize) };
// debug_assert_eq!(src_slots.elements[0].id, src_id);
unsafe { *empty_spaces.get_unchecked_mut(src_id as usize - 1) += src_count };
src_slots.pop_front();
}
let mut out = 0usize;
let mut total_prev = 0usize;
for (slot, &empty_count) in unsafe { slots.get_unchecked_mut(..=max_unmoved_src_id) }
.iter()
.zip(unsafe { empty_spaces.get_unchecked_mut(..=max_unmoved_src_id) }.iter())
{
out += checksum(slot.as_slice(), empty_count, &mut total_prev, &counts);
}
out
}
#[cfg(feature = "local")]
pub fn solve() {
use crate::helpers::leak_to_page_aligned;
let aligned_input = leak_to_page_aligned(INPUT);
let out = part1(aligned_input);
println!("Part 1: {}", out);
let out = part2(aligned_input);
println!("Part 2: {}", out);
}
pub fn run(input: &[u8]) -> impl Display {
part2(input)
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d24p1.rs | 2024/d24p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
// pub fn run(input: &str) -> &'static str {
// part2(input)
// }
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> &'static str {
unsafe { inner_part2(input) }
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut xids = [u8::MAX; 45];
let mut yids = [u8::MAX; 45];
let mut ptr = input.as_ptr();
for i in 0..45 {
xids[i] = (*ptr.add(5) - b'0') + 46;
ptr = ptr.add(7);
}
for i in 0..45 {
yids[i] = (*ptr.add(5) - b'0') + 46;
ptr = ptr.add(7);
}
ptr = ptr.add(1);
let mut node_to_id = [u8::MAX; 23 * 26 * 26];
let mut next_id = 48;
macro_rules! get_id {
($a:ident, $b:ident, $c:ident) => {{
let node =
26 * 26 * ($a - b'a' as usize) + 26 * ($b - b'a' as usize) + ($c - b'a' as usize);
let mut id = *node_to_id.get_unchecked(node);
if id == u8::MAX {
id = next_id;
*node_to_id.get_unchecked_mut(node) = id;
next_id += 1;
}
id
}};
}
static mut OPS: [[u8; 3]; 224] = {
let mut ops = [[u8::MAX; 3]; 224];
ops[46] = [46, 0, 46];
ops[47] = [47, 0, 47];
ops
};
let ops = &mut OPS;
let end = input.as_ptr().add(input.len());
loop {
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let (n, op, m) = if a == b'x' as usize {
let idx = 10 * (b - b'0' as usize) + (c - b'0' as usize);
let n = *xids.get_unchecked(idx);
let m = *yids.get_unchecked(idx);
let op = (*ptr == b'X') as u8;
ptr = ptr.add(11);
(n, op, m)
} else if a == b'y' as usize {
let idx = 10 * (b - b'0' as usize) + (c - b'0' as usize);
let n = *yids.get_unchecked(idx);
let m = *xids.get_unchecked(idx);
let op = (*ptr == b'X') as u8;
ptr = ptr.add(11);
(n, op, m)
} else {
let n = get_id!(a, b, c);
let op = *ptr;
let op = if op == b'O' {
ptr = ptr.add(3);
2
} else {
ptr = ptr.add(4);
(op == b'X') as u8
};
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(7);
let m = get_id!(a, b, c);
(n, op, m)
};
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let out = if a == b'z' as usize {
(10 * (b - b'0' as usize) + (c - b'0' as usize)) as u8
} else {
get_id!(a, b, c)
};
*ops.get_unchecked_mut(out as usize) = [n, op, m];
if ptr == end {
break;
}
}
let mut values = [u8::MAX; 224];
values[46] = 0;
values[47] = 1;
let mut out = 0;
for z in 0..46 {
macro_rules! calc_rec {
(force [fuel: $($fuel:tt)*] $n:expr) => {{
let n = $n as usize;
let [l, op, r] = *ops.get_unchecked(n);
let l = calc_rec!([fuel: $($fuel)*] l);
let r = calc_rec!([fuel: $($fuel)*] r);
match op {
0 => l & r,
1 => l ^ r,
2 => l | r,
_ => std::hint::unreachable_unchecked(),
}
}};
([fuel:] $n:expr) => {
*values.get_unchecked($n as usize)
};
([fuel: c $($rest:tt)*] $n:expr) => {{
let n = $n as usize;
let v = calc_rec!(force [fuel: $($rest)*] n);
*values.get_unchecked_mut(n) = v;
v
}};
([fuel: f $($rest:tt)*] $n:expr) => {{
let n = $n as usize;
let mut v = *values.get_unchecked(n);
if v == u8::MAX {
v = calc_rec!(force [fuel: $($rest)*] n);
*values.get_unchecked_mut(n) = v;
}
v
}};
}
out |= (calc_rec!(force [fuel: f f f f] z) as u64) << z;
}
out
}
static mut PART2_OUT: [u8; 8 * 3 + 7] = [b','; 8 * 3 + 7];
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> &'static str {
let input = input.as_bytes();
let mut node_to_id = [u8::MAX; 23 * 26 * 26];
let mut id_to_node = [u16::MAX; 222];
let mut next_id = 46;
static mut XYOPS: [[u8; 2]; 45] = [[u8::MAX; 2]; 45];
let mut xyops = &mut XYOPS;
static mut OPS: [[[u8; 2]; 2]; 222] = {
let mut ops = [[[u8::MAX; 2]; 2]; 222];
let mut i = 0;
while i < 46 {
ops[i] = [[u8::MAX - 1; 2]; 2];
i += 1;
}
ops
};
let ops = &mut OPS;
macro_rules! get_id {
($a:ident, $b:ident, $c:ident) => {{
let node =
26 * 26 * ($a - b'a' as usize) + 26 * ($b - b'a' as usize) + ($c - b'a' as usize);
let mut id = *node_to_id.get_unchecked(node);
if id == u8::MAX {
id = next_id;
*node_to_id.get_unchecked_mut(node) = id;
*id_to_node.get_unchecked_mut(id as usize) = node as u16;
next_id += 1;
}
id
}};
}
let mut ptr = input.as_ptr().add(631);
let end = input.as_ptr().add(input.len());
loop {
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
if a == b'x' as usize || a == b'y' as usize {
let n = 10 * (b - b'0' as usize) + (c - b'0' as usize);
let off = (*ptr == b'X') as usize;
ptr = ptr.add(11);
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let out = if a == b'z' as usize {
(10 * (b - b'0' as usize) + (c - b'0' as usize)) as u8
} else {
get_id!(a, b, c)
};
*xyops.get_unchecked_mut(n).get_unchecked_mut(off) = out;
} else {
let n = get_id!(a, b, c);
let op = *ptr;
ptr = ptr.add(3);
if op != b'O' {
ptr = ptr.add(1);
}
let off = (op == b'X') as usize;
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(7);
let m = get_id!(a, b, c);
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let out = if a == b'z' as usize {
(10 * (b - b'0' as usize) + (c - b'0' as usize)) as u8
} else {
get_id!(a, b, c)
};
if op == b'O' {
*ops.get_unchecked_mut(n as usize).get_unchecked_mut(1) = [u8::MAX; 2];
*ops.get_unchecked_mut(m as usize).get_unchecked_mut(1) = [u8::MAX; 2];
}
*ops.get_unchecked_mut(n as usize).get_unchecked_mut(off) = [m, out];
*ops.get_unchecked_mut(m as usize).get_unchecked_mut(off) = [n, out];
}
if ptr == end {
break;
}
}
let mut out = [u16::MAX; 8];
let mut out_len = 0;
let mut carry = xyops[0][0] as usize;
for n in 1..45 {
let act_carry_1 = xyops[n][0] as usize;
let act_res = xyops[n][1] as usize;
let exp_res = ops.get_unchecked(carry)[0][0] as usize;
let act_carry_2 = ops.get_unchecked(carry)[0][1] as usize;
let act_z = ops.get_unchecked(carry)[1][1] as usize;
if act_z >= 46 {
*out.get_unchecked_mut(out_len) = act_z as u16;
*out.get_unchecked_mut(out_len + 1) = n as u16;
out_len += 2;
debug_assert!(act_z < 222);
debug_assert!(n < 222);
if ops.get_unchecked(act_carry_1)[1] == [u8::MAX; 2] {
carry = ops.get_unchecked(act_carry_1)[0][1] as usize;
} else {
carry = ops.get_unchecked(act_carry_2)[0][1] as usize;
}
if carry == n {
carry = act_z;
}
} else {
if act_res != exp_res {
*out.get_unchecked_mut(out_len) = act_res as u16;
out_len += 1;
debug_assert!(act_res < 222);
}
if ops.get_unchecked(act_carry_1)[1] != [u8::MAX; 2] {
*out.get_unchecked_mut(out_len) = act_carry_1 as u16;
out_len += 1;
debug_assert!(act_carry_1 < 222);
} else {
carry = ops.get_unchecked(act_carry_1)[0][1] as usize;
}
if ops.get_unchecked(act_carry_2)[1] != [u8::MAX; 2] {
*out.get_unchecked_mut(out_len) = act_carry_2 as u16;
out_len += 1;
debug_assert!(act_carry_2 < 222);
} else {
carry = ops.get_unchecked(act_carry_2)[0][1] as usize;
}
if out_len & 1 != 0 {
*out.get_unchecked_mut(out_len) = carry as u16;
out_len += 1;
debug_assert!(carry < 222);
carry = *out.get_unchecked(out_len - 2) as usize;
}
}
if out_len == 8 {
break;
}
}
debug_assert_eq!(out_len, 8);
let mut out_chr = [[u8::MAX; 3]; 8];
for i in 0..8 {
let n = out[i];
if n < 46 {
out_chr[i] = [b'z', b'0' + n as u8 / 10, b'0' + n as u8 % 10];
} else {
let n = id_to_node[n as usize];
out_chr[i] = [
b'a' + (n / (26 * 26)) as u8,
b'a' + (n / 26 % 26) as u8,
b'a' + (n % 26) as u8,
];
}
}
out_chr.sort_unstable();
for i in 0..8 {
PART2_OUT[4 * i + 0] = out_chr[i][0];
PART2_OUT[4 * i + 1] = out_chr[i][1];
PART2_OUT[4 * i + 2] = out_chr[i][2];
}
std::str::from_utf8_unchecked(&PART2_OUT)
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d21p2.rs | 2024/d21p2.rs | // Original by: bendn
#![allow(warnings)]
#![allow(
confusable_idents,
uncommon_codepoints,
non_upper_case_globals,
internal_features,
mixed_script_confusables,
static_mut_refs,
incomplete_features
)]
#![feature(
iter_repeat_n,
slice_swap_unchecked,
generic_const_exprs,
iter_array_chunks,
if_let_guard,
get_many_mut,
maybe_uninit_uninit_array,
once_cell_get_mut,
iter_collect_into,
hint_assert_unchecked,
let_chains,
anonymous_lifetime_in_impl_trait,
array_windows,
maybe_uninit_array_assume_init,
vec_into_raw_parts,
try_blocks,
slice_take,
portable_simd,
test,
slice_as_chunks,
array_chunks,
slice_split_once,
core_intrinsics
)]
use std::ops::Neg;
mod util {
#![allow(non_snake_case, unused_macros)]
use rustc_hash::FxHashMap as HashMap;
use rustc_hash::FxHashSet as HashSet;
use std::{
cmp::Reverse,
collections::{hash_map::Entry, BinaryHeap},
fmt::{Debug, Display, Write},
hash::Hash,
mem::swap,
ops::RangeInclusive,
str::FromStr,
};
pub mod prelude {
#[allow(unused_imports)]
pub(crate) use super::{bits, dang, leek, mat, shucks, C};
pub use super::{
even, gcd, gt, l, lcm, lt, nail, pa, r, rand, reading, reading::Ext, sort, DigiCount,
Dir, FilterBy, FilterBy3, GreekTools, IntoCombinations, IntoLines, IterͶ,
NumTupleIterTools, ParseIter, Printable, Skip, TakeLine, TupleIterTools2,
TupleIterTools2R, TupleIterTools3, TupleUtils, UnifiedTupleUtils, UnsoundUtilities,
Widen, Ͷ, Α, Κ, Λ, Μ,
};
pub use itertools::izip;
pub use itertools::Itertools;
pub use rustc_hash::FxHashMap as HashMap;
pub use rustc_hash::FxHashSet as HashSet;
pub use std::{
cmp::Ordering::*,
cmp::{max, min},
collections::{hash_map::Entry, VecDeque},
fmt::{Debug, Display},
hint::black_box as boxd,
io::{self, Read, Write},
iter,
mem::{replace as rplc, swap, transmute as rint},
ops::Range,
};
}
macro_rules! C {
($obj:ident.$what:ident$($tt:tt)+) => {{
let x = &mut $obj.$what;
C!( x$($tt)+ )
}};
(&$buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked($n)
}
}};
($buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
*unsafe {
$buf.get_unchecked($n)
}
}};
(&mut $buf:ident[$n:expr]) => {{
#[allow(unused_unsafe)]
unsafe {
$buf.get_unchecked_mut($n)
}
}};
($buf:ident[$a:expr] = $rbuf:ident[$b:expr]) => {
*unsafe { $buf.get_unchecked_mut($a) } = unsafe { *$rbuf.get_unchecked($b) }
};
($buf:ident[$n:expr] = $e:expr) => {
*unsafe { $buf.get_unchecked_mut($n) } = $e
};
($buf:ident[$a:expr][$b:expr]) => {
unsafe { *$buf.get_unchecked($a).get_unchecked($b) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra) }
};
($buf:ident[$a:expr][$b:expr] = $rbuf:ident[$ra:expr][$rb:expr]) => {
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } =
unsafe { *$rbuf.get_unchecked($ra).get_unchecked($rb) }
};
($buf:ident[$a:expr][$b:expr] = $c:expr) => {{
#[allow(unused_unsafe)]
{
*unsafe { $buf.get_unchecked_mut($a).get_unchecked_mut($b) } = unsafe { $c }
}
}};
}
pub(crate) use C;
macro_rules! shucks {
() => {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
($fmt:literal $(, $args:expr)* $(,)?) => {
if cfg!(debug_assertions) {
unreachable!($fmt $(, $args)*);
} else {
unsafe { std::hint::unreachable_unchecked() }
}
};
(if $x:expr) => {
if $x {
if cfg!(debug_assertions) {
unreachable!();
} else {
unsafe { std::hint::unreachable_unchecked() }
}
}
};
}
pub(crate) use shucks;
macro_rules! dang {
() => {
panic!()
};
}
pub(crate) use dang;
macro_rules! leek {
($($allocation:ident)+) => {
$(std::mem::forget($allocation);)+
};
}
pub(crate) use leek;
macro_rules! mat {
($thing:ident { $($what:pat => $b:expr,)+ }) => {
match $thing { $($what => { $b })+ _ => shucks!() }
};
}
pub(crate) use mat;
#[cfg(target_feature = "avx2")]
unsafe fn count_avx<const N: usize>(hay: &[u8; N], needle: u8) -> usize {
use std::arch::x86_64::*;
let find = _mm256_set1_epi8(needle as i8);
let mut counts = _mm256_setzero_si256();
for i in 0..(N / 32) {
counts = _mm256_sub_epi8(
counts,
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(i * 32) as *const _),
find,
),
);
}
const MASK: [u8; 64] = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
];
counts = _mm256_sub_epi8(
counts,
_mm256_and_si256(
_mm256_cmpeq_epi8(
_mm256_loadu_si256(hay.as_ptr().add(N - 32) as *const _),
find,
),
_mm256_loadu_si256(MASK.as_ptr().add(N % 32) as *const _),
),
);
let sums = _mm256_sad_epu8(counts, _mm256_setzero_si256());
(_mm256_extract_epi64(sums, 0)
+ _mm256_extract_epi64(sums, 1)
+ _mm256_extract_epi64(sums, 2)
+ _mm256_extract_epi64(sums, 3)) as usize
}
pub fn count<const N: usize>(hay: &[u8; N], what: u8) -> usize {
#[cfg(target_feature = "avx2")]
return unsafe { count_avx(hay, what) };
#[cfg(not(target_feature = "avx2"))]
hay.iter().filter(|&&x| x == what).count()
}
pub fn lcm(n: impl IntoIterator<Item = u64>) -> u64 {
let mut x = n.into_iter();
let mut lcm = x.by_ref().next().expect("cannot compute LCM of 0 numbers");
let mut gcd;
for x in x {
gcd = crate::util::gcd(x, lcm);
lcm = (lcm * x) / gcd;
}
lcm
}
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum Dir {
N = b'U',
E = b'R',
S = b'D',
W = b'L',
}
pub struct UnionFind {
p: Vec<usize>,
s: Vec<usize>,
}
impl UnionFind {
pub fn new(size: usize) -> Self {
Self {
s: vec![1; size],
p: (0..size).collect(),
}
}
fn reset(&mut self) {
self.s.fill(1);
self.p
.iter_mut()
.enumerate()
.for_each(|(idx, val)| *val = idx);
}
pub fn find(&mut self, key: usize) -> usize {
if self.p[key] == key {
return key;
}
let parent = self.find(self.p[key]);
self.p[key] = parent;
parent
}
pub fn union(&mut self, a: usize, b: usize) -> bool {
let α = self.find(a);
let β = self.find(b);
if α == β {
return false;
}
let a = self.s[α];
let b = self.s[β];
if a >= b {
self.s[α] += b;
self.p[β] = α;
} else {
self.s[β] += a;
self.p[α] = β;
}
true
}
fn group_size(&self, group: usize) -> usize {
self.s[group]
}
}
pub trait UnsoundUtilities<T> {
fn ψ(self) -> T;
}
impl<T> UnsoundUtilities<T> for Option<T> {
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_none() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
impl<T, E> UnsoundUtilities<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn ψ(self) -> T {
if cfg!(debug_assertions) && self.is_err() {
panic!();
}
unsafe { self.unwrap_unchecked() }
}
}
pub struct LMap<K, V>(HashMap<K, V>, fn(K) -> V)
where
K: Eq + Hash + Copy;
impl<K: Ord + Eq + Debug + Hash + Copy, V: Copy + Debug> LMap<K, V> {
pub fn new(f: fn(K) -> V) -> Self {
Self {
0: HashMap::default(),
1: f,
}
}
pub fn with_cap(f: fn(K) -> V, cap: usize) -> Self {
Self {
0: HashMap::with_capacity_and_hasher(cap, rustc_hash::FxBuildHasher::default()),
1: f,
}
}
pub fn get(&mut self, k: K) -> V {
if let Some(x) = self.0.get(&k) {
return *x;
}
// let mut ks = self.0.keys().collect::<Vec<_>>();
// ks.sort();
// println!("{ks:?}");
let elm = self.1(k);
self.0.insert(k, elm);
elm
}
}
macro_rules! memoize {
(|$pat:pat_param in $in:ty| -> $out:ty $body:block; $arg:expr) => {{
static mut MEMOIZER: std::sync::OnceLock<crate::util::LMap<$in, $out>> =
std::sync::OnceLock::new();
unsafe {
MEMOIZER.get_mut_or_init(|| crate::util::LMap::new(|$pat: $in| -> $out { $body }))
}
.get($arg)
}};
(|$pat:pat_param in $in:ty| -> $out:ty $body:block; $arg:expr; with cap $cap:literal) => {{
static mut MEMOIZER: std::sync::OnceLock<crate::util::LMap<$in, $out>> =
std::sync::OnceLock::new();
unsafe {
MEMOIZER.get_mut_or_init(|| {
crate::util::LMap::with_cap(|$pat: $in| -> $out { $body }, $cap)
})
}
.get($arg)
}};
}
pub(crate) use memoize;
pub fn countg_with_check<N: Debug + PartialEq + Hash + Eq + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
ok: &mut impl Fn(N, N) -> bool,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
) {
if end(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if ok(start, x) {
// println!("\"{start:?}\" -> \"{x:?}\"");
countg_with_check(x, graph, ok, sum, end);
}
})
.Θ();
}
}
pub fn countg_uniq_with_check<
N: Debug + PartialEq + Hash + Eq + Copy,
I: Iterator<Item = N>,
>(
start: N,
graph: &mut impl Fn(N) -> I,
ok: &mut impl Fn(N, N) -> bool,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
has: &mut HashSet<N>,
) {
if end(start) && has.insert(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if ok(start, x) {
countg_uniq_with_check(x, graph, ok, sum, end, has);
}
})
.Θ();
}
}
pub fn countg<N: Debug + PartialEq + Hash + Eq + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
sum: &mut usize,
end: &mut impl Fn(N) -> bool,
has: &mut HashSet<N>,
) {
if end(start) {
*sum += 1;
} else {
graph(start)
.map(|x| {
if has.insert(x) {
countg(x, graph, sum, end, has);
}
})
.Θ();
}
}
// pub fn appearances(x: )
pub fn iterg<N: Debug + Copy, I: Iterator<Item = N>>(
start: N,
graph: &mut impl Fn(N) -> I,
end: &mut impl Fn(N) -> bool,
finally: &mut impl FnMut(N),
) {
if end(start) {
finally(start);
} else {
graph(start).map(|x| iterg(x, graph, end, finally)).Θ();
};
}
pub fn show<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>, D: Display>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
name: impl Fn(N) -> D,
) {
println!("digraph {{");
let mut s = HashSet::default();
let mut q = BinaryHeap::new();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
println!("}}");
return;
}
if !s.insert(n) {
continue;
}
print!("\t{}", name(n));
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
print!(" -> {}", name(n));
q.push(Reverse((c + d, n)));
}
println!(";");
}
dang!();
}
pub fn dijkstra_h<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
h: impl Fn(N) -> u16,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((h(start), 0, start)));
while let Some(Reverse((_, c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((h(n) + c + d, c + d, n)));
}
}
dang!()
}
pub fn dijkstra<N: Debug + Eq + Hash + Copy + Ord, I: Iterator<Item = (N, u16)>>(
graph: impl Fn(N) -> I,
start: N,
end: impl Fn(N) -> bool,
) -> u16 {
let mut q = BinaryHeap::new();
let mut s = HashSet::default();
q.push(Reverse((0, start)));
while let Some(Reverse((c, n))) = q.pop() {
if end(n) {
return c;
}
if !s.insert(n) {
continue;
}
for (n, d) in graph(n) {
if s.contains(&n) {
continue;
}
q.push(Reverse((c + d, n)));
}
}
dang!()
}
impl std::ops::Add<(i64, i64)> for Dir {
type Output = (i64, i64);
fn add(self, (x, y): (i64, i64)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(usize, usize)> for Dir {
type Output = (usize, usize);
fn add(self, (x, y): (usize, usize)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i32, i32)> for Dir {
type Output = (i32, i32);
fn add(self, (x, y): (i32, i32)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u16, u16)> for Dir {
type Output = (u16, u16);
fn add(self, (x, y): (u16, u16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(i16, i16)> for Dir {
type Output = (i16, i16);
fn add(self, (x, y): (i16, i16)) -> Self::Output {
match self {
Dir::N => (x, y - 1),
Dir::E => (x + 1, y),
Dir::S => (x, y + 1),
Dir::W => (x - 1, y),
}
}
}
impl std::ops::Add<(u8, u8)> for Dir {
type Output = Option<(u8, u8)>;
fn add(self, (x, y): (u8, u8)) -> Self::Output {
match self {
Dir::N => Some((x, y.checked_sub(1)?)),
Dir::E => Some((x + 1, y)),
Dir::S => Some((x, y + 1)),
Dir::W => Some((x.checked_sub(1)?, y)),
}
}
}
impl Dir {
pub fn turn_90(self) -> Self {
match self {
Dir::N => Dir::E,
Dir::E => Dir::S,
Dir::S => Dir::W,
Dir::W => Dir::N,
}
}
pub fn turn_90ccw(self) -> Self {
match self {
Dir::N => Dir::W,
Dir::E => Dir::N,
Dir::S => Dir::E,
Dir::W => Dir::S,
}
}
}
pub fn pa<T: std::fmt::Debug>(a: &[T]) {
for e in a {
print!("{e:?}");
}
println!();
}
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
if a == 0 || b == 0 {
return a | b;
}
let shift = (a | b).trailing_zeros();
a >>= shift;
loop {
b >>= b.trailing_zeros();
if a > b {
swap(&mut a, &mut b);
}
b -= a;
if b == 0 {
break;
}
}
a << shift
}
pub trait Λ {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Λ for String {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
self.as_str().λ()
}
}
impl Λ for &[u8] {
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).α().λ()
}
}
impl Λ for &str {
/// parse, unwrap
fn λ<T: FromStr>(&self) -> T
where
<T as FromStr>::Err: std::fmt::Display,
{
match self.parse() {
Ok(v) => v,
Err(e) => {
panic!(
"{e}: {self} should parse into {}",
std::any::type_name::<T>()
)
}
}
}
}
pub trait Κ {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl Κ for &[u8] {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
std::str::from_utf8(self).unwrap().κ()
}
}
impl Κ for &str {
fn κ<T: FromStr>(self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.split_ascii_whitespace().map(|x| x.λ())
}
}
pub trait Α<T> {
fn α(self) -> T;
}
impl<T, E: std::fmt::Display> Α<T> for Result<T, E> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Ok(v) => v,
Err(e) => {
panic!("unwrap failed: {e}");
}
}
}
}
impl<T> Α<T> for Option<T> {
#[cfg_attr(debug_assertions, track_caller)]
fn α(self) -> T {
match self {
Some(v) => v,
None => panic!("nothingness!"),
}
}
}
pub trait DigiCount {
fn ͱ(self) -> u32;
}
pub const powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
// https://stackoverflow.com/a/9721570
impl DigiCount for u64 {
fn ͱ(self) -> u32 {
static powers: [u64; 20] = car::from_fn!(|x| 10u64.pow(x as u32));
static mdigs: [u32; 65] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u32 {
fn ͱ(self) -> Self {
static powers: [u32; 10] = car::from_fn!(|x| 10u32.pow(x as u32));
static mdigs: [u32; 33] = car::from_fn!(|x| 2u128.pow(x as u32).ilog10() + 1);
let bit = std::mem::size_of::<Self>() * 8 - self.leading_zeros() as usize;
let mut digs = mdigs[bit];
if self < C! { powers[digs as usize - 1] } {
digs -= 1;
}
digs
}
}
impl DigiCount for u16 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
impl DigiCount for u8 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
impl DigiCount for u128 {
fn ͱ(self) -> u32 {
self.checked_ilog10().ψ() + 1
}
}
pub trait Ͷ: DigiCount {
fn ͷ(self) -> impl Iterator<Item = u8>;
fn Ͷ(self, i: u8) -> u8;
}
macro_rules! digs {
($for:ty) => {
impl Ͷ for $for {
fn ͷ(self) -> impl Iterator<Item = u8> {
let digits = self.ͱ() as u8;
(0..digits).rev().map(move |n| self.Ͷ(n))
}
fn Ͷ(self, i: u8) -> u8 {
((self / (10 as $for).pow(i as _)) % 10) as u8
}
}
};
}
digs!(u128);
digs!(u64);
digs!(u32);
digs!(u16);
digs!(u8);
#[derive(Copy, Clone, PartialEq, PartialOrd)]
pub struct Ronge {
pub begin: u16,
pub end: u16,
}
impl Debug for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl Display for Ronge {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..{}", self.begin, self.end)
}
}
impl From<RangeInclusive<u16>> for Ronge {
fn from(value: RangeInclusive<u16>) -> Self {
Self {
begin: *value.start(),
end: *value.end(),
}
}
}
impl PartialEq<RangeInclusive<u16>> for Ronge {
fn eq(&self, other: &RangeInclusive<u16>) -> bool {
self == &Self::from(other.clone())
}
}
impl Ronge {
pub fn sane(self) -> bool {
self.end >= self.begin
}
pub fn checked_len(self) -> Option<u16> {
self.sane().then(|| self.len())
}
pub fn len(self) -> u16 {
self.end - self.begin
}
/// push up
pub fn pushu(&mut self, to: u16) {
self.begin = self.begin.max(to);
}
/// push down
pub fn pushd(&mut self, to: u16) {
self.end = self.end.min(to);
}
pub fn intersect(self, with: Self) -> Self {
Self {
begin: self.begin.max(with.begin),
end: self.end.min(with.end),
}
}
pub fn news(&self, begin: u16) -> Self {
Self {
begin,
end: self.end,
}
}
pub fn newe(&self, end: u16) -> Self {
Self {
begin: self.begin,
end,
}
}
pub fn shrink(&mut self, with: Ronge) {
self.pushu(with.begin);
self.pushd(with.end);
}
}
impl IntoIterator for Ronge {
type Item = u16;
type IntoIter = std::ops::Range<u16>;
fn into_iter(self) -> Self::IntoIter {
self.begin..self.end
}
}
pub trait Μ where
Self: Sized,
{
fn μ(self, d: char) -> (Self, Self);
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display;
fn μ1(self, d: char) -> Self {
self.μ(d).1
}
fn μ0(self, d: char) -> Self {
self.μ(d).0
}
fn between(self, a: char, b: char) -> Self {
self.μ1(a).μ0(b)
}
}
impl Μ for &[u8] {
fn μ(self, d: char) -> (Self, Self) {
let i = memchr::memchr(d as u8, self)
.unwrap_or_else(|| shucks!("{} should split at {d} fine", self.p()));
(&self[..i], &self[i + 1..])
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub fn gt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a > n
}
pub fn lt<A: std::cmp::PartialOrd<T>, T>(n: T) -> impl Fn(A) -> bool {
move |a| a < n
}
impl Μ for &str {
fn μ(self, d: char) -> (Self, Self) {
self.split_once(d)
.unwrap_or_else(|| shucks!("{self} should split at {d} fine"))
}
fn μκ<T: FromStr>(self, d: char) -> impl Iterator<Item = (T, T)>
where
<T as FromStr>::Err: std::fmt::Display,
{
let (α, β) = self.μ(d);
α.κ::<T>().zip(β.κ::<T>())
}
}
pub trait IterͶ: Iterator {
fn ͷ(self) -> impl Iterator<Item = u8>;
}
impl<I: Iterator<Item = u64>> IterͶ for I {
fn ͷ(self) -> impl Iterator<Item = u8> {
self.flat_map(Ͷ::ͷ)
}
}
pub trait TupleIterTools3<T, U, V>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn m(self) -> impl Iterator<Item = U>;
fn r(self) -> impl Iterator<Item = V>;
fn lm(self) -> impl Iterator<Item = (T, U)>;
fn lr(self) -> impl Iterator<Item = (T, V)>;
fn mr(self) -> impl Iterator<Item = (U, V)>;
}
pub trait TupleIterTools2<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub trait TupleIterTools2R<T, U>: Iterator {
fn l(self) -> impl Iterator<Item = T>;
fn r(self) -> impl Iterator<Item = U>;
}
pub fn l<R, T, U>(f: impl Fn(T) -> R) -> impl Fn((T, U)) -> R {
move |(x, _)| f(x)
}
pub fn r<R, T, U>(f: impl Fn(U) -> R) -> impl Fn((T, U)) -> R {
move |(_, x)| f(x)
}
pub trait FilterBy3<T, U, V>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)>;
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)>;
}
impl<T: Copy, U: Copy, V: Copy, I: Iterator<Item = (T, U, V)>> FilterBy3<T, U, V> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(x, _, _)| f(*x))
}
fn fm(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, x, _)| f(*x))
}
fn fr(self, f: impl Fn(V) -> bool) -> impl Iterator<Item = (T, U, V)> {
self.filter(move |(_, _, x)| f(*x))
}
}
pub trait FilterBy<T, U>: Iterator {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)>;
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)>;
}
impl<T: Copy, U: Copy, I: Iterator<Item = (T, U)>> FilterBy<T, U> for I {
fn fl(self, f: impl Fn(T) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(x, _)| f(*x))
}
fn fr(self, f: impl Fn(U) -> bool) -> impl Iterator<Item = (T, U)> {
self.filter(move |(_, x)| f(*x))
}
}
pub trait NumTupleIterTools {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64;
}
impl<I: Iterator<Item = (u64, u64)>> NumTupleIterTools for I {
fn πολλαπλασιάζω_και_αθροίζω(&mut self) -> u64 {
self.map(|(a, b)| a * b).sum()
}
}
impl<T, U, I: Iterator<Item = (T, U)>> TupleIterTools2<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|(_, x)| x)
}
}
impl<'a, T: Copy + 'a, U: Copy + 'a, I: Iterator<Item = &'a (T, U)>> TupleIterTools2R<T, U> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|&(x, _)| x)
}
fn r(self) -> impl Iterator<Item = U> {
self.map(|&(_, x)| x)
}
}
impl<T, U, V, I: Iterator<Item = (T, U, V)>> TupleIterTools3<T, U, V> for I {
fn l(self) -> impl Iterator<Item = T> {
self.map(|(x, _, _)| x)
}
fn m(self) -> impl Iterator<Item = U> {
self.map(|(_, x, _)| x)
}
fn r(self) -> impl Iterator<Item = V> {
self.map(|(_, _, x)| x)
}
fn lm(self) -> impl Iterator<Item = (T, U)> {
self.map(|(a, b, _)| (a, b))
}
fn lr(self) -> impl Iterator<Item = (T, V)> {
self.map(|(a, _, b)| (a, b))
}
fn mr(self) -> impl Iterator<Item = (U, V)> {
self.map(|(_, a, b)| (a, b))
}
}
pub trait GreekTools<T>: Iterator {
fn Δ(&mut self) -> T;
fn ι<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ι1<N>(&mut self) -> impl Iterator<Item = (T, N)>
where
Self: Ι<T, N>;
fn ν<const N: usize>(&mut self, into: &mut [T; N]) -> usize;
fn Θ(&mut self);
}
pub trait ParseIter {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display;
}
impl<'x, I: Iterator<Item = &'x [u8]>> ParseIter for I {
fn κ<T: FromStr>(&mut self) -> impl Iterator<Item = T>
where
<T as FromStr>::Err: std::fmt::Display,
{
self.flat_map(|x| x.κ())
}
}
pub trait Ι<T, N>: Iterator {
fn ι(&mut self) -> impl Iterator<Item = (T, N)>;
fn ι1(&mut self) -> impl Iterator<Item = (T, N)>;
}
macro_rules! ι {
($t:ty) => {
impl<T, I: Iterator<Item = T>> Ι<T, $t> for I {
fn ι(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(0..)
}
fn ι1(&mut self) -> impl Iterator<Item = (T, $t)> {
self.zip(1..)
}
}
};
}
ι!(i8);
ι!(u8);
ι!(u16);
ι!(u32);
ι!(u64);
ι!(usize);
pub fn nail<const N: usize, T: Copy>(x: &[T]) -> [T; N] {
unsafe { (x.as_ptr() as *const [T; N]).read() }
}
pub mod reading {
#[inline]
pub fn 八(n: u64) -> u64 {
// reinterpret as u64 ("92233721" => 92233721)
// let n = u64::from_le_bytes(s);
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | true |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d19p2.rs | 2024/d19p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static LUT: [usize; 128] = {
let mut lut = [usize::MAX; 128];
lut[b'r' as usize] = 0;
lut[b'g' as usize] = 1;
lut[b'b' as usize] = 2;
lut[b'u' as usize] = 3;
lut[b'w' as usize] = 4;
lut
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let mut tries = [[0u16; 5]; 1024];
let mut tries_end = [false; 1024];
let mut tries_len = 1;
let mut ptr = input.as_ptr();
loop {
let n = ptr.cast::<u64>().read_unaligned();
let mask = _pext_u64(n, u64::from_ne_bytes([0b00001000; 8]) | (1 << 62));
let len = mask.trailing_zeros();
let end = ptr.add(len as usize);
let mut trie = 0;
loop {
// let i = _pext_u64(*ptr as u64 + 13, 0b10010010) - 1;
let i = *LUT.get_unchecked(*ptr as usize);
let mut next = *tries.get_unchecked(trie).get_unchecked(i as usize);
if next == 0 {
next = tries_len;
tries_len += 1;
}
*tries.get_unchecked_mut(trie).get_unchecked_mut(i as usize) = next;
trie = next as usize;
ptr = ptr.add(1);
if ptr == end {
break;
}
}
*tries_end.get_unchecked_mut(trie) = true;
ptr = ptr.add(2);
if *ptr.sub(2) == b'\n' {
break;
}
}
let mut lines = [0; 400];
let mut lines_len = 0;
let mut offset = ptr.offset_from(input.as_ptr()) as usize - 1;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let size = 400 / 16;
par::par(|idx| {
let chunk = lines.get_unchecked(size * idx..size * (idx + 1));
let mut count = 0;
for &offset in chunk {
let mut queue = [0; 64];
queue[0] = 1;
let mut pos = 0;
let base_ptr = input.as_ptr().add(offset);
let mut outer_ptr = base_ptr;
loop {
let n = *queue.get_unchecked(pos);
if n != 0 {
let mut ptr = outer_ptr;
let mut trie = 0;
loop {
let i = *LUT.get_unchecked(*ptr as usize);
trie = *tries.get_unchecked(trie).get_unchecked(i) as usize;
if trie == 0 {
break;
}
debug_assert!(trie < tries.len());
ptr = ptr.add(1);
if *tries_end.get_unchecked(trie) {
*queue.get_unchecked_mut(ptr.offset_from(base_ptr) as usize) += n;
}
if *ptr == b'\n' {
break;
}
}
}
pos += 1;
outer_ptr = outer_ptr.add(1);
if *outer_ptr == b'\n' {
count += *queue.get_unchecked(pos);
break;
}
}
}
sum.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d01p1.rs | 2024/d01p1.rs | // Original by: doge
#![feature(portable_simd)]
use std::simd::Simd;
const N: usize = 1000;
const LANES: usize = 8; // SIMD width for `Simd<u32, 8>`
#[inline(always)]
unsafe fn radix_sort_u17<const N: usize>(arr: &mut [u32; N]) {
let mut cnt_lo: [u16; 256] = [0; 256];
let mut cnt_hi: [u16; 512] = [0; 512];
let len = arr.len();
let chunks = len / LANES * LANES;
// Counting frequencies using SIMD
for i in (0..chunks).step_by(LANES) {
// Load 8 u32 elements into a SIMD vector
let data = Simd::<u32, LANES>::from_slice(&arr[i..i + LANES]);
// Extract lower 8 bits
let lo = data & Simd::splat(0xFFu32);
// Extract higher 9 bits
let hi = data >> Simd::splat(8u32);
// Update counts arrays
for j in 0..LANES {
*cnt_lo.get_unchecked_mut(lo[j] as usize) += 1;
*cnt_hi.get_unchecked_mut(hi[j] as usize) += 1;
}
}
// Process any remaining elements
for &x in &arr[chunks..] {
*cnt_lo.get_unchecked_mut((x & 0xFF) as usize) += 1;
*cnt_hi.get_unchecked_mut((x >> 8) as usize) += 1;
}
// Compute exclusive prefix sums
{
let mut sum = 0u16;
for count in cnt_lo.iter_mut() {
let temp = *count;
*count = sum;
sum += temp;
}
}
{
let mut sum = 0u16;
for count in cnt_hi.iter_mut() {
let temp = *count;
*count = sum;
sum += temp;
}
}
// First redistribution pass (lower 8 bits)
let mut buf = [0u32; N];
{
for &x in arr.iter() {
let idx = (x & 0xFF) as usize;
let dest = cnt_lo.get_unchecked_mut(idx);
*buf.get_unchecked_mut(*dest as usize) = x;
*dest += 1;
}
}
// Second redistribution pass (higher 9 bits)
{
for &x in buf.iter() {
let idx = (x >> 8) as usize;
let dest = cnt_hi.get_unchecked_mut(idx);
*arr.get_unchecked_mut(*dest as usize) = x;
*dest += 1;
}
}
}
#[inline(always)]
fn parse_5b(s: &[u8]) -> u32 {
// Optimize by unrolling the loop and using direct subtraction to convert ASCII digits to numbers
unsafe {
let s0 = *s.get_unchecked(0) as u32;
let s1 = *s.get_unchecked(1) as u32;
let s2 = *s.get_unchecked(2) as u32;
let s3 = *s.get_unchecked(3) as u32;
let s4 = *s.get_unchecked(4) as u32;
(s0 * 10000 + s1 * 1000 + s2 * 100 + s3 * 10 + s4) - 533328
}
}
pub fn run(s: &[u8]) -> i64 {
let mut left = [0; N];
let mut right = [0; N];
for i in 0..N {
left[i] = parse_5b(&s[i * 14..]);
right[i] = parse_5b(&s[i * 14 + 8..]);
}
unsafe {
radix_sort_u17(&mut left);
radix_sort_u17(&mut right);
}
left.iter()
.zip(&right)
.map(|(a, &b)| a.abs_diff(b))
.sum::<u32>() as i64
}
#[test]
fn d1p1() {
assert_eq!(run(include_bytes!("./../input/day1.txt")), 2192892);
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d22p2.rs | 2024/d22p2.rs | // Original by: caavik + giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(array_chunks)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
const WSIZE: usize = 16;
const LEN: usize = (1 << 24) - 1 + 2000 + WSIZE;
static mut NUM_TO_INDEX: [u32; 1 << 24] = [0; 1 << 24];
static mut DIGITS: [u8; LEN] = [0; LEN];
static mut DIFFS: [u16; LEN] = [0; LEN];
static mut LAST_SEEN: [u32; LEN] = [0; LEN];
unsafe fn build_tables() {
let mut i = 0;
let mut n = 1;
let mut next_diff_id = 0;
static mut DIFF_IDS: [u16; 19 * 19 * 19 * 19] = [u16::MAX; 19 * 19 * 19 * 19];
static mut DIFF_TO_LAST_SEEN: [u32; 40951] = [0; 40951];
while i < LEN {
if i < (1 << 24) - 1 {
NUM_TO_INDEX[n] = i as u32;
}
DIGITS[i] = (n % 10) as u8;
if i >= 4 {
let d1 = DIGITS[i - 4] as usize;
let d2 = DIGITS[i - 3] as usize;
let d3 = DIGITS[i - 2] as usize;
let d4 = DIGITS[i - 1] as usize;
let d5 = DIGITS[i - 0] as usize;
let diff = [9 + d2 - d1, 9 + d3 - d2, 9 + d4 - d3, 9 + d5 - d4]
.into_iter()
.fold(0, |a, d| 19 * a + d);
let mut diff_id = DIFF_IDS[diff];
if diff_id == u16::MAX {
diff_id = next_diff_id;
DIFF_IDS[diff] = next_diff_id;
next_diff_id += 1;
}
DIFFS[i] = diff_id;
LAST_SEEN[i] = DIFF_TO_LAST_SEEN[diff_id as usize];
DIFF_TO_LAST_SEEN[diff_id as usize] = i as u32;
}
n ^= (n << 6) & ((1 << 24) - 1);
n ^= n >> 5;
n ^= (n << 11) & ((1 << 24) - 1);
i += 1;
}
}
#[cfg_attr(any(target_os = "linux"), link_section = ".text.startup")]
unsafe extern "C" fn __ctor() {
build_tables();
}
#[used]
#[cfg_attr(target_os = "linux", link_section = ".init_array")]
#[cfg_attr(windows, link_section = ".CRT$XCU")]
static __CTOR: unsafe extern "C" fn() = __ctor;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[inline(always)]
fn parse8(n: u64) -> u32 {
use std::num::Wrapping as W;
let mut n = W(n);
let mask = W(0xFF | (0xFF << 32));
let mul1 = W(100 + (1000000 << 32));
let mul2 = W(1 + (10000 << 32));
n = (n * W(10)) + (n >> 8);
n = (((n & mask) * mul1) + (((n >> 16) & mask) * mul2)) >> 32;
n.0 as u32
}
macro_rules! parse {
($ptr:ident) => {{
let n = $ptr.cast::<u64>().read_unaligned();
let len = _pext_u64(n, 0x1010101010101010).trailing_ones();
let n = (n & 0x0F0F0F0F0F0F0F0F) << (8 * (8 - len));
$ptr = $ptr.add(len as usize + 1);
parse8(n)
}};
}
const NUM_SEQUENCES: usize = 19 * 19 * 19 * 19;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
static mut NUMS: [u32; 4096] = [0; 4096];
let nums = &mut NUMS;
let mut nums_len = 0;
let mut ptr = input.as_ptr();
while ptr <= input.as_ptr().add(input.len() - 8) {
let n = parse!(ptr);
*nums.get_unchecked_mut(nums_len) = n;
nums_len += 1;
}
if ptr != input.as_ptr().add(input.len()) {
let len = input.as_ptr().add(input.len()).offset_from(ptr) - 1;
let n = input
.as_ptr()
.add(input.len() - 1 - 8)
.cast::<u64>()
.read_unaligned();
let n = (n & 0x0F0F0F0F0F0F0F0F) & (u64::MAX << (8 * (8 - len)));
let n = parse8(n);
*nums.get_unchecked_mut(nums_len) = n;
nums_len += 1;
};
const NUM_COUNTS: usize = NUM_SEQUENCES * par::NUM_THREADS + (16 - NUM_SEQUENCES % 16) % 16;
static mut COUNTS: [u8; NUM_COUNTS] = [0; NUM_COUNTS];
COUNTS.fill(0);
let nums = nums.get_unchecked_mut(..nums_len);
let mut chunk_lens = [nums.len() / 8 / par::NUM_THREADS * 8; par::NUM_THREADS];
for i in 0..nums.len() / 8 % par::NUM_THREADS {
chunk_lens[i] += 8;
}
chunk_lens[par::NUM_THREADS - 1] += nums.len() % 8;
let mut chunk_pos = [0; par::NUM_THREADS + 1];
for i in 0..par::NUM_THREADS {
chunk_pos[i + 1] = chunk_pos[i] + chunk_lens[i];
}
par::par(|idx| {
let chunk = nums.get_unchecked(chunk_pos[idx]..chunk_pos[idx + 1]);
let counts = &mut *(&raw mut COUNTS).cast::<[u8; NUM_SEQUENCES]>().add(idx);
for &c in chunk {
let idx = *NUM_TO_INDEX.get_unchecked(c as usize) as usize;
let mut curr = idx + 1;
macro_rules! handle {
($min:expr) => {{
let digits = DIGITS.get_unchecked(curr..curr + WSIZE);
let digits = Simd::<u8, WSIZE>::from_slice(digits);
let diff = DIFFS.get_unchecked(curr..curr + WSIZE);
let last = LAST_SEEN.get_unchecked(curr..curr + WSIZE);
let last = Simd::<u32, WSIZE>::from_slice(last).cast::<i32>();
let mask = last.simd_lt(Simd::splat(idx as i32 + 4));
let to_sum = digits & mask.to_int().cast();
for i in $min..WSIZE {
*counts.get_unchecked_mut(diff[i] as usize) += to_sum[i];
}
curr += WSIZE;
}};
}
handle!(3);
for _ in 1..2000 / WSIZE {
handle!(0);
}
}
});
let mut max = u16x16::splat(0);
for i in 0..NUM_SEQUENCES.div_ceil(16) {
let mut sum = u16x16::splat(0);
for j in 0..par::NUM_THREADS {
let b = u8x16::from_slice(
COUNTS
.get_unchecked(NUM_SEQUENCES * j + 16 * i..)
.get_unchecked(..16),
);
sum += b.cast::<u16>();
}
max = max.simd_max(sum);
}
max.reduce_max() as u64
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d05p1.rs | 2024/d05p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
use std::simd::cmp::{SimdPartialEq, SimdPartialOrd};
use std::simd::num::SimdInt;
use std::simd::ptr::SimdMutPtr;
use std::simd::{mask8x32, simd_swizzle, u64x4, u8x32, u8x64, usizex4, Simd};
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
pub fn part1(input: &str) -> u32 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u32 {
unsafe { inner_part2(input) }
}
static NLMASK: [u8; 32] = {
let mut mask = [0; 32];
mask[0 * 6] = b'\n';
mask[1 * 6] = b'\n';
mask[2 * 6] = b'\n';
mask[3 * 6] = b'\n';
mask
};
static RULE_MUL_BLOCK: [u8; 32] = {
let mut block = [0; 32];
let mut i = 0;
while i < 4 {
block[6 * i] = 10;
block[6 * i + 1] = 1;
block[6 * i + 3] = 10;
block[6 * i + 4] = 1;
i += 1;
}
block
};
static SWIZZLE_BLOCK: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[6 * i] = 6 * i + 1;
block[6 * i + 3] = 6 * i + 4;
i += 1;
}
block
};
static SWIZZLE_LEFT: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[8 * i] = 6 * i;
i += 1;
}
block
};
static SWIZZLE_RIGHT: [usize; 32] = {
let mut block = [31; 32];
let mut i = 0;
while i < 4 {
block[8 * i] = 6 * i + 3;
i += 1;
}
block
};
#[inline(always)]
unsafe fn read_rules(rules: &mut [u128; 100], iter: &mut std::slice::Iter<u8>) {
loop {
let block = u8x32::from_slice(iter.as_slice().get_unchecked(..32));
if block.simd_eq(u8x32::from_slice(&NLMASK)).any() {
break;
}
let digits = (block - u8x32::splat(b'0')) * u8x32::from_slice(&RULE_MUL_BLOCK);
let nums = digits + simd_swizzle!(digits, SWIZZLE_BLOCK);
let left = std::mem::transmute::<_, usizex4>(simd_swizzle!(nums, SWIZZLE_LEFT));
let right = std::mem::transmute::<_, u64x4>(simd_swizzle!(nums, SWIZZLE_RIGHT));
let right_big = right.simd_ge(u64x4::splat(64));
let idx = left * usizex4::splat(2) + (right_big.to_int().cast() & usizex4::splat(1));
let ptr = Simd::splat(rules.as_mut_ptr().cast::<u64>()).wrapping_add(idx);
let shift_amt = right & u64x4::splat(0b111111);
let to_store = u64x4::splat(1) << shift_amt;
for (&ptr, &to_store) in std::iter::zip(ptr.as_array(), to_store.as_array()) {
*ptr |= to_store;
}
*iter = iter.as_slice().get_unchecked(24..).iter();
}
while *iter.as_slice().get_unchecked(0) != b'\n' {
let c = iter.as_slice().get_unchecked(..5);
let d1 = ((c[0] - b'0') as usize * 10) + ((c[1] - b'0') as usize);
let d2 = ((c[3] - b'0') as usize * 10) + ((c[4] - b'0') as usize);
*rules.get_unchecked_mut(d1) |= 1 << d2;
*iter = iter.as_slice().get_unchecked(6..).iter();
}
*iter = iter.as_slice().get_unchecked(1..).iter();
}
static UPDATE_MUL_BLOCK: [u8; 32] = {
let mut block = [0; 32];
let mut i = 0;
while i < 11 {
block[3 * i] = 10;
block[3 * i + 1] = 1;
i += 1;
}
block
};
const SWIZZLE_HI: [usize; 32] = {
let mut block = [2; 32];
let mut i = 0;
while i < 11 {
block[i] = 3 * i;
i += 1;
}
block
};
const SWIZZLE_LO: [usize; 32] = {
let mut block = [2; 32];
let mut i = 0;
while i < 11 {
block[i] = 3 * i + 1;
i += 1;
}
block
};
static MASKS: [u64; 23] = {
let mut masks = [0; 23];
let mut i = 0;
while i < 23 {
masks[i] = (1 << i) - 1;
i += 1;
}
masks
};
#[inline(always)]
unsafe fn parse11(iter: &mut std::slice::Iter<u8>, update: &mut [u8], rem: &mut usize) {
let len = std::cmp::min(*rem, 11);
*rem -= len;
let block = u8x32::from_slice(iter.as_slice().get_unchecked(..32));
let digits = block - u8x32::splat(b'0');
let nums = digits * u8x32::from_slice(&UPDATE_MUL_BLOCK);
let nums = simd_swizzle!(nums, SWIZZLE_HI) + simd_swizzle!(nums, SWIZZLE_LO);
let mask = mask8x32::from_bitmask(*MASKS.get_unchecked(len));
nums.store_select_unchecked(update, mask);
*iter = iter.as_slice().get_unchecked(len * 3..).iter();
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u32 {
let mut iter = input.as_bytes().iter();
let mut rules = [0u128; 100];
read_rules(&mut rules, &mut iter);
let mut tot = 0;
let mut buf = [0; 24];
let mut buf_len;
let mut mask;
'outer: while iter.len() >= 72 {
buf_len = 0;
mask = 0;
let len = 8 + u8x64::from_slice(iter.as_slice().get_unchecked(8..8 + 64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
let mut c_iter = iter.as_slice().get_unchecked(..len + 1).iter();
iter = iter.as_slice().get_unchecked(len + 1..).iter();
while !c_iter.as_slice().is_empty() {
let c = c_iter.as_slice();
let n = (*c.get_unchecked(0) - b'0') * 10 + (*c.get_unchecked(1) - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
if *rules.get_unchecked(n as usize) & mask != 0 {
continue 'outer;
}
mask |= 1 << n;
c_iter = c_iter.as_slice().get_unchecked(3..).iter();
}
tot += *buf.get_unchecked(buf_len / 2) as u32;
}
buf_len = 0;
mask = 0;
'outer: while !iter.as_slice().is_empty() {
let c = iter.as_slice();
let n = (*c.get_unchecked(0) - b'0') * 10 + (*c.get_unchecked(1) - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
if *rules.get_unchecked(n as usize) & mask != 0 {
while *iter.as_slice().get_unchecked(2) != b'\n' {
iter = iter.as_slice().get_unchecked(3..).iter();
}
iter = iter.as_slice().get_unchecked(3..).iter();
buf_len = 0;
mask = 0;
continue 'outer;
}
mask |= 1 << n;
if *c.get_unchecked(2) == b'\n' {
tot += *buf.get_unchecked(buf_len / 2) as u32;
buf_len = 0;
mask = 0;
}
iter = iter.as_slice().get_unchecked(3..).iter();
}
tot
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u32 {
let mut iter = input.as_bytes().iter();
let mut rules = [0u128; 100];
read_rules(&mut rules, &mut iter);
let mut tot = 0;
let mut buf = [0; 24];
let mut buf_len;
let mut mask;
let mut valid;
while iter.len() >= 72 {
let bytes_len = 9 + u8x64::from_slice(iter.as_slice().get_unchecked(8..8 + 64))
.simd_eq(u8x64::splat(b'\n'))
.first_set()
.unwrap_unchecked();
buf_len = bytes_len / 3;
let mut rem = buf_len;
while rem != 0 {
let last_idx = buf_len - rem;
parse11(&mut iter, buf.get_unchecked_mut(last_idx..), &mut rem);
}
valid = true;
mask = 1 << *buf.get_unchecked(0);
for i in 1..buf_len {
let n = *buf.get_unchecked(i);
valid &= *rules.get_unchecked(n as usize) & mask == 0;
mask |= 1 << n;
}
if !valid {
for i in 0..buf_len {
let succs = *rules.get_unchecked(*buf.get_unchecked(i) as usize) & mask;
if succs.count_ones() == buf_len as u32 / 2 {
tot += *buf.get_unchecked(i) as u32;
break;
}
}
}
}
buf_len = 0;
mask = 0;
valid = true;
for c in iter.as_slice().chunks_exact(3) {
let n = (c[0] - b'0') * 10 + (c[1] - b'0');
*buf.get_unchecked_mut(buf_len) = n;
buf_len += 1;
valid &= *rules.get_unchecked(n as usize) & mask == 0;
mask |= 1 << n;
if c[2] == b'\n' {
if !valid {
for i in 0..buf_len {
let succs = *rules.get_unchecked(*buf.get_unchecked(i) as usize) & mask;
if succs.count_ones() == buf_len as u32 / 2 {
tot += *buf.get_unchecked(i) as u32;
break;
}
}
}
buf_len = 0;
mask = 0;
valid = true;
}
}
tot
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d17p1.rs | 2024/d17p1.rs | // Original by: alion02
// .
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
#[inline]
unsafe fn inner1(s: &[u8]) -> &str {
static mut BUF: [u8; 17] = [b','; 17];
let chunk = s.as_ptr().add(12).cast::<u8x16>().read_unaligned();
let chunk = chunk - Simd::splat(b'0');
let chunk = _mm_maddubs_epi16(
chunk.into(),
u8x16::from_array([10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1]).into(),
);
let chunk = _mm_madd_epi16(
chunk,
u16x8::from_array([100, 1, 100, 1, 100, 1, 100, 1]).into(),
);
let chunk = _mm_packus_epi32(chunk, chunk);
let chunk = _mm_madd_epi16(
chunk,
u16x8::from_array([10000, 1, 10000, 1, 10000, 1, 10000, 1]).into(),
);
let mut a = u32x4::from(chunk)[0];
let imm1 = *s.get_unchecked(65) as u32 - b'0' as u32;
let chunk = s.as_ptr().add(64).cast::<u8x16>().read_unaligned();
let chunk = chunk.simd_eq(Simd::from_array([
0, 0, 0, b'1', 0, 0, 0, b'1', 0, 0, 0, b'1', 0, 0, 0, b'1',
]));
let mask = chunk.to_bitmask() as u32;
let offset = mask.trailing_zeros() as usize;
let imm2 = *s.get_unchecked(64 + offset + 2) as u32 - b'0' as u32;
let buf = &mut BUF;
let mut len = s.len();
loop {
let b = a % 8 ^ imm1;
*buf.get_unchecked_mut(len - 91) = ((a >> b ^ b ^ imm2) % 8 + b'0' as u32) as u8;
a >>= 3;
len += 2;
if a == 0 {
break;
}
}
std::str::from_utf8_unchecked(buf)
}
#[inline]
unsafe fn inner2(s: &[u8]) -> u32 {
0
}
#[inline]
pub fn run(s: &str) -> &str {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn part2(s: &str) -> u32 {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d24p2.rs | 2024/d24p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
// pub fn run(input: &str) -> i64 {
// part1(input) as i64
// }
pub fn run(input: &str) -> &'static str {
part2(input)
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> &'static str {
unsafe { inner_part2(input) }
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
0
}
static mut PART2_OUT: [u8; 8 * 3 + 7] = [b','; 8 * 3 + 7];
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> &'static str {
let input = input.as_bytes();
// TODO: u8 ids
let mut node_to_id = [u8::MAX; 23 * 26 * 26];
let mut id_to_node = [u16::MAX; 222];
let mut next_id = 46;
static mut XYOPS: [[u8; 2]; 45] = [[u8::MAX; 2]; 45];
let mut xyops = &mut XYOPS;
static mut OPS: [[[u8; 2]; 2]; 222] = {
let mut ops = [[[u8::MAX; 2]; 2]; 222];
let mut i = 0;
while i < 46 {
ops[i] = [[u8::MAX - 1; 2]; 2];
i += 1;
}
ops
};
let mut ops = &mut OPS;
macro_rules! get_id {
($a:ident, $b:ident, $c:ident) => {{
let node =
26 * 26 * ($a - b'a' as usize) + 26 * ($b - b'a' as usize) + ($c - b'a' as usize);
let mut id = *node_to_id.get_unchecked(node);
if id == u8::MAX {
id = next_id;
*node_to_id.get_unchecked_mut(node) = id;
*id_to_node.get_unchecked_mut(id as usize) = node as u16;
next_id += 1;
}
id
}};
}
let mut ptr = input.as_ptr().add(631);
let end = input.as_ptr().add(input.len());
loop {
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
if a == b'x' as usize || a == b'y' as usize {
let n = 10 * (b - b'0' as usize) + (c - b'0' as usize);
let off = (*ptr == b'X') as usize;
ptr = ptr.add(11);
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let out = if a == b'z' as usize {
(10 * (b - b'0' as usize) + (c - b'0' as usize)) as u8
} else {
get_id!(a, b, c)
};
*xyops.get_unchecked_mut(n).get_unchecked_mut(off) = out;
} else {
let n = get_id!(a, b, c);
let op = *ptr;
ptr = ptr.add(3);
if op != b'O' {
ptr = ptr.add(1);
}
let off = (op == b'X') as usize;
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(7);
let m = get_id!(a, b, c);
let a = *ptr as usize;
let b = *ptr.add(1) as usize;
let c = *ptr.add(2) as usize;
ptr = ptr.add(4);
let out = if a == b'z' as usize {
(10 * (b - b'0' as usize) + (c - b'0' as usize)) as u8
} else {
get_id!(a, b, c)
};
if op == b'O' {
*ops.get_unchecked_mut(n as usize).get_unchecked_mut(1) = [u8::MAX; 2];
*ops.get_unchecked_mut(m as usize).get_unchecked_mut(1) = [u8::MAX; 2];
}
*ops.get_unchecked_mut(n as usize).get_unchecked_mut(off) = [m, out];
*ops.get_unchecked_mut(m as usize).get_unchecked_mut(off) = [n, out];
}
if ptr == end {
break;
}
}
let mut out = [u16::MAX; 8];
let mut out_len = 0;
let mut carry = xyops[0][0] as usize;
for n in 1..45 {
let act_carry_1 = xyops[n][0] as usize;
let act_res = xyops[n][1] as usize;
let exp_res = ops.get_unchecked(carry)[0][0] as usize;
let act_carry_2 = ops.get_unchecked(carry)[0][1] as usize;
let act_z = ops.get_unchecked(carry)[1][1] as usize;
if act_z >= 46 {
*out.get_unchecked_mut(out_len) = act_z as u16;
*out.get_unchecked_mut(out_len + 1) = n as u16;
out_len += 2;
debug_assert!(act_z < 222);
debug_assert!(n < 222);
if ops.get_unchecked(act_carry_1)[1] == [u8::MAX; 2] {
carry = ops.get_unchecked(act_carry_1)[0][1] as usize;
} else {
carry = ops.get_unchecked(act_carry_2)[0][1] as usize;
}
if carry == n {
carry = act_z;
}
} else {
if act_res != exp_res {
*out.get_unchecked_mut(out_len) = act_res as u16;
out_len += 1;
debug_assert!(act_res < 222);
}
if ops.get_unchecked(act_carry_1)[1] != [u8::MAX; 2] {
*out.get_unchecked_mut(out_len) = act_carry_1 as u16;
out_len += 1;
debug_assert!(act_carry_1 < 222);
} else {
carry = ops.get_unchecked(act_carry_1)[0][1] as usize;
}
if ops.get_unchecked(act_carry_2)[1] != [u8::MAX; 2] {
*out.get_unchecked_mut(out_len) = act_carry_2 as u16;
out_len += 1;
debug_assert!(act_carry_2 < 222);
} else {
carry = ops.get_unchecked(act_carry_2)[0][1] as usize;
}
if out_len & 1 != 0 {
*out.get_unchecked_mut(out_len) = carry as u16;
out_len += 1;
debug_assert!(carry < 222);
carry = *out.get_unchecked(out_len - 2) as usize;
}
}
if out_len == 8 {
break;
}
}
debug_assert_eq!(out_len, 8);
let mut out_chr = [[u8::MAX; 3]; 8];
for i in 0..8 {
let n = out[i];
if n < 46 {
out_chr[i] = [b'z', b'0' + n as u8 / 10, b'0' + n as u8 % 10];
} else {
let n = id_to_node[n as usize];
out_chr[i] = [
b'a' + (n / (26 * 26)) as u8,
b'a' + (n / 26 % 26) as u8,
b'a' + (n % 26) as u8,
];
}
}
out_chr.sort_unstable();
for i in 0..8 {
PART2_OUT[4 * i + 0] = out_chr[i][0];
PART2_OUT[4 * i + 1] = out_chr[i][1];
PART2_OUT[4 * i + 2] = out_chr[i][2];
}
std::str::from_utf8_unchecked(&PART2_OUT)
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d15p2.rs | 2024/d15p2.rs | // Original by: alion02
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
#[inline]
unsafe fn inner1(s: &[u8]) -> u32 {
static DIR_TABLE: [i16; 256] = {
let mut dir_table = [0; 256];
dir_table[b'>' as usize] = 1;
dir_table[b'v' as usize] = 51;
dir_table[b'<' as usize] = -1;
dir_table[b'<' as usize + 1] = -1;
dir_table[b'^' as usize] = -51;
dir_table[b'^' as usize + 1] = -1;
dir_table
};
static mut MAP: [u8; 2560] = [0; 2560];
let map = &mut MAP;
map.copy_from_slice(s.get_unchecked(..2560));
let pos = 24usize * 51 + 24;
*map.get_unchecked_mut(pos) = b'.';
asm!(
"jmp 24f",
// #
"21:",
"sub {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
// .
"20:",
"inc {ip}",
"je 99f",
"24:",
"movzx {inst:e}, byte ptr[{instrs} + {ip}]",
"add {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {pos}], 46",
"je 20b",
"jb 21b",
// O
"mov {block_pos:e}, {pos:e}",
"22:",
// O repeats
"add {block_pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {block_pos}], 46",
"ja 22b",
"jb 21b",
// O then .
"23:",
"mov byte ptr[{map} + {pos}], 46",
"mov byte ptr[{map} + {block_pos}], 79",
"inc {ip}",
"jne 24b",
"99:",
instrs = in(reg) s.as_ptr_range().end,
ip = inout(reg) -20020isize => _,
map = in(reg) map,
pos = inout(reg) pos => _,
inst = out(reg) _,
block_pos = out(reg) _,
dir_table = inout(reg) &DIR_TABLE => _,
options(nostack),
);
let mut map = map.as_ptr().add(52).cast::<u8x16>();
let mut vec_counts = u32x4::splat(0);
let mut y_mult = i16x8::splat(-100);
for _y in 1..49 {
macro_rules! process {
($i:expr) => {{
let c = map.byte_add($i).read_unaligned();
let c = c.simd_eq(Simd::splat(b'O'));
let x = c.select(
u8x16::from_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
+ Simd::splat($i),
Simd::splat(0),
);
(c.to_int(), x)
}};
}
let (c1, x1) = process!(0);
let (c2, x2) = process!(16);
let (c3, x3) = process!(32);
let c = c1 + c2 + c3;
let c = _mm_maddubs_epi16(i8x16::splat(1).into(), c.into());
let c = _mm_madd_epi16(c, y_mult.into());
vec_counts += u32x4::from(c);
let x = x1 + x2 + x3;
let x = _mm_maddubs_epi16(x.into(), i8x16::splat(1).into());
let x = _mm_madd_epi16(x, i16x8::splat(1).into());
vec_counts += u32x4::from(x);
y_mult -= i16x8::splat(100);
map = map.byte_add(51);
}
vec_counts.reduce_sum()
}
#[inline]
unsafe fn inner2(s: &[u8]) -> u32 {
static DIR_TABLE: [i16; 256] = {
let mut dir_table = [0; 256];
dir_table[b'>' as usize] = 1;
dir_table[b'v' as usize] = 128;
dir_table[b'<' as usize] = -1;
dir_table[b'<' as usize + 1] = -1;
dir_table[b'^' as usize] = -128;
dir_table[b'^' as usize + 1] = -1;
dir_table
};
static mut MAP: [i8; 6400] = [-2; 6400];
let map = &mut MAP;
for y in 1..49 {
for x in 0..3 {
let chunk = s
.as_ptr()
.add(y * 51 + x * 16 + 1)
.cast::<u8x16>()
.read_unaligned();
let chunk = simd_swizzle!(
chunk,
[
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12,
12, 13, 13, 14, 14, 15, 15
]
);
let a = chunk
.simd_eq(Simd::splat(b'#'))
.select(i8x32::splat(-2), i8x32::splat(-1));
let b = chunk.simd_eq(Simd::splat(b'O')).select(
Simd::from_array([
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1,
]),
a,
);
map.as_mut_ptr()
.add(y * 128 + x * 32 + 2)
.cast::<i8x32>()
.write_unaligned(b);
}
}
let pos = 24usize * 128 + 48;
asm!(
"jmp 24f",
"21:",
"sub {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"20:",
"inc {ip}",
"je 99f",
"24:",
"movzx {inst:e}, byte ptr[{instrs} + {ip}]",
"add {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {pos}], -1",
"je 20b", // .
"jl 21b", // #
// []
"mov {bpos:e}, {pos:e}",
"mov {step:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp {step:l}, -128",
"je 25f", // vertical
// horizontal
"add {step:e}, {step:e}",
"26:",
"add {bpos:e}, {step:e}",
"cmp byte ptr[{map} + {bpos}], -1",
"jg 26b", // [] repeats
"jl 21b", // [] then # // TODO optimize
// [] then .
"cmp byte ptr[{map} + {pos}], 0",
"je 27f", // right
// left
"28:",
"mov word ptr[{map} + {bpos}], 256",
"sub {bpos:e}, {step:e}",
"cmp {bpos:e}, {pos:e}",
"jne 28b",
"mov byte ptr[{map} + {bpos}], -1",
"inc {ip}",
"jne 24b",
"jmp 99f",
"27:",
"mov word ptr[{map} + {bpos} - 1], 256",
"sub {bpos:e}, {step:e}",
"cmp {bpos:e}, {pos:e}",
"jne 27b",
"mov byte ptr[{map} + {bpos}], -1",
"inc {ip}",
"jne 24b",
"jmp 99f",
"31:",
"sub {pos:e}, {step:e}",
"mov rsp, {saved_rsp}",
"inc {ip}",
"jne 24b",
"jmp 99f",
"33:",
"inc {bpos:e}",
"30:",
"sub {bpos:l}, byte ptr[{map} + {bpos}]", // align block position to left
"add {bpos:e}, {step:e}",
"cmp byte ptr[{map} + {bpos}], -1",
"jl 31b", // #
"je 32f", // .
"cmp byte ptr[{map} + {bpos}], 0",
"je 30b",
"push {bpos}",
"call 30b",
"pop {bpos}",
"32:",
"cmp byte ptr[{map} + {bpos} + 1], -1",
"jl 31b", // #
"jg 33b", // []
// .
"ret",
"35:",
"sub {bpos2:l}, byte ptr[{map} + {bpos2}]", // align block position to left
"mov word ptr[{map} + {bpos2}], -1",
"add {bpos2:e}, {step:e}",
"cmp byte ptr[{map} + {bpos2}], 0",
"push {bpos2}",
"jl 36f", // done
"call 35b",
"mov {bpos2}, qword ptr[rsp]",
"36:",
"inc {bpos2:e}",
"cmp byte ptr[{map} + {bpos2}], 0",
"jl 37f", // done
"call 35b",
"37:",
"pop {bpos2}",
"mov word ptr[{map} + {bpos2}], 256",
"ret",
"25:",
"mov {saved_rsp}, rsp",
"mov {bpos2:e}, {bpos:e}",
"call 30b", // check pushability
"call 35b", // returned normally, so we can push
"inc {ip}",
"jne 24b",
"99:",
instrs = in(reg) s.as_ptr_range().end,
ip = inout(reg) -20020isize => _,
map = in(reg) map,
pos = inout(reg) pos => _,
inst = out(reg) _,
bpos = out(reg) _,
bpos2 = out(reg) _,
step = out(reg) _,
saved_rsp = out(reg) _,
dir_table = inout(reg) &DIR_TABLE => _,
);
let mut map = map.as_ptr().add(130).cast::<i8x32>();
let mut vec_counts = u32x8::splat(0);
let mut y_mult = i16x16::splat(-100);
for _y in 1..49 {
macro_rules! process {
($i:expr) => {{
let c = map.byte_add($i).read_unaligned();
let c = c.simd_eq(Simd::splat(0));
let x = c.select(
u8x32::from_array([
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
]) + Simd::splat($i),
Simd::splat(0),
);
(c.to_int(), x)
}};
}
let (c1, x1) = process!(0);
let (c2, x2) = process!(32);
let (c3, x3) = process!(64);
let c = c1 + c2 + c3;
let c = _mm256_maddubs_epi16(i8x32::splat(1).into(), c.into());
let c = _mm256_madd_epi16(c, y_mult.into());
vec_counts += u32x8::from(c);
let x = x1 + x2 + x3;
let x = _mm256_maddubs_epi16(x.into(), i8x32::splat(1).into());
let x = _mm256_madd_epi16(x, i16x16::splat(1).into());
vec_counts += u32x8::from(x);
y_mult -= i16x16::splat(100);
map = map.byte_add(128);
}
vec_counts.reduce_sum()
}
#[inline]
pub fn part1(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn run(s: &str) -> impl Display {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d03p1.rs | 2024/d03p1.rs | // Original by: alion02
#![feature(portable_simd)]
use std::{
arch::x86_64::{
__m256i, _mm256_madd_epi16, _mm256_maddubs_epi16, _mm256_movemask_epi8,
_mm256_shuffle_epi8, _mm_madd_epi16, _mm_maddubs_epi16, _mm_movemask_epi8,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
fmt::Display,
mem::{transmute, MaybeUninit},
simd::prelude::*,
};
static LUT: [u8x16; 1 << 7] = unsafe {
transmute([
255u8, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5,
7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 255, 255, 255, 7, 255, 0,
1, 2, 3, 6, 8, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 4, 255, 255, 6, 7, 255, 0, 1, 2, 3, 5, 8, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5, 7, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 6, 255, 255, 255, 8, 255,
0, 1, 2, 3, 7, 9, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 4, 5, 255, 255, 7, 8, 255, 0, 1, 2, 3, 6, 9, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 6, 7, 8, 255, 0, 1, 2,
3, 5, 9, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5,
7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 255, 255, 255, 7, 255, 0,
1, 2, 3, 6, 8, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 4, 255, 255, 6, 7, 255, 0, 1, 2, 3, 5, 8, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5, 7, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 6, 255, 255, 8, 9, 255,
0, 1, 2, 3, 7, 10, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 4, 5, 255, 7, 8, 9, 255, 0, 1, 2, 3, 6, 10, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6,
255, 0, 1, 2, 3, 5, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 255,
255, 255, 7, 255, 0, 1, 2, 3, 6, 8, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 6, 7, 255, 0, 1, 2, 3, 5, 8, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5, 7, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 6,
255, 255, 255, 8, 255, 0, 1, 2, 3, 7, 9, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 4, 5, 255, 255, 7, 8, 255, 0, 1, 2, 3, 6, 9, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 6,
7, 8, 255, 0, 1, 2, 3, 5, 9, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6,
255, 0, 1, 2, 3, 5, 7, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 255,
255, 255, 7, 255, 0, 1, 2, 3, 6, 8, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 6, 7, 255, 0, 1, 2, 3, 5, 8, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 4, 255, 255, 255, 6, 255, 0, 1, 2, 3, 5, 7, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 4, 5, 6,
255, 8, 9, 10, 255, 0, 1, 2, 3, 7, 11, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
])
};
static mut SCRATCH: [u8x32; 5] = [u8x32::from_array([0; 32]); 5];
#[target_feature(enable = "avx2,bmi1,bmi2,cmpxchg16b,lzcnt,movbe,popcnt")]
unsafe fn inner1(s: &[u8]) -> u32 {
let r = s.as_ptr_range();
let mut ptr = r.start;
let mut end = r.end.sub(77);
let lut = &LUT;
let mut sum = Simd::splat(0);
let mut finishing = false;
'chunk: loop {
let chunk = (ptr as *const u8x64).read_unaligned();
let is_u = chunk.simd_eq(Simd::splat(b'u'));
let mut u_mask = is_u.to_bitmask();
loop {
let u_offset = u_mask.trailing_zeros();
if u_offset == 64 {
ptr = ptr.add(64);
if ptr < end {
continue 'chunk;
}
if finishing {
return sum[0] as u32;
}
finishing = true;
let scratch = SCRATCH.as_mut_ptr();
(scratch).write((r.end.sub(96) as *const u8x32).read_unaligned());
(scratch.add(1)).write((r.end.sub(64) as *const u8x32).read_unaligned());
(scratch.add(2)).write((r.end.sub(32) as *const u8x32).read_unaligned());
ptr = scratch.add(3).byte_offset(ptr.offset_from(r.end)) as _;
end = scratch.add(3) as _;
continue 'chunk;
}
u_mask &= u_mask - 1;
let instruction = (ptr.add(u_offset as _).sub(1) as *const u8x16).read_unaligned();
let normalized = instruction - Simd::splat(b'0');
let is_digit = normalized.simd_lt(Simd::splat(10));
let digit_mask = is_digit.to_bitmask() as u32;
let lut_idx = (digit_mask & 0x7F0) >> 4;
let shuffle_idx = *lut.get_unchecked(lut_idx as usize);
let discombobulated: i8x16 =
_mm_shuffle_epi8(normalized.into(), shuffle_idx.into()).into();
let is_correct = discombobulated.simd_eq(Simd::from_array([
0, 0, 0, 0, 0, 0, 0, 0, 61, 69, 60, -8, -4, -7, 0, 0,
]));
if _mm_testc_si128(
is_correct.to_int().into(),
i8x16::from_array([0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, 0, 0]).into(),
) == 0
{
continue;
}
let two_digit = _mm_maddubs_epi16(
discombobulated.into(),
u8x16::from_array([100, 10, 1, 0, 100, 10, 1, 0, 100, 10, 1, 0, 100, 10, 1, 0])
.into(),
);
let three_digit: i32x4 = _mm_madd_epi16(two_digit, i8x16::splat(-1).into()).into();
sum += three_digit * simd_swizzle!(three_digit, [1, 0, 3, 2]);
}
}
}
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d19p1.rs | 2024/d19p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static LUT: [usize; 128] = {
let mut lut = [usize::MAX; 128];
lut[b'r' as usize] = 0;
lut[b'g' as usize] = 1;
lut[b'b' as usize] = 2;
lut[b'u' as usize] = 3;
lut[b'w' as usize] = 4;
lut
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut tries = [[0u16; 5]; 1024];
let mut tries_end = [false; 1024];
let mut tries_len = 1;
let mut ptr = input.as_ptr();
loop {
let n = ptr.cast::<u64>().read_unaligned();
let mask = _pext_u64(n, u64::from_ne_bytes([0b00001000; 8]) | (1 << 62));
let len = mask.trailing_zeros();
std::hint::assert_unchecked(len > 0 && len <= 8);
let end = ptr.add(len as usize);
let mut trie = 0;
loop {
// let i = _pext_u64(*ptr as u64 + 13, 0b10010010) - 1;
let i = *LUT.get_unchecked(*ptr as usize);
let mut next = *tries.get_unchecked(trie).get_unchecked(i as usize);
if next == 0 {
next = tries_len;
tries_len += 1;
}
*tries.get_unchecked_mut(trie).get_unchecked_mut(i as usize) = next;
trie = next as usize;
ptr = ptr.add(1);
if ptr == end {
break;
}
}
*tries_end.get_unchecked_mut(trie) = true;
ptr = ptr.add(2);
if *ptr.sub(2) == b'\n' {
break;
}
}
let mut lines = [0; 400];
let mut lines_len = 0;
let mut offset = ptr.offset_from(input.as_ptr()) as usize - 1;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let size = 400 / 16;
par::par(|idx| {
let chunk = lines.get_unchecked(size * idx..size * (idx + 1));
let mut count = 0;
for &offset in chunk {
let mut queue = 1u64;
let mut to_see = u64::MAX;
let base_ptr = input.as_ptr().add(offset);
loop {
let pos = 63 - (queue & to_see).leading_zeros();
to_see &= !(1 << pos);
let mut ptr = base_ptr.add(pos as usize);
let mut trie = 0;
loop {
let i = *LUT.get_unchecked(*ptr as usize);
trie = *tries.get_unchecked(trie).get_unchecked(i) as usize;
if trie == 0 {
break;
}
ptr = ptr.add(1);
let b = *tries_end.get_unchecked(trie) as u64;
queue |= b << ptr.offset_from(base_ptr) as u64;
if *ptr == b'\n' {
break;
}
}
if *ptr == b'\n' && *tries_end.get_unchecked(trie) {
count += 1;
break;
}
if queue & to_see == 0 {
break;
}
}
}
sum.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let mut tries = [[0u16; 5]; 1024];
let mut tries_end = [false; 1024];
let mut tries_len = 1;
let mut ptr = input.as_ptr();
loop {
let n = ptr.cast::<u64>().read_unaligned();
let mask = _pext_u64(n, u64::from_ne_bytes([0b00001000; 8]) | (1 << 62));
let len = mask.trailing_zeros();
let end = ptr.add(len as usize);
let mut trie = 0;
loop {
// let i = _pext_u64(*ptr as u64 + 13, 0b10010010) - 1;
let i = *LUT.get_unchecked(*ptr as usize);
let mut next = *tries.get_unchecked(trie).get_unchecked(i as usize);
if next == 0 {
next = tries_len;
tries_len += 1;
}
*tries.get_unchecked_mut(trie).get_unchecked_mut(i as usize) = next;
trie = next as usize;
ptr = ptr.add(1);
if ptr == end {
break;
}
}
*tries_end.get_unchecked_mut(trie) = true;
ptr = ptr.add(2);
if *ptr.sub(2) == b'\n' {
break;
}
}
let mut lines = [0; 400];
let mut lines_len = 0;
let mut offset = ptr.offset_from(input.as_ptr()) as usize - 1;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let sum = std::sync::atomic::AtomicU64::new(0);
let size = 400 / 16;
par::par(|idx| {
let chunk = lines.get_unchecked(size * idx..size * (idx + 1));
let mut count = 0;
for &offset in chunk {
let mut queue = [0; 64];
queue[0] = 1;
let mut pos = 0;
let base_ptr = input.as_ptr().add(offset);
let mut outer_ptr = base_ptr;
loop {
let n = *queue.get_unchecked(pos);
if n != 0 {
let mut ptr = outer_ptr;
let mut trie = 0;
loop {
let i = *LUT.get_unchecked(*ptr as usize);
trie = *tries.get_unchecked(trie).get_unchecked(i) as usize;
if trie == 0 {
break;
}
debug_assert!(trie < tries.len());
ptr = ptr.add(1);
if *tries_end.get_unchecked(trie) {
*queue.get_unchecked_mut(ptr.offset_from(base_ptr) as usize) += n;
}
if *ptr == b'\n' {
break;
}
}
}
pos += 1;
outer_ptr = outer_ptr.add(1);
if *outer_ptr == b'\n' {
count += *queue.get_unchecked(pos);
break;
}
}
}
sum.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
sum.into_inner()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d02p2.rs | 2024/d02p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
#![feature(fn_align)]
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
static LT_VALID: [bool; 256] = {
let mut out = [false; 256];
out[1] = true;
out[2] = true;
out[3] = true;
out
};
#[inline(always)]
fn lt_valid(diff: i8) -> bool {
LT_VALID[diff as u8 as usize]
}
static GT_VALID: [bool; 256] = {
let mut out = [false; 256];
out[253] = true;
out[254] = true;
out[255] = true;
out
};
#[inline(always)]
fn gt_valid(diff: i8) -> bool {
GT_VALID[diff as u8 as usize]
}
pub unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 1000];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let mut lens = [1000 / par1::NUM_THREADS; par1::NUM_THREADS];
for i in 0..1000 % par1::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par1::NUM_THREADS + 1];
for i in 0..par1::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let acc = std::sync::atomic::AtomicU64::new(0);
par1::par(|idx| {
unsafe fn read(input: &mut std::slice::Iter<u8>) -> (i8, u8) {
let d1 = *input.next().unwrap_unchecked();
let mut d2 = *input.next().unwrap_unchecked();
let mut n = d1 - b'0';
if d2 >= b'0' {
n = 10 * n + (d2 - b'0');
d2 = *input.next().unwrap_unchecked();
}
(n as i8, d2)
}
let mut count = 0;
for i in poss[idx]..poss[idx + 1] {
let l = *lines.get_unchecked(i);
let mut input = input.get_unchecked(l..).iter();
let (n1, _) = read(&mut input);
let (n2, c2) = read(&mut input);
let diff = n2 - n1;
static VALID: [bool; 256] = {
let mut out = [false; 256];
out[253] = true;
out[254] = true;
out[255] = true;
out[1] = true;
out[2] = true;
out[3] = true;
out
};
let mut prev = n2;
let mut ctrl = c2;
let mut valid = VALID[diff as u8 as usize];
if valid {
if diff > 0 {
while valid && ctrl != b'\n' {
let (n, c) = read(&mut input);
let new_diff = n - prev;
(prev, ctrl) = (n, c);
valid &= lt_valid(new_diff);
}
} else {
while valid && ctrl != b'\n' {
let (n, c) = read(&mut input);
let new_diff = n - prev;
(prev, ctrl) = (n, c);
valid &= gt_valid(new_diff);
}
}
}
if valid {
count += 1;
}
}
acc.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
pub unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
let mut lines = [0; 1000];
let mut lines_len = 1;
let mut offset = 0;
while offset + 32 < input.len() {
let b = u8x32::from_slice(input.get_unchecked(offset..offset + 32));
let mut m = b.simd_eq(u8x32::splat(b'\n')).to_bitmask();
while m != 0 {
let pos = m.trailing_zeros();
m &= !(1 << pos);
*lines.get_unchecked_mut(lines_len) = offset + pos as usize + 1;
lines_len += 1;
}
offset += 32;
}
while offset + 1 < input.len() {
if *input.get_unchecked(offset) == b'\n' {
*lines.get_unchecked_mut(lines_len) = offset + 1;
lines_len += 1;
}
offset += 1;
}
let mut lens = [1000 / par2::NUM_THREADS; par2::NUM_THREADS];
for i in 0..1000 % par2::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par2::NUM_THREADS + 1];
for i in 0..par2::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let acc = std::sync::atomic::AtomicU64::new(0);
par2::par(|idx| {
unsafe fn read(input: &mut std::slice::Iter<u8>) -> (i8, u8) {
let d1 = *input.next().unwrap_unchecked();
let mut d2 = *input.next().unwrap_unchecked();
let mut n = d1 - b'0';
if d2 >= b'0' {
n = 10 * n + (d2 - b'0');
d2 = *input.next().unwrap_unchecked();
}
(n as i8, d2)
}
let mut count = 0;
for i in poss[idx]..poss[idx + 1] {
let l = *lines.get_unchecked(i);
let mut input = input.get_unchecked(l..).iter();
let (n1, _) = read(&mut input);
let (n2, c2) = read(&mut input);
let diff = n2 - n1;
let mut prevprev = n1;
let mut prev = n2;
let mut ctrl = c2;
static STATE_MAP: [[u8; 4]; 4] =
[[2, 1, 0, 0], [4, 3, 3, 3], [4, 3, 4, 3], [4, 4, 3, 3]];
let mut lt_st = if lt_valid(diff) { 0 } else { 1 };
let mut gt_st = if gt_valid(diff) { 0 } else { 1 };
while lt_st != 4 && gt_st != 4 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
(prevprev, prev, ctrl) = (prev, n, c);
}
if lt_st != 4 {
while lt_st == 0 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !lt_valid(p_diff) {
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
}
(prevprev, prev, ctrl) = (prev, n, c);
}
if ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let lt_idx = 2 * (lt_valid(p_diff) as usize) + lt_valid(pp_diff) as usize;
lt_st = *STATE_MAP
.get_unchecked(lt_st as usize)
.get_unchecked(lt_idx);
(prev, ctrl) = (n, c);
}
while lt_st == 3 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !lt_valid(p_diff) {
lt_st = 4;
}
(prev, ctrl) = (n, c);
}
} else if gt_st != 4 {
while gt_st == 0 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !gt_valid(p_diff) {
let pp_diff = n - prevprev;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
}
(prevprev, prev, ctrl) = (prev, n, c);
}
if ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
let pp_diff = n - prevprev;
let gt_idx = 2 * (gt_valid(p_diff) as usize) + gt_valid(pp_diff) as usize;
gt_st = *STATE_MAP
.get_unchecked(gt_st as usize)
.get_unchecked(gt_idx);
(prev, ctrl) = (n, c);
}
while gt_st == 3 && ctrl != b'\n' {
let (n, c) = read(&mut input);
let p_diff = n - prev;
if !gt_valid(p_diff) {
gt_st = 4;
}
(prev, ctrl) = (n, c);
}
}
if lt_st != 4 || gt_st != 4 {
count += 1;
}
}
acc.fetch_add(count, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
mod par1 {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
mod par2 {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d13p1.rs | 2024/d13p1.rs | // Original by: alion02
// .
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
unsafe fn inner1(s: &[u8]) -> u64 {
static LUT: [i8x16; 128] = {
let mut lut = [[-1i8; 16]; 128];
let mut y = 3;
while y < 6 {
let mut x = 3;
while x < 6 {
let mut y_end = 16;
let y_start = y_end - y;
let mut x_end = y_start - 4;
let x_start = x_end - x;
let index = (((1 << x_end) - 1 ^ (1 << x_start) - 1) & 0x1FC) / 4;
let entry = &mut lut[index];
let mut i = 16;
while y_start < y_end {
y_end -= 1;
i -= 1;
entry[i] = y_end;
}
let mut i = 8;
while x_start < x_end {
x_end -= 1;
i -= 1;
entry[i] = x_end;
}
x += 1;
}
y += 1;
}
unsafe { transmute(lut) }
};
let start = s.as_ptr();
let i = s.len() as isize;
let lut = LUT.as_ptr();
let mults10 = u8x16::from_array([10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1, 10, 1]);
let mults100 = u16x8::from_array([100, 1, 100, 1, 100, 1, 100, 1]);
let mults10000 = u16x8::from_array([10000, 1, 10000, 1, 10000, 1, 10000, 1]);
let swar_mask = 0xF0_F0_FF_FF_FF_FF_F0_F0u64;
let swar_bextr = 8 | 8 << 8;
let sum;
asm!(
"20:",
"vpaddb {chunk}, {neg_ascii_zero}, xmmword ptr[{start} + {i} - 17]",
"vpminub {xtmp}, {chunk}, {_9}",
"vpcmpeqb {xtmp}, {xtmp}, {chunk}",
"vpmovmskb {mask}, {xtmp}",
"tzcnt {r1}, {mask}",
"lea {i}, [{i} + {r1} - 69]",
"andn {r2}, {swar_mask}, qword ptr[{start} + {i} + 13]",
"imul {r2}, {r2}, 2561",
"bextr {ax}, {r2}, {swar_bextr:r}",
"shr {r2}, 56",
"andn rax, {swar_mask}, qword ptr[{start} + {i} + 34]",
"imul rax, rax, 2561",
"bextr {bx}, rax, {swar_bextr:r}",
"shr rax, 56",
"imul {r2}, {bx}",
"mov {r1}, rax",
"imul {r1}, {ax}",
"sub {r1}, {r2}",
"jz 21f",
"and {mask}, 0x1FC",
"vpshufb {chunk}, {chunk}, xmmword ptr[{lut} + {mask} * 4]",
"vpmaddubsw {chunk}, {chunk}, {mults10}",
"vpmaddwd {chunk}, {chunk}, {mults100}",
"vpackusdw {chunk}, {chunk}, {chunk}",
"vpmaddwd {chunk}, {chunk}, {mults10000}",
"vmovd {px:e}, {chunk}",
"vpextrd edx, {chunk}, 1",
"imul rax, {px}",
"imul rdx, {bx}",
"sub rax, rdx",
"imul {ax}, rax",
"cqo",
"idiv {r1}",
"test rdx, rdx",
"jnz 21f",
"imul {bx}, {r1}",
"imul {r1}, {px}",
"add {sum_a}, rax",
"mov rax, {r1}",
"sub rax, {ax}",
"cqo",
"idiv {bx}",
"add {sum_b}, rax",
"21:",
"test {i}, {i}",
"jns 20b",
"lea rax, [{sum_a} + {sum_a} * 2]",
"add rax, {sum_b}",
chunk = out(xmm_reg) _,
neg_ascii_zero = in(xmm_reg) u8x16::splat(b'0'.wrapping_neg()),
xtmp = out(xmm_reg) _,
_9 = in(xmm_reg) u8x16::splat(9),
start = in(reg) start,
i = inout(reg) i => _,
mask = out(reg) _,
r1 = out(reg) _,
ax = out(reg) _,
r2 = out(reg) _, // ay
bx = out(reg) _,
out("rax") sum, // by
px = out(reg) _,
out("rdx") _, // py, rem
sum_a = inout(reg) 0u64 => _,
sum_b = inout(reg) 0u64 => _,
swar_mask = in(reg) swar_mask,
swar_bextr = in(reg) swar_bextr,
lut = in(reg) lut,
mults10 = in(xmm_reg) mults10,
mults100 = in(xmm_reg) mults100,
mults10000 = in(xmm_reg) mults10000,
options(nostack),
);
sum
}
unsafe fn inner2(s: &[u8]) -> u64 {
0
}
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
pub fn part2(s: &str) -> impl Display {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d15p1.rs | 2024/d15p1.rs | // Original by: alion02
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
#[inline]
unsafe fn inner1(s: &[u8]) -> u32 {
static DIR_TABLE: [i16; 256] = {
let mut dir_table = [0; 256];
dir_table[b'>' as usize] = 1;
dir_table[b'v' as usize] = 51;
dir_table[b'<' as usize] = -1;
dir_table[b'<' as usize + 1] = -1;
dir_table[b'^' as usize] = -51;
dir_table[b'^' as usize + 1] = -1;
dir_table
};
static mut MAP: [u8; 2560] = [0; 2560];
let map = &mut MAP;
map.copy_from_slice(s.get_unchecked(..2560));
let pos = 24usize * 51 + 24;
*map.get_unchecked_mut(pos) = b'.';
asm!(
"jmp 24f",
// #
"21:",
"sub {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
// .
"20:",
"inc {ip}",
"je 99f",
"24:",
"movzx {inst:e}, byte ptr[{instrs} + {ip}]",
"add {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {pos}], 46",
"je 20b",
"jb 21b",
// O
"mov {block_pos:e}, {pos:e}",
"22:",
// O repeats
"add {block_pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {block_pos}], 46",
"ja 22b",
"jb 21b",
// O then .
"23:",
"mov byte ptr[{map} + {pos}], 46",
"mov byte ptr[{map} + {block_pos}], 79",
"inc {ip}",
"jne 24b",
"99:",
instrs = in(reg) s.as_ptr_range().end,
ip = inout(reg) -20020isize => _,
map = in(reg) map,
pos = inout(reg) pos => _,
inst = out(reg) _,
block_pos = out(reg) _,
dir_table = inout(reg) &DIR_TABLE => _,
options(nostack),
);
let mut map = map.as_ptr().add(52).cast::<u8x16>();
let mut vec_counts = u32x4::splat(0);
let mut y_mult = i16x8::splat(-100);
for _y in 1..49 {
macro_rules! process {
($i:expr) => {{
let c = map.byte_add($i).read_unaligned();
let c = c.simd_eq(Simd::splat(b'O'));
let x = c.select(
u8x16::from_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])
+ Simd::splat($i),
Simd::splat(0),
);
(c.to_int(), x)
}};
}
let (c1, x1) = process!(0);
let (c2, x2) = process!(16);
let (c3, x3) = process!(32);
let c = c1 + c2 + c3;
let c = _mm_maddubs_epi16(i8x16::splat(1).into(), c.into());
let c = _mm_madd_epi16(c, y_mult.into());
vec_counts += u32x4::from(c);
let x = x1 + x2 + x3;
let x = _mm_maddubs_epi16(x.into(), i8x16::splat(1).into());
let x = _mm_madd_epi16(x, i16x8::splat(1).into());
vec_counts += u32x4::from(x);
y_mult -= i16x8::splat(100);
map = map.byte_add(51);
}
vec_counts.reduce_sum()
}
#[inline]
unsafe fn inner2(s: &[u8]) -> u32 {
static DIR_TABLE: [i16; 256] = {
let mut dir_table = [0; 256];
dir_table[b'>' as usize] = 1;
dir_table[b'v' as usize] = 128;
dir_table[b'<' as usize] = -1;
dir_table[b'<' as usize + 1] = -1;
dir_table[b'^' as usize] = -128;
dir_table[b'^' as usize + 1] = -1;
dir_table
};
static mut MAP: [i8; 6400] = [-2; 6400];
let map = &mut MAP;
for y in 1..49 {
for x in 0..3 {
let chunk = s
.as_ptr()
.add(y * 51 + x * 16 + 1)
.cast::<u8x16>()
.read_unaligned();
let chunk = simd_swizzle!(
chunk,
[
0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12,
12, 13, 13, 14, 14, 15, 15
]
);
let a = chunk
.simd_eq(Simd::splat(b'#'))
.select(i8x32::splat(-2), i8x32::splat(-1));
let b = chunk.simd_eq(Simd::splat(b'O')).select(
Simd::from_array([
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1,
]),
a,
);
map.as_mut_ptr()
.add(y * 128 + x * 32 + 2)
.cast::<i8x32>()
.write_unaligned(b);
}
}
let pos = 24usize * 128 + 48;
asm!(
"jmp 24f",
"21:",
"sub {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"20:",
"inc {ip}",
"je 99f",
"24:",
"movzx {inst:e}, byte ptr[{instrs} + {ip}]",
"add {pos:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp byte ptr[{map} + {pos}], -1",
"je 20b", // .
"jl 21b", // #
// []
"mov {bpos:e}, {pos:e}",
"mov {step:e}, dword ptr[{dir_table} + {inst} * 2]",
"cmp {step:l}, -128",
"je 25f", // vertical
// horizontal
"add {step:e}, {step:e}",
"26:",
"add {bpos:e}, {step:e}",
"cmp byte ptr[{map} + {bpos}], -1",
"jg 26b", // [] repeats
"jl 21b", // [] then # // TODO optimize
// [] then .
"cmp byte ptr[{map} + {pos}], 0",
"je 27f", // right
// left
"28:",
"mov word ptr[{map} + {bpos}], 256",
"sub {bpos:e}, {step:e}",
"cmp {bpos:e}, {pos:e}",
"jne 28b",
"mov byte ptr[{map} + {bpos}], -1",
"inc {ip}",
"jne 24b",
"jmp 99f",
"27:",
"mov word ptr[{map} + {bpos} - 1], 256",
"sub {bpos:e}, {step:e}",
"cmp {bpos:e}, {pos:e}",
"jne 27b",
"mov byte ptr[{map} + {bpos}], -1",
"inc {ip}",
"jne 24b",
"jmp 99f",
"31:",
"sub {pos:e}, {step:e}",
"mov rsp, {saved_rsp}",
"inc {ip}",
"jne 24b",
"jmp 99f",
"33:",
"inc {bpos:e}",
"30:",
"sub {bpos:l}, byte ptr[{map} + {bpos}]", // align block position to left
"add {bpos:e}, {step:e}",
"cmp byte ptr[{map} + {bpos}], -1",
"jl 31b", // #
"je 32f", // .
"cmp byte ptr[{map} + {bpos}], 0",
"je 30b",
"push {bpos}",
"call 30b",
"pop {bpos}",
"32:",
"cmp byte ptr[{map} + {bpos} + 1], -1",
"jl 31b", // #
"jg 33b", // []
// .
"ret",
"35:",
"sub {bpos2:l}, byte ptr[{map} + {bpos2}]", // align block position to left
"mov word ptr[{map} + {bpos2}], -1",
"add {bpos2:e}, {step:e}",
"cmp byte ptr[{map} + {bpos2}], 0",
"push {bpos2}",
"jl 36f", // done
"call 35b",
"mov {bpos2}, qword ptr[rsp]",
"36:",
"inc {bpos2:e}",
"cmp byte ptr[{map} + {bpos2}], 0",
"jl 37f", // done
"call 35b",
"37:",
"pop {bpos2}",
"mov word ptr[{map} + {bpos2}], 256",
"ret",
"25:",
"mov {saved_rsp}, rsp",
"mov {bpos2:e}, {bpos:e}",
"call 30b", // check pushability
"call 35b", // returned normally, so we can push
"inc {ip}",
"jne 24b",
"99:",
instrs = in(reg) s.as_ptr_range().end,
ip = inout(reg) -20020isize => _,
map = in(reg) map,
pos = inout(reg) pos => _,
inst = out(reg) _,
bpos = out(reg) _,
bpos2 = out(reg) _,
step = out(reg) _,
saved_rsp = out(reg) _,
dir_table = inout(reg) &DIR_TABLE => _,
);
let mut map = map.as_ptr().add(130).cast::<i8x32>();
let mut vec_counts = u32x8::splat(0);
let mut y_mult = i16x16::splat(-100);
for _y in 1..49 {
macro_rules! process {
($i:expr) => {{
let c = map.byte_add($i).read_unaligned();
let c = c.simd_eq(Simd::splat(0));
let x = c.select(
u8x32::from_array([
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
]) + Simd::splat($i),
Simd::splat(0),
);
(c.to_int(), x)
}};
}
let (c1, x1) = process!(0);
let (c2, x2) = process!(32);
let (c3, x3) = process!(64);
let c = c1 + c2 + c3;
let c = _mm256_maddubs_epi16(i8x32::splat(1).into(), c.into());
let c = _mm256_madd_epi16(c, y_mult.into());
vec_counts += u32x8::from(c);
let x = x1 + x2 + x3;
let x = _mm256_maddubs_epi16(x.into(), i8x32::splat(1).into());
let x = _mm256_madd_epi16(x, i16x16::splat(1).into());
vec_counts += u32x8::from(x);
y_mult -= i16x16::splat(100);
map = map.byte_add(128);
}
vec_counts.reduce_sum()
}
#[inline]
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn part2(s: &str) -> impl Display {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d18p1.rs | 2024/d18p1.rs | // Original by: alion02
// .
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pdep_u32, _pext_u32, _pext_u64,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
static LUT: [i8x16; 512] = unsafe {
let mut lut = [[-1i8; 16]; 512];
let mut idx = 0;
while idx < 512 {
let shuffle = &mut lut[idx];
let mut mask = idx << 2;
if idx & 1 == 0 {
mask |= 2;
}
mask |= 0x800;
let mut slot = 0;
let mut byte = 0;
while slot < 8 {
let zeros = mask.trailing_zeros();
match zeros {
1 => {
shuffle[slot + 1] = byte;
byte += 2;
}
2 => {
shuffle[slot] = byte;
shuffle[slot + 1] = byte + 1;
byte += 3;
}
_ => break,
}
mask >>= zeros + 1;
slot += 2;
}
idx += 1;
}
transmute(lut)
};
#[inline]
unsafe fn inner1(s: &[u8]) -> u32 {
let mut ptr = s.as_ptr().cast::<i8x16>();
let lut = &LUT;
static mut MAP: [i8; 73 * 72 / 8] = [0; 73 * 72 / 8];
let map = MAP.as_mut_ptr();
for i in 0..23 {
map.add(72 / 8 + i * 72 / 8 * 3)
.cast::<i8x32>()
.write_unaligned(i8x32::from_array([
!0, !0, !0, !0, !0, !0, !0, !0, !-128, !0, !0, !0, !0, !0, !0, !0, !0, !-128, !0,
!0, !0, !0, !0, !0, !0, !0, !-128, !-1, !-1, !-1, !-1, !-1,
]));
}
map.add(69 * 72 / 8)
.cast::<i8x32>()
.write_unaligned(i8x32::from_array([
!0, !0, !0, !0, !0, !0, !0, !0, !-128, !0, !0, !0, !0, !0, !0, !0, !0, !-128, !0, !0,
!0, !0, !0, !0, !0, !0, !-128, !-1, !-1, !-1, !-1, !-1,
]));
macro_rules! btr {
($idx:expr) => {
asm!(
"btr dword ptr[{map} + {offset}], {idx:e}",
map = in(reg) map,
idx = in(reg) $idx,
offset = const 72 / 8,
options(nostack),
);
};
}
for _ in 0..512 {
let chunk = ptr.read_unaligned();
let chunk = chunk - Simd::splat(b'0' as _);
let mask = chunk.simd_lt(Simd::splat(0)).to_bitmask() as u32;
let step = _pdep_u32(8, mask).trailing_zeros() + 1;
let shuffle = lut.as_ptr().byte_add(((mask & 0x7FC) * 4) as usize).read();
let chunk = _mm_shuffle_epi8(chunk.into(), shuffle.into());
let chunk = _mm_maddubs_epi16(chunk, u16x8::splat(u16::from_ne_bytes([10, 1])).into());
let chunk: u32x4 = _mm_madd_epi16(
chunk,
u16x8::from_array([72, 1, 72, 1, 72, 1, 72, 1]).into(),
)
.into();
let p1 = chunk[0];
let p2 = chunk[1];
btr!(p1);
btr!(p2);
ptr = ptr.byte_add(step as usize);
}
static mut FRONT: [u16; 256] = [0; 256];
let res: u32;
asm!(
"30:",
"lea {next:e}, [{pos} + 1]",
"btr dword ptr[{map}], {next:e}",
"mov word ptr[{front} + {j} * 2], {next:x}",
"adc {j:l}, 0",
"lea {next:e}, [{pos} + 72]",
"btr dword ptr[{map}], {next:e}",
"mov word ptr[{front} + {j} * 2], {next:x}",
"adc {j:l}, 0",
"lea {next:e}, [{pos} - 1]",
"btr dword ptr[{map}], {next:e}",
"mov word ptr[{front} + {j} * 2], {next:x}",
"adc {j:l}, 0",
"lea {next:e}, [{pos} - 72]",
"btr dword ptr[{map}], {next:e}",
"mov word ptr[{front} + {j} * 2], {next:x}",
"adc {j:l}, 0",
"cmp {i:l}, {k:l}",
"jne 20f",
"mov {k:e}, {j:e}",
"inc {dist:e}",
"20:",
"movzx {pos:e}, word ptr[{front} + {i} * 2]",
"inc {i:l}",
"cmp {pos:x}, {end}",
"jne 30b",
map = in(reg) map,
pos = in(reg) 72usize,
next = out(reg) _,
front = in(reg) &mut FRONT,
i = inout(reg) 0usize => _,
j = inout(reg) 0usize => _,
k = inout(reg) 0usize => _,
dist = inout(reg) 0 => res,
end = const 72 * 72 - 2,
options(nostack),
);
res
}
#[inline]
unsafe fn inner2(s: &[u8]) -> &str {
""
}
#[inline]
pub fn run(s: &str) -> u32 {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn part2(s: &str) -> &str {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d23p2.rs | 2024/d23p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
// pub fn run(input: &str) -> i64 {
// part1(input) as i64
// }
pub fn run(input: &str) -> &'static str {
part2(input)
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> &'static str {
unsafe { inner_part2(input) }
}
const L: usize = 11;
#[inline(always)]
unsafe fn parse(input: &str, sets: &mut [[u64; L]; 26 * 26 + 1]) {
let mut ptr = input.as_ptr();
let end = ptr.add(input.len() - 18);
loop {
let mut b = ptr.cast::<u8x16>().read_unaligned();
b[2] = *ptr.add(16);
let b = simd_swizzle!(b, [0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 2, 0, 0, 0, 0]);
let b = b - u8x16::splat(b'a');
let m = u8x16::from_array([26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 26, 1, 0, 0, 0, 0]);
let b = u16x8::from(_mm_maddubs_epi16(b.into(), m.into()));
let i = b * u16x8::splat(L as u16) + (simd_swizzle!(b, [1, 0, 3, 2, 5, 4, 7, 6]) >> 6);
let (x, y) = (0, 1);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (2, 3);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
let (x, y) = (4, 5);
*sets.as_mut_ptr().cast::<u64>().add(i[x] as usize) ^= 1 << (b[y] & 63);
*sets.as_mut_ptr().cast::<u64>().add(i[y] as usize) ^= 1 << (b[x] & 63);
ptr = ptr.add(18);
if ptr > end {
break;
}
}
let end = input.as_ptr().add(input.len());
while ptr != end {
let b1 = *ptr.add(0) as usize - b'a' as usize;
let b2 = *ptr.add(1) as usize - b'a' as usize;
let b3 = *ptr.add(3) as usize - b'a' as usize;
let b4 = *ptr.add(4) as usize - b'a' as usize;
let n1 = 26 * b1 + b2;
let n2 = 26 * b3 + b4;
*sets.get_unchecked_mut(n1).get_unchecked_mut(n2 / 64) |= 1 << (n2 % 64);
*sets.get_unchecked_mut(n2).get_unchecked_mut(n1 / 64) |= 1 << (n1 % 64);
ptr = ptr.add(6);
}
}
static LUT1: [(u64, u64); 26] = {
let mut lut = [(u64::MAX, u64::MAX); 26];
let off = (26 * (b't' - b'a') as usize) % 64;
let mut i = 0;
while i < 26 {
let mut j = 0;
while j < i {
if off + j < 64 {
lut[i].0 &= !(1 << (off + j));
} else {
lut[i].1 &= !(1 << (off + j - 64));
}
j += 1;
}
i += 1;
}
lut
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut sets = [[0u64; L]; 26 * 26 + 1];
parse(input, &mut sets);
let mut count = u16x16::splat(0);
for b2 in 0..26 {
let i = 26 * (b't' - b'a') as usize + b2;
let mut s1 = sets.as_ptr().add(i).cast::<[u64; 12]>().read();
let (m1, m2) = LUT1[b2];
s1[7] &= m1;
s1[8] &= m2;
s1[11] = 0;
let mut acc = u64x4::splat(0);
for si in 0..L {
while s1[si] != 0 {
let o = s1[si].trailing_zeros() as usize;
let j = 64 * si + o;
s1[si] ^= 1 << o;
let s2 = sets.as_ptr().add(j).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
acc += tot8;
}
}
let mhhhh = u64x4::splat(0xFF00FF00FF00FF00);
let mllll = mhhhh >> 8;
let (acch, accl) = ((acc & mhhhh) >> 8, acc & mllll);
count += std::mem::transmute::<u64x4, u16x16>(acch + accl);
}
count.reduce_sum() as u64
}
static mut PART2_OUT: [u8; 13 * 2 + 12] = [b','; 13 * 2 + 12];
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> &'static str {
let mut sets = [[0u64; L]; 26 * 26 + 1];
parse(input, &mut sets);
for i in 0..26 * 26 {
let mut s1 = sets.as_ptr().add(i).cast::<[u64; 12]>().read();
s1[11] = 0;
if s1 == [0; 12] {
continue;
}
macro_rules! handle {
($other:expr) => {
'handle: {
let other = $other;
let s2 = sets.as_ptr().add(other).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
let count = std::mem::transmute::<_, u8x32>(tot8).reduce_sum();
if count != 11 {
break 'handle;
}
let mut common = std::mem::transmute::<_, [u64; 12]>([xa, xb, xc]);
for i in 0..L {
let mut b = common[i];
while b != 0 {
let o = b.trailing_zeros() as usize;
let j = 64 * i + o;
b ^= 1 << o;
let s2 = sets.as_ptr().add(j).cast::<[u64; 12]>().read();
let sa = u64x4::from_slice(&s1[4 * 0..4 * 1]);
let sb = u64x4::from_slice(&s1[4 * 1..4 * 2]);
let sc = u64x4::from_slice(&s1[4 * 2..4 * 3]);
let s2a = u64x4::from_slice(&s2[4 * 0..4 * 1]);
let s2b = u64x4::from_slice(&s2[4 * 1..4 * 2]);
let s2c = u64x4::from_slice(&s2[4 * 2..4 * 3]);
let xa = sa & s2a;
let xb = sb & s2b;
let xc = sc & s2c;
let m1 = u64x4::splat(u64::from_ne_bytes([0xAA; 8]));
let (xah, xal) = ((xa & m1) >> 1, xa & (m1 >> 1));
let (xbh, xbl) = ((xb & m1) >> 1, xb & (m1 >> 1));
let (xch, xcl) = ((xc & m1) >> 1, xc & (m1 >> 1));
let (xh, xl) = (xah + xbh + xch, xal + xbl + xcl);
let m2 = u64x4::splat(u64::from_ne_bytes([0xCC; 8]));
let (xhh, xhl) = ((xh & m2) >> 2, xh & (m2 >> 2));
let (xlh, xll) = ((xl & m2) >> 2, xl & (m2 >> 2));
let tot4 = xhh + xhl + xlh + xll;
let m4 = u64x4::splat(u64::from_ne_bytes([0xF0; 8]));
let (t4h, t4l) = ((tot4 & m4) >> 4, tot4 & (m4 >> 4));
let tot8 = t4h + t4l;
let count = std::mem::transmute::<_, u8x32>(tot8).reduce_sum();
if count != 11 {
break 'handle;
}
}
}
*common.get_unchecked_mut(i / 64) |= 1 << (i % 64);
*common.get_unchecked_mut(other / 64) |= 1 << (other % 64);
let mut pos = 0;
for i in 0..L {
let mut b = common[i];
while b != 0 {
let o = b.trailing_zeros() as usize;
let j = 64 * i + o;
b ^= 1 << o;
*PART2_OUT.get_unchecked_mut(pos) = b'a' + (j / 26) as u8;
*PART2_OUT.get_unchecked_mut(pos + 1) = b'a' + (j % 26) as u8;
pos += 3;
}
}
return std::str::from_utf8_unchecked(&PART2_OUT);
}
};
}
let mut j = 0;
let mut b = *s1.get_unchecked(j);
while b == 0 {
j += 1;
b = *s1.get_unchecked(j);
}
handle!(64 * j + b.trailing_zeros() as usize);
b &= !(1 << b.trailing_zeros());
while b == 0 {
j += 1;
b = *s1.get_unchecked(j);
}
handle!(64 * j + b.trailing_zeros() as usize);
}
std::hint::unreachable_unchecked();
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d08p1.rs | 2024/d08p1.rs | // Original by: alion02
#![allow(clippy::pointers_in_nomem_asm_block)]
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
use std::{
arch::{
asm,
x86_64::{
__m256i, _mm256_madd_epi16, _mm256_maddubs_epi16, _mm256_movemask_epi8,
_mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16, _mm_maddubs_epi16,
_mm_movemask_epi8, _mm_packus_epi32, _mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
fmt::Display,
mem::{offset_of, transmute, MaybeUninit},
simd::prelude::*,
};
// perhaps for later use
macro_rules! black_box {
($thing:expr) => {{
let mut thing = $thing;
asm!(
"/*{t}*/",
t = inout(reg) thing,
options(pure, nomem, preserves_flags, nostack)
);
thing
}};
}
unsafe fn process<const P2: bool>(s: &[u8]) -> u32 {
let r = s.as_ptr_range();
let mut ptr = r.start;
let mut cy = 0usize;
#[repr(C, align(32))]
struct Tables {
_padding1: [u8; 16],
antinodes: [u64; 150],
_padding2: [u8; 16],
frequencies: [[[u8; 2]; 4]; 75],
}
static mut TABLES: Tables = Tables {
_padding1: [0; 16],
antinodes: [0; 150],
_padding2: [0; 16],
frequencies: [[[0; 2]; 4]; 75],
};
let Tables {
antinodes,
frequencies,
..
} = &mut TABLES;
antinodes[50..100].fill(0);
frequencies.fill(Default::default());
loop {
let c1 = ptr.cast::<u8x32>().read_unaligned() + Simd::splat(127 - b'.');
let c2 = ptr.add(18).cast::<u8x32>().read_unaligned() + Simd::splat(127 - b'.');
let m1 = c1.simd_ge(Simd::splat(128)).to_bitmask();
let m2 = c2.simd_ge(Simd::splat(128)).to_bitmask();
let mut mask = m1 | m2 << 18;
if P2 {
*antinodes.get_unchecked_mut(50 + cy) |= mask;
}
while mask != 0 {
let cx = mask.trailing_zeros() as usize;
let bucket = frequencies
.get_unchecked_mut((ptr.add(cx).read() as usize).unchecked_sub(b'0' as usize));
let count_bucket = bucket.get_unchecked_mut(3).get_unchecked_mut(0);
let count = *count_bucket as usize;
*count_bucket += 1;
let [nx, ny] = bucket.get_unchecked_mut(count);
*nx = cx as u8;
*ny = cy as u8;
for i in 0..count {
let [sx, sy] = *bucket.get_unchecked(i);
let sx = sx as usize;
let sy = sy as usize;
let dx = cx as isize - sx as isize;
let dy = cy - sy;
let sbit = 1 << sx;
let cbit = 1 << cx;
if dx > 0 {
let dx = dx as usize;
if P2 {
let mut bit = cbit << dx;
let mut idx = cy + dy;
while bit < 1 << 50 && idx < 50 {
*antinodes.get_unchecked_mut(50 + idx) |= bit;
bit <<= dx;
idx += dy;
}
let mut bit = sbit >> dx;
let mut idx = sy as isize - dy as isize;
while bit > 0 && idx >= 0 {
*antinodes.get_unchecked_mut(50 + idx as usize) |= bit;
bit >>= dx;
idx -= dy as isize;
}
} else {
*antinodes.get_unchecked_mut(50 + cy + dy) |= cbit << dx;
*antinodes.get_unchecked_mut(50 + sy - dy) |= sbit >> dx;
}
} else {
let dx = -dx as usize;
if P2 {
let mut bit = cbit >> dx;
let mut idx = cy + dy;
while bit > 0 && idx < 50 {
*antinodes.get_unchecked_mut(50 + idx) |= bit;
bit >>= dx;
idx += dy;
}
let mut bit = sbit << dx;
let mut idx = sy as isize - dy as isize;
while bit < 1 << 50 && idx >= 0 {
*antinodes.get_unchecked_mut(50 + idx as usize) |= bit;
bit <<= dx;
idx -= dy as isize;
}
} else {
*antinodes.get_unchecked_mut(50 + cy + dy) |= cbit >> dx;
*antinodes.get_unchecked_mut(50 + sy - dy) |= sbit << dx;
}
}
}
mask &= mask - 1;
}
ptr = ptr.add(51);
cy += 1;
if ptr == r.end {
break;
}
}
antinodes
.get_unchecked(50..100)
.iter()
.map(|&row| if P2 { row } else { row & 0x3FFFFFFFFFFFF }.count_ones())
.sum()
}
unsafe fn inner1(s: &[u8]) -> u32 {
let r = s.as_ptr_range();
#[repr(C, align(32))]
struct Tables {
_padding1: [u8; 16],
antinodes: [u64; 150],
_padding2: [u8; 16],
frequencies: [[[u8; 2]; 4]; 75],
}
static mut TABLES: Tables = Tables {
_padding1: [0; 16],
antinodes: [0; 150],
_padding2: [0; 16],
frequencies: [[[0; 2]; 4]; 75],
};
let tables = &mut TABLES;
tables.antinodes[50..100].fill(0);
tables.frequencies.fill([[255; 2]; 4]);
asm!(
"21:",
"vpaddb {y1}, {offset}, ymmword ptr[{ptr}]",
"vpaddb {y2}, {offset}, ymmword ptr[{ptr} + 18]",
"vpmovmskb {r1:e}, {y1}",
"vpmovmskb {r2:e}, {y2}",
"shl {r2}, 18",
"or {r1}, {r2}",
"jz 20f",
"23:",
"tzcnt {cx}, {r1}",
"movzx {r2:e}, byte ptr[{ptr} + {cx}]",
"lea {r2}, [{table} + {r2} * 8 + 432]",
"movsx {count:e}, byte ptr[{r2} + 7]",
"inc {count:e}",
"mov byte ptr[{r2} + 7], {count:l}",
"mov byte ptr[{r2} + {count} * 2], {cx:l}",
"mov byte ptr[{r2} + {count} * 2 + 1], {cy:l}",
"jz 22f",
"shlx {cbit}, {one:r}, {cx}",
"26:",
"movzx {sx:e}, byte ptr[{r2} + {count} * 2 - 2]",
"movzx {sy:e}, byte ptr[{r2} + {count} * 2 - 1]",
"shlx {sbit}, {one:r}, {sx}",
"mov {dy:e}, {cy:e}",
"sub {dy}, {sy}",
"mov {dx:e}, {cx:e}",
"sub {sy:e}, {dy:e}",
"sub {dx}, {sx}",
"lea {sx}, [{cy} + {dy}]",
"jbe 24f",
"shlx {dy}, {cbit}, {dx}",
"shrx {sbit}, {sbit}, {dx}",
"jmp 25f",
"24:",
"neg {dx}",
"shrx {dy}, {cbit}, {dx}",
"shlx {sbit}, {sbit}, {dx}",
"25:",
"or qword ptr[{table} + {sx} * 8], {dy}",
"or qword ptr[{table} + {sy} * 8], {sbit}",
"dec {count:e}",
"jnz 26b",
"22:",
"blsr {r1}, {r1}",
"jnz 23b",
"20:",
"add {ptr}, -51",
"dec {cy:e}",
"jns 21b",
y1 = out(ymm_reg) _,
y2 = out(ymm_reg) _,
offset = in(ymm_reg) u8x32::splat(127 - b'.'),
ptr = inout(reg) r.end.sub(51) => _,
r1 = out(reg) _,
r2 = out(reg) _,
count = out(reg) _,
cx = out(reg) _,
cy = inout(reg) 49usize => _,
sx = out(reg) _,
sy = out(reg) _,
dx = out(reg) _,
dy = out(reg) _,
cbit = out(reg) _,
sbit = out(reg) _,
table = in(reg) (tables as *mut Tables).byte_add(offset_of!(Tables, antinodes) + size_of::<u64>() * 50),
one = in(reg) 1,
options(nostack),
);
tables
.antinodes
.get_unchecked(50..100)
.iter()
.map(|&row| (row & 0x3FFFFFFFFFFFF).count_ones())
.sum()
}
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
unsafe fn inner2(s: &[u8]) -> u32 {
process::<true>(s)
}
pub fn part2(s: &str) -> impl Display {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d16p1.rs | 2024/d16p1.rs | // Original by: alion02
#![feature(thread_local, portable_simd, core_intrinsics)]
#![allow(
clippy::precedence,
clippy::missing_transmute_annotations,
clippy::pointers_in_nomem_asm_block,
clippy::erasing_op,
static_mut_refs,
internal_features,
clippy::missing_safety_doc,
clippy::identity_op,
clippy::zero_prefixed_literal
)]
#[allow(unused)]
use std::{
arch::{
asm,
x86_64::{
__m128i, __m256i, _bextr2_u32, _mm256_madd_epi16, _mm256_maddubs_epi16,
_mm256_movemask_epi8, _mm256_shuffle_epi8, _mm_hadd_epi16, _mm_madd_epi16,
_mm_maddubs_epi16, _mm_minpos_epu16, _mm_movemask_epi8, _mm_packus_epi32,
_mm_shuffle_epi8, _mm_testc_si128, _pext_u32,
},
},
array,
fmt::Display,
hint::assert_unchecked,
intrinsics::{likely, unlikely},
mem::{offset_of, transmute, MaybeUninit},
ptr,
simd::prelude::*,
slice,
};
macro_rules! row_len {
() => {
142
};
}
macro_rules! side_len {
() => {
row_len!() - 1
};
}
macro_rules! far_edge {
() => {
row_len!() - 3
};
}
#[inline]
unsafe fn inner1(s: &[u8]) -> u32 {
static mut CURR: [Node; 65536] = [unsafe { transmute(0) }; 65536];
static mut NEXT: [Node; 65536] = [unsafe { transmute(0) }; 65536];
static OFFSET: [i16; 4] = [1, row_len!(), -1, -row_len!()];
let mut visited = [0u8; row_len!() * side_len!()];
let mut curr = &mut CURR;
let mut next = &mut NEXT;
let offset = &OFFSET;
#[derive(Clone, Copy)]
#[repr(align(4))]
struct Node {
pos: u16,
dir: u8,
cost: u8,
}
curr[0] = Node {
pos: far_edge!() * row_len!() + 1,
dir: 0,
cost: 0,
};
curr[1].cost = !0;
let mut turn_cost = 0;
loop {
let mut i = 0;
let mut k = 0;
loop {
let mut j = i;
let cost = curr.get_unchecked_mut(j).cost;
let next_cost = cost + 1;
loop {
let node = curr.get_unchecked_mut(j);
let mut pos = node.pos;
assert!(*s.get_unchecked(pos as usize) != b'#');
if pos == row_len!() + far_edge!() {
return turn_cost + cost as u32 * 2;
}
let mut dir = node.dir;
let visit_mask = dir & 1;
'delete: {
if *visited.get_unchecked(pos as usize) & visit_mask == 0 {
*visited.get_unchecked_mut(pos as usize) |= visit_mask;
dir ^= 1;
{
let pos = pos.wrapping_add_signed(*offset.get_unchecked(dir as usize));
if *s.get_unchecked(pos as usize) != b'#' {
*next.get_unchecked_mut(k) = Node {
pos: pos
.wrapping_add_signed(*offset.get_unchecked(dir as usize)),
dir,
cost: next_cost,
};
k += 1;
}
}
dir ^= 2;
{
let pos = pos.wrapping_add_signed(*offset.get_unchecked(dir as usize));
if *s.get_unchecked(pos as usize) != b'#' {
*next.get_unchecked_mut(k) = Node {
pos: pos
.wrapping_add_signed(*offset.get_unchecked(dir as usize)),
dir,
cost: next_cost,
};
k += 1;
}
}
dir ^= 3;
pos = pos.wrapping_add_signed(*offset.get_unchecked(dir as usize));
if *s.get_unchecked(pos as usize) != b'#' {
node.pos = pos.wrapping_add_signed(*offset.get_unchecked(dir as usize));
node.cost = next_cost;
break 'delete;
}
}
*curr.get_unchecked_mut(j) = *curr.get_unchecked(i);
i += 1;
}
j += 1;
if curr.get_unchecked(j).cost > cost {
break;
}
}
if curr.get_unchecked(i).cost == !0 {
break;
}
}
turn_cost += 1000;
(curr, next) = (next, curr);
curr.get_unchecked_mut(k).cost = !0;
}
// let mut curr = Vec::<Node>::from_iter([Node {
// pos: far_edge!() * row_len!() + 1,
// dir: 0,
// cost: 0,
// }]);
// let mut next = Vec::<Node>::from_iter([Node {
// pos: !0,
// dir: !0,
// cost: !0,
// }]);
// let mut i = 0;
// let mut turn_cost = 0;
// let mut visited = [0u8; row_len!() * side_len!()];
// loop {
// // let mut map = s.to_vec();
// // for node in &front {
// // map[node.pos as usize] = b">v<^"[node.dir as usize];
// // }
// // for node in &curr {
// // map[node.pos as usize] = b'*';
// // }
// // for node in &next {
// // map[node.pos as usize] = b'+';
// // }
// // for y in 0..side_len!() {
// // println!(
// // "{}",
// // std::str::from_utf8(&map[y * row_len!()..y * row_len!() + side_len!()]).unwrap()
// // );
// // }
// let mut node = curr.get_unchecked_mut(i);
// let curr_cost = node.cost;
// let mut j = i;
// loop {
// let node = curr.get_unchecked_mut(j);
// if *visited.get_unchecked(node.pos as usize) & 1 << node.dir != 0 {
// *curr.get_unchecked_mut(j) = *curr.get_unchecked(i);
// i += 1;
// } else {
// if node.pos == row_len!() + far_edge!() {
// return turn_cost + node.cost as u32 * 2 + 2;
// }
// macro_rules! offset {
// ($dir:expr) => {
// *[1i16, row_len!(), -1, -row_len!()].get_unchecked($dir as usize)
// };
// }
// }
// if j == curr.len() {
// break;
// }
// }
// if i == curr.len() {
// (curr, next) = (next, curr);
// i = 0;
// turn_cost += 1000;
// }
// // front.retain_mut(
// // |&mut Node {
// // pos: ref mut pos_ref,
// // dir,
// // cost: ref mut cost_ref,
// // }| {
// // if found_end {
// // return false;
// // }
// // let pos = *pos_ref;
// // let cost = *cost_ref + 1;
// // if pos == row_len!() + far_edge!() {
// // found_end = true;
// // return true;
// // }
// // macro_rules! offset {
// // ($dir:expr) => {
// // *[1i16, row_len!(), -1, -row_len!()].get_unchecked($dir as usize)
// // };
// // }
// // let off = offset!(dir);
// // let mut npos = pos.wrapping_add_signed(off);
// // let retain = if *s.get_unchecked(npos as usize) != b'#' && {
// // npos = npos.wrapping_add_signed(off);
// // *visited.get_unchecked(npos as usize) & 5 << (dir & 1) == 0
// // } {
// // *visited.get_unchecked_mut(npos as usize) |= 1 << dir;
// // *cost_ref = cost;
// // *pos_ref = npos;
// // true
// // } else {
// // false
// // };
// // let dir = dir ^ 1;
// // let off = offset!(dir);
// // let mut npos = pos.wrapping_add_signed(off);
// // if *s.get_unchecked(npos as usize) != b'#' && {
// // npos = npos.wrapping_add_signed(off);
// // *visited.get_unchecked(npos as usize) & 5 << (dir & 1) == 0
// // } {
// // *visited.get_unchecked_mut(npos as usize) |= 1 << dir;
// // next.push_back(Node { pos: npos, dir, cost });
// // }
// // let dir = dir ^ 2;
// // let off = offset!(dir);
// // let mut npos = pos.wrapping_add_signed(off);
// // if *s.get_unchecked(npos as usize) != b'#' && {
// // npos = npos.wrapping_add_signed(off);
// // *visited.get_unchecked(npos as usize) & 5 << (dir & 1) == 0
// // } {
// // *visited.get_unchecked_mut(npos as usize) |= 1 << dir;
// // next.push_back(Node { pos: npos, dir, cost });
// // }
// // retain
// // },
// // );
// // if found_end {
// // return turn_cost + front.back().unwrap_unchecked().cost as u32 * 2;
// // }
// }
}
#[inline]
unsafe fn inner2(s: &[u8]) -> u32 {
0
}
#[inline]
pub fn run(s: &str) -> impl Display {
unsafe { inner1(s.as_bytes()) }
}
#[inline]
pub fn part2(s: &str) -> impl Display {
unsafe { inner2(s.as_bytes()) }
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d12p2.rs | 2024/d12p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
#[cfg(debug_assertions)]
let real_input = input;
let mut edges = const {
let mut edges = [0; 141 + 141 * 141 + 32];
let mut i = 0;
while i < 141 {
edges[141 + 0 * 141 + i] = 1;
i += 1;
}
edges[141 + 0] += 1;
edges
};
let mut array = [MaybeUninit::<u8>::uninit(); 141 + 141 * 141 + 32];
array.get_unchecked_mut(..141).fill(MaybeUninit::new(b'\n'));
std::ptr::copy(
input.as_ptr(),
array.as_mut_ptr().add(141).cast(),
140 * 141,
);
array
.get_unchecked_mut(141 + 140 * 141..)
.fill(MaybeUninit::new(b'\n'));
let input = &mut *((&raw mut array) as *mut [u8; 141 + 141 * 141 + 32]);
// TODO: bitmap to which neighbours are equal -> switch table
let mut off = 141;
while off < 141 + 140 * 141 {
let o1 = off;
let o2 = off + 1;
let o3 = off + 141;
let b1 = u8x32::from_slice(input.get_unchecked(o1..o1 + 32));
let b2 = u8x32::from_slice(input.get_unchecked(o2..o2 + 32));
let b3 = u8x32::from_slice(input.get_unchecked(o3..o3 + 32));
let t = b1.simd_ne(b2);
let l = b1.simd_ne(b3);
let mut s1 = i8x32::from_slice(edges.get_unchecked(o1..o1 + 32));
s1 += t.to_int() & i8x32::splat(1);
s1 += l.to_int() & i8x32::splat(1);
*edges.get_unchecked_mut(o1) = s1[0];
let mut s2 = s1.rotate_elements_left::<1>();
s2[31] = *edges.get_unchecked(o2 + 32 - 1);
s2 += t.to_int() & i8x32::splat(1);
s2.copy_to_slice(edges.get_unchecked_mut(o2..o2 + 32));
let mut s3 = i8x32::from_slice(edges.get_unchecked(o3..o3 + 32));
s3 += l.to_int() & i8x32::splat(1);
s3.copy_to_slice(edges.get_unchecked_mut(o3..o3 + 32));
off += 32;
}
#[cfg(debug_assertions)]
{
let mut expected = [0; 140 * 141];
for y in 0..140 {
for x in 0..140 {
let c = real_input[141 * y + x];
let mut n = 0;
if x == 0 || real_input[141 * y + (x - 1)] != c {
n += 1;
}
if x == 140 || real_input[141 * y + (x + 1)] != c {
n += 1;
}
if y == 0 || real_input[141 * (y - 1) + x] != c {
n += 1;
}
if y == 139 || real_input[141 * (y + 1) + x] != c {
n += 1;
}
expected[141 * y + x] = n;
}
}
for y in 0..140 {
for x in 0..140 {
assert_eq!(
edges[141 + 141 * y + x],
expected[141 * y + x],
"x={x} y={y}"
);
}
}
}
collect(&input, &edges)
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
#[cfg(debug_assertions)]
let real_input = input;
let mut corners = [0; 141 + 141 * 141 + 32];
corners[141 + 0] += 1;
let mut array = [MaybeUninit::<u8>::uninit(); 141 + 141 * 141 + 32];
array.get_unchecked_mut(..141).fill(MaybeUninit::new(b'\n'));
std::ptr::copy(
input.as_ptr(),
array.as_mut_ptr().add(141).cast(),
140 * 141,
);
array
.get_unchecked_mut(141 + 140 * 141..)
.fill(MaybeUninit::new(b'\n'));
let input = &mut *((&raw mut array) as *mut [u8; 141 + 141 * 141 + 32]);
// TODO: bitmap to which neighbours are equal -> switch table
let mut off = 0;
while off < 141 + 140 * 141 {
let o1 = off;
let o2 = off + 1;
let o3 = off + 141;
let o4 = off + 1 + 141;
let b1 = u8x32::from_slice(input.get_unchecked(o1..o1 + 32));
let b2 = u8x32::from_slice(input.get_unchecked(o2..o2 + 32));
let b3 = u8x32::from_slice(input.get_unchecked(o3..o3 + 32));
let b4 = u8x32::from_slice(input.get_unchecked(o4..o4 + 32));
let t = b1.simd_ne(b2);
let b = b3.simd_ne(b4);
let l = b1.simd_ne(b3);
let r = b2.simd_ne(b4);
let d1 = b1.simd_ne(b4);
let d2 = b2.simd_ne(b3);
let mut s1 = i8x32::from_slice(corners.get_unchecked(o1..o1 + 32));
s1 += (t.simd_eq(l) & (d1 | t)).to_int() & i8x32::splat(1);
*corners.get_unchecked_mut(o1) = s1[0];
let mut s2 = s1.rotate_elements_left::<1>();
s2[31] = *corners.get_unchecked(o2 + 32 - 1);
s2 += (t.simd_eq(r) & (d2 | t)).to_int() & i8x32::splat(1);
s2.copy_to_slice(corners.get_unchecked_mut(o2..o2 + 32));
let mut s3 = i8x32::from_slice(corners.get_unchecked(o3..o3 + 32));
s3 += (b.simd_eq(l) & (d2 | b)).to_int() & i8x32::splat(1);
*corners.get_unchecked_mut(o3) = s3[0];
let mut s4 = s3.rotate_elements_left::<1>();
s4[31] = *corners.get_unchecked(o4 + 32 - 1);
s4 += (b.simd_eq(r) & (d1 | b)).to_int() & i8x32::splat(1);
s4.copy_to_slice(corners.get_unchecked_mut(o4..o4 + 32));
off += 32;
}
#[cfg(debug_assertions)]
{
let mut expected = [0; 140 * 141];
for y in 0..140 {
for x in 0..140 {
let c = real_input[141 * y + x];
let mut n = 0;
let t = (y != 0).then(|| real_input[141 * (y - 1) + x]);
let b = (y != 139).then(|| real_input[141 * (y + 1) + x]);
let l = (x != 0).then(|| real_input[141 * y + (x - 1)]);
let r = (x != 139).then(|| real_input[141 * y + (x + 1)]);
let tl = (y != 0 && x != 0).then(|| real_input[141 * (y - 1) + (x - 1)]);
let tr = (y != 0 && x != 139).then(|| real_input[141 * (y - 1) + (x + 1)]);
let bl = (y != 139 && x != 0).then(|| real_input[141 * (y + 1) + (x - 1)]);
let br = (y != 139 && x != 139).then(|| real_input[141 * (y + 1) + (x + 1)]);
n += (t != Some(c) && l != Some(c)) as i8;
n += (t != Some(c) && r != Some(c)) as i8;
n += (b != Some(c) && l != Some(c)) as i8;
n += (b != Some(c) && r != Some(c)) as i8;
n += (t == Some(c) && l == Some(c) && tl != Some(c)) as i8;
n += (t == Some(c) && r == Some(c) && tr != Some(c)) as i8;
n += (b == Some(c) && l == Some(c) && bl != Some(c)) as i8;
n += (b == Some(c) && r == Some(c) && br != Some(c)) as i8;
expected[141 * y + x] = n;
}
}
for y in 0..140 {
for x in 0..140 {
assert_eq!(
corners[141 + 141 * y + x],
expected[141 * y + x],
"got={}, expected={}, x={x}, y={y}",
corners[141 + 141 * y + x],
expected[141 * y + x],
);
}
}
}
collect(&input, &corners)
}
#[inline(always)]
unsafe fn collect(input: &[u8; 141 + 141 * 141 + 32], extra: &[i8; 141 + 141 * 141 + 32]) -> u64 {
let mut lens = [140 / par::NUM_THREADS; par::NUM_THREADS];
for i in 0..140 % par::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par::NUM_THREADS + 1];
for i in 0..par::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let mut uf = [MaybeUninit::<u64>::uninit(); 141 + 140 * 141];
let uf = uf.as_mut_ptr().cast::<u64>();
let acc = std::sync::atomic::AtomicU64::new(0);
par::par(|idx| {
let mut tot = 0;
// First line: no union with top
{
let y = poss[idx];
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
for x in 0..140 {
let off = 141 + 141 * y + x;
let c = *input.get_unchecked(off);
let e = *extra.get_unchecked(off) as u8 as u64;
*uf.add(off) = root as u64;
if c != prev_c {
prev_c = c;
root = off;
*uf.add(off) = 0;
}
let t = &mut *uf.add(root).cast::<[u32; 2]>();
t[1] += 1;
tot += t[1] as u64 * e as u64 + t[0] as u64;
t[0] += e as u32;
}
}
for y in poss[idx] + 1..poss[idx + 1] {
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
let mut top_prev = u32::MAX as u64;
for x in 0..140 {
let off = 141 + 141 * y + x;
let c = *input.get_unchecked(off);
let e = *extra.get_unchecked(off) as u8 as u64;
*uf.add(off) = root as u64;
if c != prev_c {
prev_c = c;
root = off;
*uf.add(off) = 0;
}
let t = &mut *uf.add(root).cast::<[u32; 2]>();
t[1] += 1;
tot += t[1] as u64 * e as u64 + t[0] as u64;
t[0] += e as u32;
let top = off - 141;
let tt = *uf.add(top);
if tt != top_prev {
top_prev = top as u64;
}
if (top_prev == top as u64 || root == off) && *input.get_unchecked(top) == c {
let mut tt_root = top;
while *uf.add(tt_root).cast::<u32>().add(1) == 0 {
tt_root = *uf.add(tt_root).cast::<u32>() as usize;
}
if tt_root != root {
let t2 = &mut *uf.add(tt_root).cast::<[u32; 2]>();
tot += t[1] as u64 * t2[0] as u64 + t[0] as u64 * t2[1] as u64;
t[1] += t2[1];
t[0] += t2[0];
*uf.add(tt_root) = root as u64;
}
}
}
}
const LEVELS: usize = par::NUM_THREADS.ilog2() as usize;
const { assert!(1 << LEVELS == par::NUM_THREADS) };
for i in 0..LEVELS {
if idx & (1 << i) != 0 {
break;
}
let next = idx + (1 << i);
par::wait(next);
let y = poss[next];
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
let mut top_prev = u32::MAX as u64;
for x in 0..140 {
let off = 141 + 141 * y + x;
let top = off - 141;
let c = *input.get_unchecked(off);
let mut c_changed = false;
if c != prev_c {
prev_c = c;
c_changed = true;
root = off;
while *uf.add(root).cast::<u32>().add(1) == 0 {
root = *uf.add(root).cast::<u32>() as usize;
}
}
let tt = *uf.add(top);
if tt != top_prev {
top_prev = top as u64;
}
if (top_prev == top as u64 || c_changed) && *input.get_unchecked(top) == c {
let mut tt_root = top;
while *uf.add(tt_root).cast::<u32>().add(1) == 0 {
tt_root = *uf.add(tt_root).cast::<u32>() as usize;
}
if tt_root != root {
let t = &mut *uf.add(root).cast::<[u32; 2]>();
let t2 = &mut *uf.add(tt_root).cast::<[u32; 2]>();
tot += t[1] as u64 * t2[0] as u64 + t[0] as u64 * t2[1] as u64;
t[1] += t2[1];
t[0] += t2[0];
*uf.add(tt_root) = root as u64;
}
}
}
}
if idx & 1 == 0 {}
acc.fetch_add(tot, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d20p2.rs | 2024/d20p2.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::mem::transmute;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part2(input) as i64
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
const LEFT: usize = -1isize as usize;
const RIGHT: usize = 1isize as usize;
const UP: usize = -142isize as usize;
const DOWN: usize = 142isize as usize;
#[inline(always)]
unsafe fn find_start(input: &[u8]) -> usize {
let mut offset = 0;
loop {
let block = u8x64::from_slice(input.get_unchecked(offset..offset + 64));
let mask = block.simd_eq(u8x64::splat(b'S')).to_bitmask();
if mask != 0 {
break offset + mask.trailing_zeros() as usize;
}
offset += 64;
}
}
const SLINE: usize = 139 + 28;
const SUP: usize = -(SLINE as isize) as usize;
const SDOWN: usize = SLINE;
const SLEFT: usize = LEFT;
const SRIGHT: usize = RIGHT;
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
unsafe fn part2_rec<const IDIR: usize, const SDIR: usize>(
input: &[u8; 141 * 142],
seen: &mut [i16; 20 + (139 + 40) * SLINE],
icurr: usize,
scurr: usize,
mut n: i16,
) {
*seen.get_unchecked_mut(scurr) = n;
n += 1;
macro_rules! next {
($($d1:ident $d2:ident),*) => {$(
if $d1 != -(IDIR as isize) as usize {
let icand = icurr.wrapping_add($d1);
let scand = scurr.wrapping_add($d2);
if *input.get_unchecked(icand) != b'#' {
// TODO: use become
part2_rec::<$d1, $d2>(input, seen, icand, scand, n);
return
}
}
)*};
}
next!(LEFT SLEFT, RIGHT SRIGHT, UP SUP, DOWN SDOWN);
}
let input: &[u8; 141 * 142] = input.as_bytes().try_into().unwrap_unchecked();
let s = find_start(input);
let mut seen = [i16::MAX; 20 + (139 + 40) * SLINE];
let icurr = s;
let scurr = 20 + SLINE * (s / 142 - 1 + 20) + (s % 142 - 1);
let n = 0;
macro_rules! next {
($($d1:ident $d2:ident),*) => {$(
let icand = icurr.wrapping_add($d1);
if *input.get_unchecked(icand) != b'#' {
part2_rec::<$d1, $d2>(input, &mut seen, icurr, scurr, n);
}
)*};
}
next!(LEFT SLEFT, RIGHT SRIGHT, UP SUP, DOWN SDOWN);
const THREADS: usize = 16;
const BASE: usize = 143;
const REAL_LEN: usize = 141 * 142 - 2 * BASE + 8;
const STEP: usize = REAL_LEN / THREADS;
const { assert!(REAL_LEN % THREADS == 0) }
let sum = std::sync::atomic::AtomicU64::new(0);
par::par(|thread| {
let start = BASE + thread * STEP;
let end = start + STEP;
let mut count = i32x16::splat(0);
for icurr in start..end {
if *input.get_unchecked(icurr) == b'#' || *input.get_unchecked(icurr) == b'\n' {
continue;
}
let scurr = 20 + SLINE * (icurr / 142 - 1 + 20) + (icurr % 142 - 1);
let n = *seen.get_unchecked(scurr);
count += sum_cheats(scurr, n, &seen);
}
sum.fetch_add(
-count.reduce_sum() as u64,
std::sync::atomic::Ordering::Relaxed,
);
});
sum.into_inner()
}
#[inline(always)]
unsafe fn sum_cheats(scurr: usize, n: i16, seen: &[i16; 20 + (139 + 40) * SLINE]) -> i32x16 {
const fn offset_distances() -> ([usize; 75], [[i16; 16]; 75]) {
let mut offs = [0; 75];
let mut dists = [[i16::MAX; 16]; 75];
let mut pos = 0;
let line = SLINE as isize;
let (mut ls, mut le) = (-line * 20, -line * 20);
let end = line * 20;
let mut d = 1;
while ls <= end {
let mid = (ls + le) / 2;
let base = (mid / line).abs();
let mut ts = ls;
while ts <= le {
offs[pos] = ts as usize;
let mut i = 0;
while i < 16 && ts + i <= le {
let is = ts + i;
dists[pos][i as usize] = 100 + base as i16 + is.abs_diff(mid) as i16 - 1;
i += 1;
}
pos += 1;
ts += 16;
}
if ls == -20 {
d = -1;
}
ls = ls - d + line;
le = le + d + line;
}
(offs, dists)
}
const OFFSETS: [usize; 75] = unsafe { transmute(offset_distances().0) };
const DISTANCES: [i16x16; 75] = unsafe { transmute(offset_distances().1) };
let mut count = i16x16::splat(0);
macro_rules! handle {
($i:expr) => {{
let offset = OFFSETS[$i];
let dists = DISTANCES[$i];
let base = scurr.wrapping_add(offset);
let s = seen.get_unchecked(base..base + 16);
let m = (i16x16::splat(n) - dists).simd_gt(i16x16::from_slice(s));
count += m.to_int();
}};
}
for i in 0..25 {
handle!(i)
}
for i in 25..50 {
handle!(i)
}
for i in 50..75 {
handle!(i)
}
count.cast::<i32>()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
fn wait() {
for i in 1..NUM_THREADS {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d04p2.rs | 2024/d04p2.rs | // Original by: bendn
#![feature(portable_simd)]
// type bitset = bitvec::BitArr!(for 140, in u64);
// pub mod set {
// uint::construct_uint! {pub struct bitset(3); }
// }
// use set::bitset;
use cmp::SimdPartialEq;
use std::simd::*;
const SIZE: usize = 140;
fn bits(input: &[u8], i: usize) -> u64 {
let w = u8x64::from_slice(&input[64 * i..]);
let x = u8x64::from_slice(&input[64 * i + 2..]);
let a = u8x64::from_slice(&input[141 + 64 * i + 1..]);
let y = u8x64::from_slice(&input[141 * 2 + 64 * i..]);
let z = u8x64::from_slice(&input[141 * 2 + 64 * i + 2..]);
let wz = ((w ^ z) + (x ^ y)).simd_eq(u8x64::splat((b'M' ^ b'S') + (b'M' ^ b'S')));
// let xy = (x ^ y).simd_eq(u8x64::splat(b'M' ^ b'S'));
let a = a.simd_eq(u8x64::splat(b'A'));
(wz & a).to_bitmask()
}
pub fn run(input: &[u8]) -> u32 {
assert_eq!(input.len(), 141 * 140);
let mut sum = 0;
for i in 0..304 {
sum += bits(input, i).count_ones();
}
sum
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d12p1.rs | 2024/d12p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
use std::mem::MaybeUninit;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let input = input.as_bytes();
#[cfg(debug_assertions)]
let real_input = input;
let mut edges = const {
let mut edges = [0; 141 + 141 * 141 + 32];
let mut i = 0;
while i < 141 {
edges[141 + 0 * 141 + i] = 1;
i += 1;
}
edges[141 + 0] += 1;
edges
};
let mut array = [MaybeUninit::<u8>::uninit(); 141 + 141 * 141 + 32];
array.get_unchecked_mut(..141).fill(MaybeUninit::new(b'\n'));
std::ptr::copy(
input.as_ptr(),
array.as_mut_ptr().add(141).cast(),
140 * 141,
);
array
.get_unchecked_mut(141 + 140 * 141..)
.fill(MaybeUninit::new(b'\n'));
let input = &mut *((&raw mut array) as *mut [u8; 141 + 141 * 141 + 32]);
// TODO: bitmap to which neighbours are equal -> switch table
let mut off = 141;
while off < 141 + 140 * 141 {
let o1 = off;
let o2 = off + 1;
let o3 = off + 141;
let b1 = u8x32::from_slice(input.get_unchecked(o1..o1 + 32));
let b2 = u8x32::from_slice(input.get_unchecked(o2..o2 + 32));
let b3 = u8x32::from_slice(input.get_unchecked(o3..o3 + 32));
let t = b1.simd_ne(b2);
let l = b1.simd_ne(b3);
let mut s1 = i8x32::from_slice(edges.get_unchecked(o1..o1 + 32));
s1 += t.to_int() & i8x32::splat(1);
s1 += l.to_int() & i8x32::splat(1);
*edges.get_unchecked_mut(o1) = s1[0];
let mut s2 = s1.rotate_elements_left::<1>();
s2[31] = *edges.get_unchecked(o2 + 32 - 1);
s2 += t.to_int() & i8x32::splat(1);
s2.copy_to_slice(edges.get_unchecked_mut(o2..o2 + 32));
let mut s3 = i8x32::from_slice(edges.get_unchecked(o3..o3 + 32));
s3 += l.to_int() & i8x32::splat(1);
s3.copy_to_slice(edges.get_unchecked_mut(o3..o3 + 32));
off += 32;
}
#[cfg(debug_assertions)]
{
let mut expected = [0; 140 * 141];
for y in 0..140 {
for x in 0..140 {
let c = real_input[141 * y + x];
let mut n = 0;
if x == 0 || real_input[141 * y + (x - 1)] != c {
n += 1;
}
if x == 140 || real_input[141 * y + (x + 1)] != c {
n += 1;
}
if y == 0 || real_input[141 * (y - 1) + x] != c {
n += 1;
}
if y == 139 || real_input[141 * (y + 1) + x] != c {
n += 1;
}
expected[141 * y + x] = n;
}
}
for y in 0..140 {
for x in 0..140 {
assert_eq!(
edges[141 + 141 * y + x],
expected[141 * y + x],
"x={x} y={y}"
);
}
}
}
collect(&input, &edges)
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
#[cfg(debug_assertions)]
let real_input = input;
let mut corners = [0; 141 + 141 * 141 + 32];
corners[141 + 0] += 1;
let mut array = [MaybeUninit::<u8>::uninit(); 141 + 141 * 141 + 32];
array.get_unchecked_mut(..141).fill(MaybeUninit::new(b'\n'));
std::ptr::copy(
input.as_ptr(),
array.as_mut_ptr().add(141).cast(),
140 * 141,
);
array
.get_unchecked_mut(141 + 140 * 141..)
.fill(MaybeUninit::new(b'\n'));
let input = &mut *((&raw mut array) as *mut [u8; 141 + 141 * 141 + 32]);
// TODO: bitmap to which neighbours are equal -> switch table
let mut off = 0;
while off < 141 + 140 * 141 {
let o1 = off;
let o2 = off + 1;
let o3 = off + 141;
let o4 = off + 1 + 141;
let b1 = u8x32::from_slice(input.get_unchecked(o1..o1 + 32));
let b2 = u8x32::from_slice(input.get_unchecked(o2..o2 + 32));
let b3 = u8x32::from_slice(input.get_unchecked(o3..o3 + 32));
let b4 = u8x32::from_slice(input.get_unchecked(o4..o4 + 32));
let t = b1.simd_ne(b2);
let b = b3.simd_ne(b4);
let l = b1.simd_ne(b3);
let r = b2.simd_ne(b4);
let d1 = b1.simd_ne(b4);
let d2 = b2.simd_ne(b3);
let mut s1 = i8x32::from_slice(corners.get_unchecked(o1..o1 + 32));
s1 += (t.simd_eq(l) & (d1 | t)).to_int() & i8x32::splat(1);
*corners.get_unchecked_mut(o1) = s1[0];
let mut s2 = s1.rotate_elements_left::<1>();
s2[31] = *corners.get_unchecked(o2 + 32 - 1);
s2 += (t.simd_eq(r) & (d2 | t)).to_int() & i8x32::splat(1);
s2.copy_to_slice(corners.get_unchecked_mut(o2..o2 + 32));
let mut s3 = i8x32::from_slice(corners.get_unchecked(o3..o3 + 32));
s3 += (b.simd_eq(l) & (d2 | b)).to_int() & i8x32::splat(1);
*corners.get_unchecked_mut(o3) = s3[0];
let mut s4 = s3.rotate_elements_left::<1>();
s4[31] = *corners.get_unchecked(o4 + 32 - 1);
s4 += (b.simd_eq(r) & (d1 | b)).to_int() & i8x32::splat(1);
s4.copy_to_slice(corners.get_unchecked_mut(o4..o4 + 32));
off += 32;
}
#[cfg(debug_assertions)]
{
let mut expected = [0; 140 * 141];
for y in 0..140 {
for x in 0..140 {
let c = real_input[141 * y + x];
let mut n = 0;
let t = (y != 0).then(|| real_input[141 * (y - 1) + x]);
let b = (y != 139).then(|| real_input[141 * (y + 1) + x]);
let l = (x != 0).then(|| real_input[141 * y + (x - 1)]);
let r = (x != 139).then(|| real_input[141 * y + (x + 1)]);
let tl = (y != 0 && x != 0).then(|| real_input[141 * (y - 1) + (x - 1)]);
let tr = (y != 0 && x != 139).then(|| real_input[141 * (y - 1) + (x + 1)]);
let bl = (y != 139 && x != 0).then(|| real_input[141 * (y + 1) + (x - 1)]);
let br = (y != 139 && x != 139).then(|| real_input[141 * (y + 1) + (x + 1)]);
n += (t != Some(c) && l != Some(c)) as i8;
n += (t != Some(c) && r != Some(c)) as i8;
n += (b != Some(c) && l != Some(c)) as i8;
n += (b != Some(c) && r != Some(c)) as i8;
n += (t == Some(c) && l == Some(c) && tl != Some(c)) as i8;
n += (t == Some(c) && r == Some(c) && tr != Some(c)) as i8;
n += (b == Some(c) && l == Some(c) && bl != Some(c)) as i8;
n += (b == Some(c) && r == Some(c) && br != Some(c)) as i8;
expected[141 * y + x] = n;
}
}
for y in 0..140 {
for x in 0..140 {
assert_eq!(
corners[141 + 141 * y + x],
expected[141 * y + x],
"got={}, expected={}, x={x}, y={y}",
corners[141 + 141 * y + x],
expected[141 * y + x],
);
}
}
}
collect(&input, &corners)
}
#[inline(always)]
unsafe fn collect(input: &[u8; 141 + 141 * 141 + 32], extra: &[i8; 141 + 141 * 141 + 32]) -> u64 {
let mut lens = [140 / par::NUM_THREADS; par::NUM_THREADS];
for i in 0..140 % par::NUM_THREADS {
lens[i] += 1;
}
let mut poss = [0; par::NUM_THREADS + 1];
for i in 0..par::NUM_THREADS {
poss[i + 1] = poss[i] + lens[i];
}
let mut uf = [MaybeUninit::<u64>::uninit(); 141 + 140 * 141];
let uf = uf.as_mut_ptr().cast::<u64>();
let acc = std::sync::atomic::AtomicU64::new(0);
par::par(|idx| {
let mut tot = 0;
// First line: no union with top
{
let y = poss[idx];
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
for x in 0..140 {
let off = 141 + 141 * y + x;
let c = *input.get_unchecked(off);
let e = *extra.get_unchecked(off) as u8 as u64;
*uf.add(off) = root as u64;
if c != prev_c {
prev_c = c;
root = off;
*uf.add(off) = 0;
}
let t = &mut *uf.add(root).cast::<[u32; 2]>();
t[1] += 1;
tot += t[1] as u64 * e as u64 + t[0] as u64;
t[0] += e as u32;
}
}
for y in poss[idx] + 1..poss[idx + 1] {
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
let mut top_prev = u32::MAX as u64;
for x in 0..140 {
let off = 141 + 141 * y + x;
let c = *input.get_unchecked(off);
let e = *extra.get_unchecked(off) as u8 as u64;
*uf.add(off) = root as u64;
if c != prev_c {
prev_c = c;
root = off;
*uf.add(off) = 0;
}
let t = &mut *uf.add(root).cast::<[u32; 2]>();
t[1] += 1;
tot += t[1] as u64 * e as u64 + t[0] as u64;
t[0] += e as u32;
let top = off - 141;
let tt = *uf.add(top);
if tt != top_prev {
top_prev = top as u64;
}
if (top_prev == top as u64 || root == off) && *input.get_unchecked(top) == c {
let mut tt_root = top;
while *uf.add(tt_root).cast::<u32>().add(1) == 0 {
tt_root = *uf.add(tt_root).cast::<u32>() as usize;
}
if tt_root != root {
let t2 = &mut *uf.add(tt_root).cast::<[u32; 2]>();
tot += t[1] as u64 * t2[0] as u64 + t[0] as u64 * t2[1] as u64;
t[1] += t2[1];
t[0] += t2[0];
*uf.add(tt_root) = root as u64;
}
}
}
}
const LEVELS: usize = par::NUM_THREADS.ilog2() as usize;
const { assert!(1 << LEVELS == par::NUM_THREADS) };
for i in 0..LEVELS {
if idx & (1 << i) != 0 {
break;
}
let next = idx + (1 << i);
par::wait(next);
let y = poss[next];
let mut prev_c = u8::MAX;
let mut root = usize::MAX;
let mut top_prev = u32::MAX as u64;
for x in 0..140 {
let off = 141 + 141 * y + x;
let top = off - 141;
let c = *input.get_unchecked(off);
let mut c_changed = false;
if c != prev_c {
prev_c = c;
c_changed = true;
root = off;
while *uf.add(root).cast::<u32>().add(1) == 0 {
root = *uf.add(root).cast::<u32>() as usize;
}
}
let tt = *uf.add(top);
if tt != top_prev {
top_prev = top as u64;
}
if (top_prev == top as u64 || c_changed) && *input.get_unchecked(top) == c {
let mut tt_root = top;
while *uf.add(tt_root).cast::<u32>().add(1) == 0 {
tt_root = *uf.add(tt_root).cast::<u32>() as usize;
}
if tt_root != root {
let t = &mut *uf.add(root).cast::<[u32; 2]>();
let t2 = &mut *uf.add(tt_root).cast::<[u32; 2]>();
tot += t[1] as u64 * t2[0] as u64 + t[0] as u64 * t2[1] as u64;
t[1] += t2[1];
t[0] += t2[0];
*uf.add(tt_root) = root as u64;
}
}
}
}
if idx & 1 == 0 {}
acc.fetch_add(tot, std::sync::atomic::Ordering::Relaxed);
});
acc.into_inner()
}
mod par {
use std::sync::atomic::{AtomicPtr, Ordering};
pub const NUM_THREADS: usize = 16;
#[repr(align(64))]
struct CachePadded<T>(T);
static mut INIT: bool = false;
static WORK: [CachePadded<AtomicPtr<()>>; NUM_THREADS] =
[const { CachePadded(AtomicPtr::new(std::ptr::null_mut())) }; NUM_THREADS];
#[inline(always)]
fn submit<F: Fn(usize)>(f: &F) {
unsafe {
if !INIT {
INIT = true;
for idx in 1..NUM_THREADS {
thread_run(idx, f);
}
}
}
for i in 1..NUM_THREADS {
WORK[i].0.store(f as *const F as *mut (), Ordering::Release);
}
}
#[inline(always)]
pub fn wait(i: usize) {
loop {
let ptr = WORK[i].0.load(Ordering::Acquire);
if ptr.is_null() {
break;
}
std::hint::spin_loop();
}
}
#[inline(always)]
fn wait_all() {
for i in 1..NUM_THREADS {
wait(i);
}
}
fn thread_run<F: Fn(usize)>(idx: usize, _f: &F) {
_ = std::thread::Builder::new().spawn(move || unsafe {
let work = WORK.get_unchecked(idx);
loop {
let data = work.0.load(Ordering::Acquire);
if !data.is_null() {
(&*data.cast::<F>())(idx);
work.0.store(std::ptr::null_mut(), Ordering::Release);
}
std::hint::spin_loop();
}
});
}
pub unsafe fn par<F: Fn(usize)>(f: F) {
submit(&f);
f(0);
wait_all();
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d06p1.rs | 2024/d06p1.rs | // Original by: doge
const WIDTH: usize = 131;
const HEIGHT: usize = 130;
const SIZE: usize = WIDTH * HEIGHT;
#[inline(always)]
unsafe fn inner(s: &[u8]) -> u32 {
let loc = memchr::memchr(b'^', s).unwrap_unchecked();
let mut new = [1_u8; SIZE];
let s_ptr = s.as_ptr();
let new_ptr = new.as_mut_ptr();
let slen = s.len();
let mut total = 0;
let mut loc = loc;
macro_rules! process_cell {
() => {{
let cell_ptr = new_ptr.add(loc);
total += *cell_ptr as u32;
*cell_ptr = 0;
}};
}
macro_rules! check_bounds {
($next_expr:expr, $check_expr:expr) => {{
process_cell!();
let next = $next_expr;
if $check_expr(next) {
return total;
}
let c = *s_ptr.add(next);
if c == b'#' {
break;
}
loc = next;
}};
}
'outer: loop {
// Up
loop {
check_bounds!(loc.wrapping_sub(WIDTH), |n| n >= slen);
}
// Right
loop {
check_bounds!(loc + 1, |n| *s_ptr.add(n) == b'\n');
}
// Down
loop {
check_bounds!(loc.wrapping_add(WIDTH), |n| n >= slen);
}
// Left
loop {
check_bounds!(loc.wrapping_sub(1), |n| *s_ptr.add(n) == b'\n');
}
}
}
#[inline(always)]
pub fn run(input: &[u8]) -> u32 {
unsafe { inner(input) }
}
#[test]
fn d6p1() {
assert_eq!(run(include_bytes!("./../input/day6.txt")), 5269);
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
indiv0/aoc-fastest | https://github.com/indiv0/aoc-fastest/blob/ca5efdd944ad509a05ad8e559632e7ee605a884c/2024/d22p1.rs | 2024/d22p1.rs | // Original by: giooschi
#![allow(unused_attributes)]
#![allow(static_mut_refs)]
#![feature(portable_simd)]
#![feature(avx512_target_feature)]
#![feature(slice_ptr_get)]
#![feature(array_ptr_get)]
#![feature(core_intrinsics)]
#![feature(int_roundings)]
use std::arch::x86_64::*;
use std::simd::prelude::*;
pub fn run(input: &str) -> i64 {
part1(input) as i64
}
#[inline(always)]
pub fn part1(input: &str) -> u64 {
unsafe { inner_part1(input) }
}
#[inline(always)]
pub fn part2(input: &str) -> u64 {
unsafe { inner_part2(input) }
// super::day22par::part2(input)
}
#[inline(always)]
pub(crate) fn parse8(n: u64) -> u32 {
use std::num::Wrapping as W;
let mut n = W(n);
let mask = W(0xFF | (0xFF << 32));
let mul1 = W(100 + (1000000 << 32));
let mul2 = W(1 + (10000 << 32));
n = (n * W(10)) + (n >> 8);
n = (((n & mask) * mul1) + (((n >> 16) & mask) * mul2)) >> 32;
n.0 as u32
}
macro_rules! parse {
($ptr:ident) => {{
let n = $ptr.cast::<u64>().read_unaligned();
let len = _pext_u64(n, 0x1010101010101010).trailing_ones();
let n = (n & 0x0F0F0F0F0F0F0F0F) << (8 * (8 - len));
$ptr = $ptr.add(len as usize + 1);
parse8(n)
}};
}
pub(crate) use parse;
pub(crate) const M: u32 = 16777216 - 1;
#[inline(always)]
pub(crate) fn next(mut n: u32) -> u32 {
n ^= n << 6;
n ^= (n & M) >> 5;
n ^= n << 11;
n
}
// static LUT1: [u32; 1 << 24] =
// unsafe { std::mem::transmute(*include_bytes!(concat!(env!("OUT_DIR"), "/d22p1.lut"))) };
#[allow(long_running_const_eval)]
static LUT1: [u32; 1 << 24] = {
let mut masks = [0; 24];
let mut i = 0;
while i < 24 {
let mut n = 1 << i;
let mut j = 0;
while j < 2000 {
n ^= n << 6;
n ^= (n & M) >> 5;
n ^= n << 11;
j += 1;
}
masks[i] = n & M;
i += 1;
}
let mut lut = [0u32; 1 << 24];
let mut i = 0;
while i < 24 {
let m = masks[i];
let mut n = 0;
let mn = 1 << i;
while n < mn {
lut[(1 << i) | n as usize] = lut[n as usize] ^ m;
n += 1;
}
i += 1;
}
lut
};
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part1(input: &str) -> u64 {
let mut ptr = input.as_ptr();
let mut sum = 0;
while ptr <= input.as_ptr().add(input.len() - 8) {
let n = parse!(ptr);
sum += *LUT1.get_unchecked((n & M) as usize) as u64;
}
if ptr != input.as_ptr().add(input.len()) {
let len = input.as_ptr().add(input.len()).offset_from(ptr) - 1;
let n = input
.as_ptr()
.add(input.len() - 1 - 8)
.cast::<u64>()
.read_unaligned();
let n = (n & 0x0F0F0F0F0F0F0F0F) & (u64::MAX << (8 * (8 - len)));
let n = parse8(n);
sum += *LUT1.get_unchecked((n & M) as usize) as u64;
};
sum
}
#[allow(unused)]
#[target_feature(enable = "popcnt,avx2,ssse3,bmi1,bmi2,lzcnt")]
#[cfg_attr(avx512_available, target_feature(enable = "avx512vl"))]
unsafe fn inner_part2(input: &str) -> u64 {
let input = input.as_bytes();
const COUNTS_LEN: usize = (20usize * 20 * 20 * 20).next_multiple_of(64);
let mut counts = [0u16; COUNTS_LEN];
macro_rules! handle {
($n:expr, $i:expr, $seen:ident) => {{
let mut n = $n;
let b1 = fastdiv::fastmod_u32_10(n);
n = next(n) & M;
let b2 = fastdiv::fastmod_u32_10(n);
n = next(n) & M;
let b3 = fastdiv::fastmod_u32_10(n);
n = next(n) & M;
let mut b4 = fastdiv::fastmod_u32_10(n);
let mut d1 = 9 + b1 - b2;
let mut d2 = 9 + b2 - b3;
let mut d3 = 9 + b3 - b4;
for _ in 3..2000 {
n = next(n) & M;
let b5 = fastdiv::fastmod_u32_10(n);
let d4 = 9 + b4 - b5;
let idx = (d1 + 20 * (d2 + 20 * (d3 + 20 * d4))) as usize;
let s = $seen.get_unchecked_mut(idx);
if *s != $i {
*s = $i;
*counts.get_unchecked_mut(idx) += b5 as u16;
}
(d1, d2, d3, b4) = (d2, d3, d4, b5);
}
}};
}
let mut seen = [0u8; COUNTS_LEN];
let mut i = 1;
let mut ptr = input.as_ptr();
while ptr <= input.as_ptr().add(input.len() - 8) {
let n = parse!(ptr);
handle!(n, i, seen);
i = i.wrapping_add(1);
if i == 0 {
i = 1;
seen = [0u8; COUNTS_LEN];
}
}
if ptr != input.as_ptr().add(input.len()) {
let len = input.as_ptr().add(input.len()).offset_from(ptr) - 1;
let n = input
.as_ptr()
.add(input.len() - 1 - 8)
.cast::<u64>()
.read_unaligned();
let n = (n & 0x0F0F0F0F0F0F0F0F) & (u64::MAX << (8 * (8 - len)));
let n = parse8(n);
handle!(n, i, seen);
}
let mut max = u16x16::splat(0);
for i in 0..COUNTS_LEN / 16 {
let b = u16x16::from_slice(counts.get_unchecked(16 * i..16 * i + 16));
max = max.simd_max(b);
}
max.reduce_max() as u64
}
mod fastdiv {
#[inline]
const fn mul128_u32(lowbits: u64, d: u32) -> u64 {
(lowbits as u128 * d as u128 >> 64) as u64
}
#[inline]
const fn compute_m_u32(d: u32) -> u64 {
(0xFFFFFFFFFFFFFFFF / d as u64) + 1
}
#[inline]
pub const fn fastmod_u32_10(a: u32) -> u32 {
const D: u32 = 10;
const M: u64 = compute_m_u32(D);
let lowbits = M.wrapping_mul(a as u64);
mul128_u32(lowbits, D) as u32
}
}
| rust | MIT | ca5efdd944ad509a05ad8e559632e7ee605a884c | 2026-01-04T20:19:58.878961Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/build.rs | build.rs | use std::fs::{read, read_to_string};
use embedinator::{Icon, ResourceBuilder};
include!("assets/ids.rs");
const ICONS: &[(u16, &str)] = &[
(APP_ICON, "assets/app.png"),
(BRIGHTNESS_LIGHT_ICON, "assets/brightness_light.png"),
(BRIGHTNESS_DARK_ICON, "assets/brightness_dark.png")
];
fn main() {
let mut res = ResourceBuilder::from_env().add_manifest(read_to_string("assets/app.manifest").unwrap());
println!("cargo:rerun-if-changed=assets/app.manifest");
println!("cargo:rerun-if-changed=assets/ids.rs");
for (id, name) in ICONS.iter().copied() {
println!("cargo:rerun-if-changed={}", name);
res = res.add_icon(id, Icon::from_png_bytes(read(name).unwrap()));
}
res.finish();
println!("cargo:rerun-if-changed=build.rs");
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/config.rs | src/config.rs | use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::os::windows::ffi::OsStringExt;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use log::debug;
use windows::core::imp::CoTaskMemFree;
use windows::Win32::UI::Shell::{FOLDERID_RoamingAppData, SHGetKnownFolderPath, KF_FLAG_DEFAULT};
use crate::monitors::MonitorPath;
use crate::Result;
use crate::windowing::hotkey::{KeyCombination, Modifier, VirtualKey};
#[derive(Debug)]
pub struct Config {
pub dirty: bool,
pub restore_from_config: bool,
pub use_prioritized_autostart: bool,
pub icon_scoll_enabled: bool,
pub icon_scroll_step_size: f32,
pub hotkeys_enabled: bool,
pub hotkey_step_size: f32,
pub brightness_increase_hotkey: KeyCombination,
pub brightness_decrease_hotkey: KeyCombination,
pub monitors: BTreeMap<MonitorPath, MonitorSettings>
}
impl Default for Config {
fn default() -> Self {
Self {
dirty: true,
restore_from_config: true,
use_prioritized_autostart: false,
icon_scoll_enabled: false,
icon_scroll_step_size: 5.0,
hotkeys_enabled: false,
hotkey_step_size: 10.0,
brightness_increase_hotkey: KeyCombination::from(([Modifier::Alt], VirtualKey::F1)),
brightness_decrease_hotkey: KeyCombination::from(([Modifier::Alt], VirtualKey::F2)),
monitors: Default::default(),
}
}
}
#[derive(Default, Debug)]
pub struct MonitorSettings {
pub saved_brightness: Option<u32>,
pub custom_name: Option<String>,
pub position: Option<i32>
}
impl Config {
pub fn path() -> &'static Path {
static PATH: OnceLock<PathBuf> = OnceLock::new();
PATH.get_or_init(|| {
unsafe { SHGetKnownFolderPath(&FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, None) }
.map(|ptr| unsafe {
let osstr = OsString::from_wide(ptr.as_wide());
CoTaskMemFree(ptr.as_ptr() as _);
osstr
})
.map(PathBuf::from)
.unwrap_or_else(|err| {
log::warn!("Failed to retrieve AppData location: {}", err);
log::info!("Falling back to current directory...");
PathBuf::from(".")
})
.join("rusty-twinkle-tray.ini")
})
}
pub fn restore() -> Result<Config> {
let mut config = Self::default();
if Self::path().exists() {
config.load()?;
}
Ok(config)
}
pub fn save_if_dirty(&self) -> Result<()> {
if self.dirty {
self.save()?;
}
Ok(())
}
pub fn monitor(&mut self, path: &MonitorPath) -> &mut MonitorSettings {
self.monitors.entry(path.clone()).or_default()
}
fn save(&self) -> Result<()> {
let mut file = BufWriter::new(File::create(Self::path())?);
write!(file, "[General]\r\n")?;
write!(file, "RestoreFromConfig={}\r\n", self.restore_from_config)?;
write!(file, "UsePrioritizedAutostart={}\r\n", self.use_prioritized_autostart)?;
write!(file, "IconScrollEnabled={}\r\n", self.icon_scoll_enabled)?;
write!(file, "IconScrollStepSize={}\r\n", self.icon_scroll_step_size)?;
write!(file, "HotkeysEnabled={}\r\n", self.hotkeys_enabled)?;
write!(file, "HotkeyStepSize={}\r\n", self.hotkey_step_size)?;
write!(file, "BrightnessIncreaseHotkey={}\r\n", self.brightness_increase_hotkey.display(false))?;
write!(file, "BrightnessDecreaseHotkey={}\r\n", self.brightness_decrease_hotkey.display(false))?;
write!(file, "\r\n")?;
for (path, settings) in &self.monitors {
if settings.saved_brightness.is_none() && settings.custom_name.is_none() && settings.position.is_none() {
continue;
}
write!(file, "[{}]\r\n", path.as_str())?;
if let Some(brightness) = settings.saved_brightness {
write!(file, "SavedBrightness={}\r\n", brightness)?;
}
if let Some(name) = &settings.custom_name {
write!(file, "CustomName={}\r\n", name)?;
}
if let Some(order) = settings.position {
write!(file, "Position={}\r\n", order)?;
}
write!(file, "\r\n")?;
}
Ok(())
}
fn load(&mut self) -> Result<()> {
let file = BufReader::new(File::open(Self::path())?);
let mut section = String::new();
for (number, line) in file.lines().enumerate() {
let line = line?;
let line = line.trim();
if line.is_empty() {
continue;
}
if line.starts_with('[') {
if !line.ends_with(']') {
return Err(format!("Invalid section (Line: {number})").into());
}
section = line[1..line.len() - 1].to_string();
continue;
}
if section.is_empty() {
return Err("No section".into());
}
let (key, value) = line
.split_once('=')
.ok_or_else(|| format!("Line \"{line}\" (#{number}) is not a key value pair"))?;
match section.as_str() {
"General" => match key {
"RestoreFromConfig" => self.restore_from_config = value.parse()?,
"UsePrioritizedAutostart" => self.use_prioritized_autostart = value.parse()?,
"IconScrollEnabled" => self.icon_scoll_enabled = value.parse()?,
"IconScrollStepSize" => self.icon_scroll_step_size = value.parse()?,
"HotkeysEnabled" => self.hotkeys_enabled = value.parse()?,
"HotkeyStepSize" => self.hotkey_step_size = value.parse()?,
"BrightnessIncreaseHotkey" => self.brightness_increase_hotkey = value.parse()?,
"BrightnessDecreaseHotkey" => self.brightness_decrease_hotkey = value.parse()?,
_ => debug!("Ignoring unknown key in section {}: {}={}", section, key, value)
},
path if path.starts_with("\\\\?\\DISPLAY") => {
let path = MonitorPath::from(path);
let settings = self.monitors.entry(path).or_default();
match key {
"SavedBrightness" => {
settings.saved_brightness = Some(value.parse()?);
}
"CustomName" => {
settings.custom_name = Some(value.to_string());
}
"Position" => {
settings.position = Some(value.parse()?);
}
_ => debug!("Ignoring unknown key in section {}: {}={}", section, key, value)
}
}
_ => debug!("Ignoring key in unknown section {}: {}={}", section, key, value)
}
}
Ok(())
}
}
pub mod autostart {
use std::path::PathBuf;
use std::sync::LazyLock;
use log::warn;
use registry::AutoStartRegKey;
use windows::core::{w, PCWSTR};
use windows::Win32::System::Registry::{KEY_READ, KEY_SET_VALUE};
static EXE_PATH: LazyLock<PathBuf> = LazyLock::new(|| {
std::env::current_exe()
.and_then(dunce::canonicalize)
.expect("Failed to get exe path")
});
// Programs seems to start in alphabetical order. So we prefix the name with an underscore.
const PROGRAM_KEY: PCWSTR = w!("_RustyTwinkleTray");
pub fn is_enabled(user: bool) -> bool {
AutoStartRegKey::new(user, KEY_READ)
.and_then(|reg| reg.read_path(PROGRAM_KEY))
.map_err(|e| warn!("Failed to read registry: {e}"))
.ok()
.flatten()
.map(|path| EXE_PATH.eq(&path))
.unwrap_or(false)
}
pub fn set_enabled(user: bool, enabled: bool) -> crate::Result<()> {
let reg = AutoStartRegKey::new(user, KEY_READ | KEY_SET_VALUE)?;
match enabled {
true => reg.write_path(PROGRAM_KEY, &EXE_PATH)?,
false => reg.delete(PROGRAM_KEY)?
}
Ok(())
}
mod registry {
use std::ffi::OsString;
use std::mem::zeroed;
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::slice;
use log::warn;
use windows::core::{w, HRESULT, PCWSTR};
use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_MORE_DATA};
use windows::Win32::System::Registry::{
RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE,
REG_EXPAND_SZ, REG_SAM_FLAGS, REG_SZ, REG_VALUE_TYPE
};
use crate::Result;
pub struct AutoStartRegKey {
handle: HKEY
}
impl AutoStartRegKey {
pub fn new(user: bool, permissions: REG_SAM_FLAGS) -> Result<Self> {
let handle = unsafe {
let mut handle = zeroed();
RegOpenKeyExW(
match user {
true => HKEY_CURRENT_USER,
false => HKEY_LOCAL_MACHINE
},
w!(r#"Software\Microsoft\Windows\CurrentVersion\Run"#),
0,
permissions,
&mut handle
)?;
handle
};
Ok(Self { handle })
}
pub fn read_path(&self, key: PCWSTR) -> Result<Option<PathBuf>> {
let mut buffer = vec![0u16; 256];
loop {
let mut size = buffer.len() as u32 * 2;
let mut ty = REG_VALUE_TYPE::default();
match unsafe { RegQueryValueExW(self.handle, key, None, Some(&mut ty), Some(buffer.as_mut_ptr() as _), Some(&mut size)) } {
Ok(()) => {
if !matches!(ty, REG_SZ | REG_EXPAND_SZ) {
return Err("Invalid registry item type".into());
}
let end = buffer.iter().take_while(|i| **i != 0).count();
return Ok(Some(PathBuf::from(OsString::from_wide(&buffer[..end]))));
}
Err(e) if e.code() == HRESULT::from_win32(ERROR_MORE_DATA.0) => buffer.resize(size as usize / 2, 0),
Err(e) if e.code() == HRESULT::from_win32(ERROR_FILE_NOT_FOUND.0) => return Ok(None),
Err(e) => return Err(e.into())
}
}
}
pub fn delete(&self, key: PCWSTR) -> Result<()> {
unsafe { RegDeleteValueW(self.handle, key)? };
Ok(())
}
pub fn write_path(&self, key: PCWSTR, path: &Path) -> Result<()> {
let path = path
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect::<Vec<_>>();
let path = unsafe { slice::from_raw_parts(path.as_ptr() as _, path.len() * 2) };
unsafe { RegSetValueExW(self.handle, key, 0, REG_SZ, Some(path))? };
Ok(())
}
}
impl Drop for AutoStartRegKey {
fn drop(&mut self) {
unsafe {
RegCloseKey(self.handle).unwrap_or_else(|e| warn!("Failed to close registry key: {e}"));
}
}
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/theme.rs | src/theme.rs | use std::mem::size_of;
use windows::core::{w, PCWSTR};
use windows::Win32::System::Registry::{RegCloseKey, RegOpenKeyExW, RegQueryValueExW, HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WOW64_64KEY};
use windows::UI::Color;
use windows::UI::ViewManagement::{UIColorType, UISettings};
use windows_ext::UI::Xaml::ElementTheme;
use crate::Result;
pub struct ColorSet {
pub tint: Color,
pub fallback: Color,
pub opacity: f64,
pub theme: ElementTheme
}
impl ColorSet {
pub fn dark() -> Self {
Self {
tint: Color { R: 0, G: 0, B: 0, A: 255 },
fallback: Color { R: 0, G: 0, B: 0, A: 255 },
opacity: 0.6,
theme: ElementTheme::Dark
}
}
pub fn light() -> Self {
Self {
tint: Color {
R: 255,
G: 255,
B: 255,
A: 255
},
fallback: Color {
R: 255,
G: 255,
B: 255,
A: 255
},
opacity: 0.7,
theme: ElementTheme::Light
}
}
pub fn accent(color: Color) -> Self {
Self {
tint: color,
fallback: color,
opacity: 0.7,
theme: ElementTheme::Dark
}
}
pub fn system(system_settings: &SystemSettings, ui_settings: &UISettings) -> Self {
system_settings
.is_accent_enabled()
.map_err(|err| log::warn!("Could not detect accent state: {err}"))
.ok()
.and_then(|enabled| {
enabled
.then_some(UIColorType::AccentDark1)
.and_then(|c| {
ui_settings
.GetColorValue(c)
.map_err(|err| log::warn!("Failed to query accent color: {err}"))
.ok()
})
.map(Self::accent)
})
.or_else(|| {
system_settings
.is_system_theme_light()
.map_err(|err| log::warn!("Could not detect system theme state: {err}"))
.ok()
.and_then(|enabled| enabled.then_some(Self::light()))
})
.unwrap_or(Self::dark())
}
}
/*
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Theme {
Light,
Dark,
Accent
}
impl Theme {
pub fn system() -> Self {
get_theme_setting(w!("ColorPrevalence"))
.then_some(Self::Accent)
.or_else(|| get_theme_setting(w!("SystemUsesLightTheme"))
.then_some(Self::Light))
.unwrap_or(Self::Dark)
}
pub fn opacity(self) -> f32 {
match self {
Theme::Light => 0.8,
Theme::Dark => 0.7,
Theme::Accent => 0.8
}
}
fn color_name(self) -> PCWSTR {
match self {
Theme::Light => w!("ImmersiveLightChromeMedium"),
Theme::Dark => w!("ImmersiveDarkChromeMedium"),
Theme::Accent => w!("ImmersiveSystemAccentDark1")
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct ThemeColor {
r: u8,
g: u8,
b: u8,
opacity: f32
}
impl ThemeColor {
pub fn tint_color(self) -> Color {
Color { R: self.r, G: self.g, B: self.b, A: 255 }
}
pub fn opacity(self) -> f64 {
self.opacity as f64
}
pub fn fallback_color(self) -> Color {
//let d = self.is_light()
// .then_some(255)
// .unwrap_or(0);
//Color {
// R: lerp(d, self.r, self.opacity),
// G: lerp(d, self.g, self.opacity),
// B: lerp(d, self.b, self.opacity),
// A: 255,
//}
Color { R: self.r, G: self.g, B: self.b, A: 255 }
}
pub fn is_light(self) -> bool {
false
}
}
impl From<Theme> for ThemeColor {
fn from(value: Theme) -> Self {
let color = unsafe {
let color_set = GetImmersiveUserColorSetPreference(false, false);
let color_type = GetImmersiveColorTypeFromName(value.color_name());
GetImmersiveColorFromColorSetEx(color_set, color_type, false, 0)
.to_ne_bytes()
};
Self {
r: color[0],
g: color[1],
b: color[2],
opacity: value.opacity(),
}
}
}
#[link(name = "uxtheme", kind = "raw-dylib")]
extern "system" {
#[link_ordinal(94)]
fn GetImmersiveColorSetCount() -> u32;
#[link_ordinal(95)]
fn GetImmersiveColorFromColorSetEx(dwImmersiveColorSet: u32, dwImmersiveColorType: u32, bIgnoreHighContrast: bool, dwHighContrastCacheMode: u32) -> u32;
#[link_ordinal(96)]
fn GetImmersiveColorTypeFromName(name: PCWSTR) -> u32;
#[link_ordinal(98)]
fn GetImmersiveUserColorSetPreference(bForceCheckRegistry: bool, bSkipCheckOnFail: bool) -> u32;
#[link_ordinal(100)]
fn GetImmersiveColorNamedTypeByIndex(dwImmersiveColorType: u32) -> *const PCWSTR;
}
*/
pub struct SystemSettings {
key: HKEY
}
impl SystemSettings {
pub fn new() -> crate::Result<Self> {
let mut key = HKEY::default();
unsafe {
RegOpenKeyExW(
HKEY_CURRENT_USER,
w!(r#"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"#),
0,
KEY_READ | KEY_WOW64_64KEY,
&mut key
)
}?;
Ok(Self { key })
}
/*
pub fn add_change_callback<F>(self: &Arc<Self>, callback: F) -> Result<SystemSettingsChangedCallback>
where F : FnMut(&SystemSettings) + Send + 'static
{
SystemSettingsChangedCallbackInner::new(self.clone(), Box::new(callback))
.map(SystemSettingsChangedCallback)
}
*/
unsafe fn query_value(&self, name: PCWSTR) -> Result<bool> {
let mut data: u32 = 0;
unsafe {
RegQueryValueExW(
self.key,
name,
None,
None,
Some(&mut data as *const _ as _),
Some(&mut (size_of::<u32>() as u32))
)?;
}
Ok(data > 0)
}
pub fn is_accent_enabled(&self) -> Result<bool> {
unsafe { self.query_value(w!("ColorPrevalence")) }
}
pub fn is_system_theme_light(&self) -> Result<bool> {
unsafe { self.query_value(w!("SystemUsesLightTheme")) }
}
}
impl Drop for SystemSettings {
fn drop(&mut self) {
unsafe {
RegCloseKey(self.key).unwrap_or_else(|err| log::warn!("Failed to close registry key: {err}"));
}
}
}
/*
pub struct SystemSettingsChangedCallback(Arc<SystemSettingsChangedCallbackInner>);
impl SystemSettingsChangedCallback {
pub fn detach(self) {
std::mem::forget(self)
}
}
struct SystemSettingsChangedCallbackInner {
settings: Arc<SystemSettings>,
callback: Mutex<Box<dyn FnMut(&SystemSettings) + Send>>,
event: HANDLE,
waiter: PTP_WAIT
}
impl SystemSettingsChangedCallbackInner {
fn new(settings: Arc<SystemSettings>, callback: Box<dyn FnMut(&SystemSettings) + Send>) -> Result<Arc<Self>> {
let r = Arc::try_new_cyclic::<_, TracedError>(move |weak| {
let event = unsafe { CreateEventW(None, true, false, None)? };
let waiter = unsafe { CreateThreadpoolWait(Some(Self::callback_func), Some(weak.clone().into_raw() as _), None)? };
Ok(Self {
settings,
callback: Mutex::new(callback),
event,
waiter,
})
})?;
r.register()?;
Ok(r)
}
fn register(&self) -> Result<()> {
unsafe {
ResetEvent(self.event)?;
RegNotifyChangeKeyValue(
self.settings.key,
false,
REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC,
self.event,
true
)?;
SetThreadpoolWait(self.waiter, self.event, None);
}
Ok(())
}
unsafe extern "system" fn callback_func(_: PTP_CALLBACK_INSTANCE, context: *mut c_void, _: PTP_WAIT, _: u32) {
let context = ManuallyDrop::new(Weak::<Self>::from_raw(context as _));
match context.upgrade() {
Some(context) => {
(context.callback.lock_no_poison())(&context.settings);
context.register()
.unwrap_or_else(|err| log::warn!("Failed to reregister callback: {err}"));
}
None => log::error!("Weak ptr is gone :(")
}
}
}
impl Drop for SystemSettingsChangedCallbackInner {
fn drop(&mut self) {
unsafe {
CloseThreadpoolWait(self.waiter);
CloseHandle(self.event)
.unwrap_or_else(|err| log::warn!("Failed to destroy event: {err}"));
}
}
}
pub fn get_theme_setting(name: PCWSTR) -> bool {
unsafe {
let mut data: u32 = 0;
RegGetValueW(
HKEY_CURRENT_USER,
w!(r#"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"#),
name,
RRF_RT_REG_DWORD | RRF_SUBKEY_WOW6464KEY,
None,
Some(&mut data as *const _ as _),
Some(&mut (size_of::<u32>() as u32))
).unwrap();
data > 0
}
}
fn lerp(a: u8, b: u8, v: f32) -> u8 {
((a as f32) * (1.0 - v) + (b as f32) * v) as u8
}
*/
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/backend.rs | src/backend.rs | use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Display;
use std::mem::take;
use std::sync::{Arc, Mutex};
use std::thread::{spawn, JoinHandle};
use std::time::{Duration, Instant};
use futures_lite::future::yield_now;
use futures_lite::FutureExt;
use log::{debug, trace, warn};
use loole::{unbounded, Receiver, Sender};
use crate::config::Config;
use crate::monitors::{Monitor, MonitorConnection, MonitorPath};
use crate::runtime::reducing_spsc::{Reducible, ReducingReceiver, ReducingSender, TryRecvError};
use crate::runtime::{block_on, reducing_spsc, LocalExecutor, Timer};
use crate::utils::extensions::{ChannelExt, MutexExt};
use crate::CustomEvent;
#[derive(Debug, Clone)]
enum BackendCommand {
Stop,
RefreshMonitors,
QueryBrightness(Option<Duration>),
SetBrightness(MonitorPath, u32)
}
pub struct MonitorController {
sender: Sender<BackendCommand>,
thread: Option<JoinHandle<()>>
}
impl MonitorController {
pub fn new(main_sender: Sender<CustomEvent>, config: Arc<Mutex<Config>>) -> Self {
let (sender, receiver) = unbounded();
sender.send_ignore(BackendCommand::RefreshMonitors);
let thread = Some(spawn(move || block_on(Self::worker_task(main_sender, receiver, config))));
Self { sender, thread }
}
async fn worker_task(sender: Sender<CustomEvent>, receiver: Receiver<BackendCommand>, config: Arc<Mutex<Config>>) {
let executor = LocalExecutor::default();
let mut monitor_map: BTreeMap<MonitorPath, ReducingSender<MonitorCommand>> = BTreeMap::new();
let mut delayed_query: Option<Instant> = None;
executor
.run(async {
loop {
let query_event = async {
delayed_query
.map(Timer::at)
.unwrap_or_else(Timer::never)
.await;
BackendCommand::QueryBrightness(None)
};
let command_event = async { receiver.recv_async().await.expect("Controller disappeared") };
match query_event.or(command_event).await {
BackendCommand::QueryBrightness(None) => {
delayed_query.take();
let config = config.lock_no_poison();
monitor_map.iter().for_each(|(p, s)| {
s.send_ignore(MonitorCommand::QueryBrightness {
target: config
.restore_from_config
.then(|| config.monitors.get(p))
.flatten()
.and_then(|s| s.saved_brightness)
})
});
}
BackendCommand::RefreshMonitors => {
trace!("Refreshing monitor list");
let mut current_monitors = Monitor::find_all()
.map_err(|err| log::warn!("Failed to enumerate monitors: {err}"))
.unwrap_or_default();
debug!("Skipping over unnamed monitors as they are likely integrated displays");
current_monitors.retain(|m| !m.name().is_empty());
let old_monitors = take(&mut monitor_map).into_keys().collect::<BTreeSet<_>>();
// Yield to allow the monitor tasks to finish
yield_now().await;
executor.clean_pending_tasks();
for path in &old_monitors {
if current_monitors.iter().all(|m| m.path() != path) {
sender.send_ignore(CustomEvent::MonitorRemoved { path: path.clone() });
}
}
for monitor in current_monitors {
let path = monitor.path().clone();
if !old_monitors.contains(&path) {
sender.send_ignore(CustomEvent::MonitorAdded {
path: path.clone(),
name: monitor.name().to_string()
});
}
let (tx, rx) = reducing_spsc::channel();
executor.spawn(monitor_task(monitor, sender.clone(), rx));
monitor_map.insert(path, tx);
}
delayed_query = Some(Instant::now());
}
BackendCommand::QueryBrightness(Some(delay)) => {
delayed_query = delayed_query
.into_iter()
.chain([Instant::now() + delay])
.min();
}
BackendCommand::SetBrightness(p, v) => {
monitor_map
.get(&p)
.map(|s| s.send_ignore(MonitorCommand::SetBrightness { value: v, notify: false }))
.unwrap_or_else(|| warn!("Unknown monitor {:?}", p));
let mut config = config.lock_no_poison();
if config.restore_from_config {
config.monitors.entry(p).or_default().saved_brightness = Some(v);
config.dirty = true;
}
}
BackendCommand::Stop => break
}
}
})
.await;
}
pub fn refresh_brightness(&self) {
self.send_command(BackendCommand::QueryBrightness(None));
}
pub fn shutdown(&self) {
self.send_command(BackendCommand::Stop);
}
fn send_command(&self, command: BackendCommand) {
self.sender.send_ignore(command)
}
pub fn create_proxy(&self) -> MonitorControllerProxy {
MonitorControllerProxy(self.sender.clone())
}
}
impl Drop for MonitorController {
fn drop(&mut self) {
let _ = self.sender.send(BackendCommand::Stop);
if let Some(handle) = self.thread.take() {
debug!("Waiting for worker thread to shutdown!");
handle.join().expect("worker thread panic");
}
}
}
#[derive(Debug, Copy, Clone)]
enum MonitorCommand {
QueryBrightness { target: Option<u32> },
SetBrightness { value: u32, notify: bool }
}
impl Reducible for MonitorCommand {
fn reduce(self, other: Self) -> Self {
use MonitorCommand::*;
match (self, other) {
(QueryBrightness { target: current }, QueryBrightness { target: next }) => QueryBrightness { target: next.or(current) },
(QueryBrightness { .. }, SetBrightness { value, .. }) => QueryBrightness { target: Some(value) },
(SetBrightness { value, .. }, QueryBrightness { target }) => QueryBrightness {
target: Some(target.unwrap_or(value))
},
(SetBrightness { .. }, SetBrightness { value, notify }) => SetBrightness { value, notify }
}
}
}
async fn monitor_task(monitor: Monitor, sender: Sender<CustomEvent>, mut control: ReducingReceiver<MonitorCommand>) {
let mut current_brightness = None;
let mut cached_connection: Option<MonitorConnection> = None;
let mut next_command = None;
let mut dirty = false;
loop {
match next_command.take().ok_or(()).or(control.try_recv()) {
Err(TryRecvError::Closed) => break,
Err(TryRecvError::Empty) => {
if dirty {
debug!("Attempting to write save new settings for {}", monitor.name());
if let Some(connection) = &cached_connection {
retry(|| connection.save_settings())
.await
.unwrap_or_else(|err| warn!("Failed to save new settings for {}: {}", monitor.name(), err));
}
dirty = false;
}
trace!("Closing connection to {} and going to sleep", monitor.name());
cached_connection = None;
next_command = control.recv().await;
}
Ok(MonitorCommand::SetBrightness { value, .. }) if Some(value) == current_brightness => {
trace!("Brightness already at requested level {}", value);
}
Ok(command) => {
if cached_connection.is_none() {
trace!("Opening connection to {}", monitor.name());
cached_connection = retry(|| monitor.open())
.await
.map_err(|err| warn!("Failed to connect to monitor: {err}"))
.ok();
}
let connection = match cached_connection.as_ref() {
Some(conn) => conn,
None => continue
};
match command {
MonitorCommand::QueryBrightness { target } => {
trace!("Attempting to read brightness of {}", monitor.name());
match retry(|| connection.get_brightness()).await {
Ok((brightness, range)) => {
if range != (0..=100) {
warn!("unexpected brightness range: {:?}", range);
}
current_brightness = Some(brightness);
match target {
Some(target) if target != brightness => {
log::info!(
"Restoring saved brightness for {} (current: {}, saved: {})",
monitor.name(),
brightness,
target
);
next_command = Some(MonitorCommand::SetBrightness { value: target, notify: true });
}
_ => {
sender.send_ignore(CustomEvent::BrightnessChanged {
path: monitor.path().clone(),
value: brightness
});
}
}
}
Err(err) => warn!("Failed to query brightness: {err}")
}
}
MonitorCommand::SetBrightness { value, notify } => {
trace!("Attempting to set brightness of {}", monitor.name());
let success = retry(|| connection.set_brightness(value))
.await
.map_err(|err| warn!("Failed to set brightness: {err}"))
.is_ok();
if success {
current_brightness = Some(value);
dirty = true;
}
if notify {
if let Some(current) = current_brightness {
sender.send_ignore(CustomEvent::BrightnessChanged {
path: monitor.path().clone(),
value: current
});
}
}
}
}
Timer::after(Duration::from_millis(250)).await;
}
}
}
trace!("Monitor task for {} is shutting down", monitor.name());
}
async fn retry<R, E: Display, F: FnMut() -> std::result::Result<R, E>>(mut op: F) -> std::result::Result<R, E> {
let mut tries = 0;
let mut backoff_ms = 100;
loop {
match op() {
Ok(result) => return Ok(result),
Err(err) if tries <= 4 => {
debug!("Retrying in {}: {}", backoff_ms, err);
Timer::after(Duration::from_millis(backoff_ms)).await;
tries += 1;
backoff_ms *= 2;
}
Err(err) => return Err(err)
}
}
}
pub struct MonitorControllerProxy(Sender<BackendCommand>);
impl MonitorControllerProxy {
pub fn set_brightness(&self, monitor: MonitorPath, value: u32) {
self.send_command(BackendCommand::SetBrightness(monitor, value));
}
pub fn refresh_brightness_in(&self, delay: Duration) {
self.send_command(BackendCommand::QueryBrightness(Some(delay)));
}
pub fn refresh_monitors(&self) {
self.send_command(BackendCommand::RefreshMonitors);
}
fn send_command(&self, command: BackendCommand) {
self.0.send_ignore(command);
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/mousehook.rs | src/mousehook.rs | use std::cell::Cell;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use log::{warn};
use windows::core::{GUID};
use windows::Win32::Foundation::{BOOL, FALSE, HINSTANCE, HWND, LPARAM, LRESULT, RECT, TRUE, WPARAM};
use windows::Win32::System::SystemInformation::GetTickCount64;
use windows::Win32::UI::Shell::{Shell_NotifyIconGetRect, NOTIFYICONIDENTIFIER};
use windows::Win32::UI::WindowsAndMessaging::{CallNextHookEx, EnumWindows, GetClassNameA, SetWindowsHookExW, UnhookWindowsHookEx, HC_ACTION, HHOOK, MSLLHOOKSTRUCT, WHEEL_DELTA, WH_MOUSE_LL, WM_MOUSEWHEEL};
use crate::Result;
struct CallbackContext {
tray_id: NOTIFYICONIDENTIFIER,
tray_rect: RECT,
last_rect_query: u64,
callback: Box<dyn FnMut(f32)>
}
impl CallbackContext {
fn new<F: FnMut(f32)+ 'static>(id: NOTIFYICONIDENTIFIER, callback: F) -> Self {
Self {
tray_id: id,
tray_rect: Default::default(),
last_rect_query: 0,
callback: Box::new(callback),
}
}
fn cached_tray_rect(&mut self) -> RECT {
let current_time = unsafe { GetTickCount64() };
if current_time.saturating_sub(self.last_rect_query) > 1000 {
self.tray_rect = unsafe { Shell_NotifyIconGetRect(&self.tray_id) }
//.inspect(|rect| trace!("Found tray rect: {:?}", rect))
.map_err(|err| warn!("Failed to query tray rect: {}", err))
.unwrap_or(self.tray_rect);
self.last_rect_query = current_time;
}
self.tray_rect
}
}
thread_local! { static CONTEXT: Cell<Option<CallbackContext>> = Cell::new(None) }
pub struct TrayIconScrollCallback {
hook: HHOOK,
_unsent: PhantomData<*mut ()>
}
impl Debug for TrayIconScrollCallback {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TrayIconScrollCallback").finish_non_exhaustive()
}
}
impl Drop for TrayIconScrollCallback {
fn drop(&mut self) {
CONTEXT.set(None);
unsafe {
UnhookWindowsHookEx(self.hook)
.unwrap_or_else(|err| warn!("Failed to remove mouse hook: {err}"));
}
}
}
impl TrayIconScrollCallback {
pub fn new<F: FnMut(f32) + 'static>(callback: F) -> Result<Self> {
let id = find_tray_icon_identifier()?;
CONTEXT.set(Some(CallbackContext::new(id, callback)));
let hook = unsafe { SetWindowsHookExW(WH_MOUSE_LL, Some(low_level_mouse_proc), HINSTANCE::default(), 0)? };
Ok(Self {
hook,
_unsent: PhantomData,
})
}
}
unsafe extern "system" fn low_level_mouse_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
let event_data = (lparam.0 as *const MSLLHOOKSTRUCT).read();
if code == HC_ACTION as i32 {
match wparam.0 as u32 {
WM_MOUSEWHEEL => if let Some(mut context) = CONTEXT.take() {
if in_rect(context.cached_tray_rect(), event_data.pt.x, event_data.pt.y) {
(context.callback)(parse_wheel_delta(&event_data));
}
CONTEXT.set(Some(context));
}
_ => {}
}
}
CallNextHookEx(HHOOK::default(), code, wparam, lparam)
}
fn in_rect(rect: RECT, x: i32, y: i32) -> bool {
x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom
}
fn parse_wheel_delta(event_data: &MSLLHOOKSTRUCT) -> f32 {
(event_data.mouseData >> 16) as i16 as f32 / WHEEL_DELTA as f32
}
// betrayer doesn't yet export a way to get the platform-specific primitives
// To work around this we manually find its hidden window
fn find_tray_icon_identifier() -> Result<NOTIFYICONIDENTIFIER> {
unsafe extern "system" fn enum_window_proc(hwnd: HWND, lparam: LPARAM) -> BOOL {
const TARGET_CLASS: &[u8] = b"tray_icon_window";
let mut buf = [0u8; 32];
let len = GetClassNameA(hwnd, &mut buf) as usize;
if len != 0 && &buf[..len] == TARGET_CLASS {
let param = lparam.0 as *mut Option<HWND>;
param.write(Some(hwnd));
FALSE
} else {
TRUE
}
}
let mut target_window: Option<HWND> = None;
unsafe { let _ = EnumWindows(Some(enum_window_proc), LPARAM(&mut target_window as *mut _ as _)); }
Ok(NOTIFYICONIDENTIFIER {
cbSize: size_of::<NOTIFYICONIDENTIFIER>() as u32,
hWnd: target_window.ok_or("Failed to find tray icon parent window")?,
uID: 1, //betrayer numbers tray icons in ascending order
guidItem: GUID::zeroed(),
})
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/monitors.rs | src/monitors.rs | use std::fmt::{Debug, Formatter};
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use windows::Win32::Devices::Display::*;
use windows::Win32::Foundation::{BOOL, HANDLE};
use windows::Win32::Graphics::Gdi::HMONITOR;
use crate::monitors::gdi::find_all_gdi_monitors;
use crate::monitors::paths::{find_all_paths, get_gdi_name, get_name_and_path};
use crate::utils::error::{Result, WinOptionExt};
use crate::utils::string::WStr;
use crate::win_assert;
#[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct MonitorPath(Arc<Path>);
impl MonitorPath {
pub fn as_str(&self) -> &str {
self.0.to_str().expect("MonitorPath is not valid UTF-8")
}
}
impl Debug for MonitorPath {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.0, f)
}
}
impl<const N: usize> From<WStr<N>> for MonitorPath {
fn from(value: WStr<N>) -> Self {
Self(Arc::from(PathBuf::from(value)))
}
}
impl From<&str> for MonitorPath {
fn from(value: &str) -> Self {
Self(Arc::from(PathBuf::from(value)))
}
}
#[derive(Debug, Clone)]
pub struct Monitor {
name: String,
path: MonitorPath,
hmonitor: HMONITOR
}
impl Monitor {
pub fn find_all() -> Result<Vec<Monitor>> {
let monitors = find_all_gdi_monitors()?;
find_all_paths()?
.into_iter()
.map(|display| {
let (name, path) = get_name_and_path(&display)?;
let gdi = get_gdi_name(&display)?;
let hmonitor = monitors.iter().find(|(n, _)| n == &gdi).some()?.1;
Ok(Monitor { name, path, hmonitor })
})
.collect()
}
pub fn name(&self) -> &str {
&self.name
}
pub fn path(&self) -> &MonitorPath {
&self.path
}
pub fn open(&self) -> Result<MonitorConnection> {
MonitorConnection::open(self.hmonitor)
}
}
pub struct MonitorConnection {
handle: HANDLE
}
impl MonitorConnection {
fn open(monitor: HMONITOR) -> Result<Self> {
win_assert!({
let mut n = 0;
unsafe {
GetNumberOfPhysicalMonitorsFromHMONITOR(monitor, &mut n)?;
};
n == 1
});
let mut physical_monitor = PHYSICAL_MONITOR::default();
unsafe { GetPhysicalMonitorsFromHMONITOR(monitor, std::slice::from_mut(&mut physical_monitor))? };
Ok(Self {
handle: physical_monitor.hPhysicalMonitor
})
}
/*
Seems to be broken
pub fn get_capabilities(&self) -> Result<MonitorCapabilities> {
let mut caps = 0;
let mut temps = 0;
dbg!(unsafe { GetMonitorCapabilities(self.handle, &mut caps, &mut temps)});
dbg!(unsafe { GetLastError()});
Ok(MonitorCapabilities::from_bits_truncate(dbg!(caps)))
}
*/
pub fn get_brightness(&self) -> Result<(u32, RangeInclusive<u32>)> {
let mut min = 0;
let mut cur = 0;
let mut max = 0;
unsafe { BOOL(GetMonitorBrightness(self.handle, &mut min, &mut cur, &mut max)).ok()? };
Ok((cur, min..=max))
}
pub fn set_brightness(&self, new: u32) -> Result<()> {
unsafe { BOOL(SetMonitorBrightness(self.handle, new)).ok()? };
Ok(())
}
pub fn save_settings(&self) -> Result<()> {
unsafe { BOOL(SaveCurrentMonitorSettings(self.handle)).ok()? };
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::error::Result;
#[test]
fn caps() -> Result<()> {
for monitor in Monitor::find_all()? {
println!("{}", monitor.name());
let conn = monitor.open()?;
let (current, range) = conn.get_brightness()?;
println!("\tbrightness: {} / {}-{}", current, range.start(), range.end());
conn.set_brightness(*range.start())?;
//println!("\tcaps: {:?}", conn.get_capabilities()?);
}
Ok(())
}
}
impl Drop for MonitorConnection {
fn drop(&mut self) {
unsafe { DestroyPhysicalMonitor(self.handle).unwrap_or_else(|err| log::warn!("Failed to release physical monitor: {err}")) }
}
}
/*
bitflags! {
#[derive(Debug, Copy, Clone)]
pub struct MonitorCapabilities: u32 {
const BRIGHTNESS = MC_CAPS_BRIGHTNESS;
const COLOR_TEMPERATURE = MC_CAPS_COLOR_TEMPERATURE;
const CONTRAST = MC_CAPS_CONTRAST;
const DEGAUSS = MC_CAPS_DEGAUSS;
const DISPLAY_AREA_POSITION = MC_CAPS_DISPLAY_AREA_POSITION;
const DISPLAY_AREA_SIZE = MC_CAPS_DISPLAY_AREA_SIZE;
const MONITOR_TECHNOLOGY_TYPE = MC_CAPS_MONITOR_TECHNOLOGY_TYPE;
const RED_GREEN_BLUE_DRIVE = MC_CAPS_RED_GREEN_BLUE_DRIVE;
const RED_GREEN_BLUE_GAIN = MC_CAPS_RED_GREEN_BLUE_GAIN;
const RESTORE_FACTORY_COLOR_DEFAULTS = MC_CAPS_RESTORE_FACTORY_COLOR_DEFAULTS;
const RESTORE_FACTORY_DEFAULTS = MC_CAPS_RESTORE_FACTORY_DEFAULTS;
const RESTORE_FACTORY_DEFAULTS_ENABLES_MONITOR_SETTINGS = MC_RESTORE_FACTORY_DEFAULTS_ENABLES_MONITOR_SETTINGS;
}
}
*/
type GdiName = WStr<32>;
mod paths {
use std::mem::size_of;
use windows::Win32::Devices::Display::{
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER, DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO,
DISPLAYCONFIG_SOURCE_DEVICE_NAME, DISPLAYCONFIG_TARGET_DEVICE_NAME, QDC_ONLY_ACTIVE_PATHS
};
use windows::Win32::Foundation::WIN32_ERROR;
use super::{GdiName, MonitorPath, WStr};
use crate::utils::error::Result;
pub fn find_all_paths() -> Result<Vec<DISPLAYCONFIG_PATH_INFO>> {
unsafe {
let mut path_count = 0;
let mut mode_count = 0;
GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)?;
let mut paths = vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
let mut modes = vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
QueryDisplayConfig(
QDC_ONLY_ACTIVE_PATHS,
&mut path_count,
paths.as_mut_ptr(),
&mut mode_count,
modes.as_mut_ptr(),
None
)?;
Ok(paths)
}
}
pub(super) fn get_gdi_name(path: &DISPLAYCONFIG_PATH_INFO) -> Result<GdiName> {
let mut source_name = DISPLAYCONFIG_SOURCE_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME,
size: size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32,
adapterId: path.sourceInfo.adapterId,
id: path.sourceInfo.id
},
..Default::default()
};
unsafe { WIN32_ERROR(DisplayConfigGetDeviceInfo(&mut source_name.header) as u32).ok()? };
Ok(source_name.viewGdiDeviceName.into())
}
pub(super) fn get_name_and_path(path: &DISPLAYCONFIG_PATH_INFO) -> Result<(String, MonitorPath)> {
let mut target_name = DISPLAYCONFIG_TARGET_DEVICE_NAME {
header: DISPLAYCONFIG_DEVICE_INFO_HEADER {
r#type: DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME,
size: size_of::<DISPLAYCONFIG_TARGET_DEVICE_NAME>() as u32,
adapterId: path.targetInfo.adapterId,
id: path.targetInfo.id
},
..Default::default()
};
unsafe { WIN32_ERROR(DisplayConfigGetDeviceInfo(&mut target_name.header) as u32).ok()? };
let path = WStr::from(target_name.monitorDevicePath).into();
let name = WStr::from(target_name.monitorFriendlyDeviceName).to_string_lossy();
Ok((name, path))
}
}
mod gdi {
use std::mem::size_of;
use windows::Win32::Foundation::{BOOL, LPARAM, RECT, TRUE};
use windows::Win32::Graphics::Gdi::{EnumDisplayMonitors, GetMonitorInfoW, HDC, HMONITOR, MONITORINFO, MONITORINFOEXW};
use super::GdiName;
use crate::utils::error::Result;
fn find_all_hmonitors() -> Result<Vec<HMONITOR>> {
unsafe {
let result = Box::into_raw(Box::default());
unsafe extern "system" fn enum_func(hm: HMONITOR, _: HDC, _: *mut RECT, result: LPARAM) -> BOOL {
let result = &mut *(result.0 as *mut Vec<HMONITOR>);
result.push(hm);
TRUE
}
EnumDisplayMonitors(None, None, Some(enum_func), LPARAM(result as _)).ok()?;
Ok(*Box::from_raw(result))
}
}
fn get_gdi_name(hm: HMONITOR) -> Result<GdiName> {
let mut mi = MONITORINFOEXW {
monitorInfo: MONITORINFO {
cbSize: size_of::<MONITORINFOEXW>() as u32,
..Default::default()
},
..Default::default()
};
unsafe { GetMonitorInfoW(hm, &mut mi as *mut _ as _).ok()? };
Ok(mi.szDevice.into())
}
pub(super) fn find_all_gdi_monitors() -> Result<Vec<(GdiName, HMONITOR)>> {
find_all_hmonitors()?
.into_iter()
.map(|hm| get_gdi_name(hm).map(|name| (name, hm)))
.collect()
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/main.rs | src/main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod backend;
mod config;
mod monitors;
pub mod runtime;
mod theme;
mod ui;
mod utils;
mod views;
mod watchers;
mod windowing;
mod mousehook;
use std::pin::Pin;
use std::process::ExitCode;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use betrayer::{ClickType, Icon, Menu, MenuItem, TrayEvent, TrayIconBuilder};
use futures_lite::{FutureExt, Stream, StreamExt};
use futures_lite::stream::pending;
use log::{debug, error, info, trace, warn, LevelFilter};
use windows::Foundation::TypedEventHandler;
use windows::Win32::Foundation::RECT;
use windows::Win32::System::WinRT::{RoInitialize, RoUninitialize, RO_INIT_SINGLETHREADED};
use windows::UI::ViewManagement::UISettings;
use windows_ext::UI::Xaml::ElementTheme;
use windows_ext::UI::Xaml::Hosting::WindowsXamlManager;
use crate::backend::MonitorController;
use crate::config::{autostart, Config};
use crate::monitors::MonitorPath;
use crate::runtime::{FutureStream, Timer};
use crate::theme::{ColorSet, SystemSettings};
pub use crate::utils::error::Result;
use crate::utils::extensions::{ChannelExt, MutexExt};
use crate::utils::{logger, panic};
use crate::views::{BrightnessFlyout, ProxyWindow, SettingsWindow};
use crate::watchers::{EventWatcher, PowerEvent};
use windowing::hotkey::HotKey;
use crate::mousehook::{TrayIconScrollCallback};
use crate::windowing::{event_loop, get_primary_work_area, poll_for_click_outside_of_rect};
include!("../assets/ids.rs");
#[derive(Debug, Clone)]
pub enum CustomEvent {
Quit,
Show,
FocusLost,
ThemeChange,
ClickedOutside,
Refresh,
OpenSettings,
CloseSettings,
MonitorAdded { path: MonitorPath, name: String },
MonitorRemoved { path: MonitorPath },
BrightnessChanged { path: MonitorPath, value: u32 },
ChangeGeneralBrightness(f32),
ReinitializeControls
}
fn run() -> Result<()> {
// For changing the autostart setting with an elevated instance
if let Some(arg) = std::env::args()
.skip_while(|arg| arg != "--config-autostart")
.nth(1)
{
match arg.as_str() {
"enable" => autostart::set_enabled(false, true)?,
"disable" => autostart::set_enabled(false, false)?,
_ => panic!("Invalid argument: {}", arg)
}
return Ok(());
}
let settings_mode = std::env::args().any(|arg| arg == "--settings-mode");
unsafe { RoInitialize(RO_INIT_SINGLETHREADED)? };
let _xaml_manager = WindowsXamlManager::InitializeForCurrentThread()?;
let config = Arc::new(Mutex::new(Config::restore()?));
let (wnd_sender, wnd_receiver) = loole::unbounded();
let mut controller = MonitorController::new(wnd_sender.clone(), config.clone());
let ui_settings = UISettings::new()?;
let mut colors = SystemSettings::new()
.map_err(|err| warn!("Failed to read system settings: {err}"))
.ok()
.map_or_else(ColorSet::dark, |system_settings| ColorSet::system(&system_settings, &ui_settings));
let tray = TrayIconBuilder::new()
.with_tooltip("Change Brightness")
.with_icon(Icon::from_resource(
if colors.theme == ElementTheme::Light {
BRIGHTNESS_LIGHT_ICON
} else {
BRIGHTNESS_DARK_ICON
},
None
)?)
.with_menu(Menu::new([MenuItem::button("Quit", CustomEvent::Quit)]))
.build(cloned!([wnd_sender] move |event| wnd_sender.filter_send_ignore(match event {
TrayEvent::Tray(ClickType::Left) => Some(CustomEvent::Show),
TrayEvent::Menu(e) => Some(e),
_ => None
})))?;
let _event_watcher = EventWatcher::new()?
.on_power_event({
let proxy = controller.create_proxy();
move |event| match event {
PowerEvent::MonitorOn => proxy.refresh_brightness_in(Duration::from_secs(10)),
PowerEvent::Resume => proxy.refresh_monitors(),
_ => {}
}
})?
.on_display_change({
let proxy = controller.create_proxy();
move || proxy.refresh_monitors()
})?;
ui_settings.ColorValuesChanged(&TypedEventHandler::new(cloned!([wnd_sender] move |_: &Option<UISettings>, _| {
wnd_sender.send_ignore(CustomEvent::ThemeChange);
Ok(())
})))?;
let proxy_window = ProxyWindow::new()?;
let mut flyout = BrightnessFlyout::new(wnd_sender.clone(), &colors)?;
let mut settings_window: Option<SettingsWindow> = None;
if settings_mode {
wnd_sender.send_ignore(CustomEvent::OpenSettings);
}
wnd_sender.send_ignore(CustomEvent::ReinitializeControls);
let mut hotkey_dec: Pin<Box<dyn Stream<Item=CustomEvent>>> = Box::pin(pending()); //HotKey::register(([Modifier::Alt], VirtualKey::F1))?;
let mut hotkey_inc: Pin<Box<dyn Stream<Item=CustomEvent>>> = Box::pin(pending()); //HotKey::register(([Modifier::Alt], VirtualKey::F2))?;
let mut scroll_callback = None;
let mut last_close = Instant::now();
event_loop(async {
let mut click_watcher = FutureStream::new();
let mut events = wnd_receiver.into_stream();
while let Some(event) =
(&mut events)
.or(&mut click_watcher)
.or(&mut hotkey_dec)
.or(&mut hotkey_inc)
.next().await {
match event {
CustomEvent::Quit => {
controller.shutdown();
return Ok(());
}
CustomEvent::Show => {
if flyout.is_open() {
trace!("Flyout already open. Closing it instead");
flyout.close();
continue;
}
if last_close.elapsed() >= Duration::from_millis(250) {
let idpi = 1.0 / proxy_window.dpi();
let workspace = get_primary_work_area()?;
let gap = 13;
let right = workspace.right - gap;
let bottom = workspace.bottom - gap;
if !proxy_window.activate() {
// This happens when opening the flyout while the start menu is open
debug!("Failed to set window foreground");
let size = flyout.size();
click_watcher.set(async move {
trace!("Calculated flyout size: {:?}", size);
let click = async {
let rect = RECT {
left: right - (size.Width / idpi) as i32,
top: bottom - (size.Height / idpi) as i32,
right,
bottom
};
// We actively poll for clicks outside the flyout for simplicity
// and because low level mouse hooks don't work when the focused application is elevated
poll_for_click_outside_of_rect(Duration::from_millis(100), rect).await;
Some(CustomEvent::ClickedOutside)
};
let timeout = async {
// Don't waste energy if the flyout is left open
Timer::after(Duration::from_secs(30)).await;
trace!("Canceling click watcher");
None
};
click.or(timeout).await
});
}
flyout.show(&proxy_window, right as f32 * idpi, bottom as f32 * idpi);
controller.refresh_brightness();
}
}
CustomEvent::FocusLost => {
click_watcher.clear();
proxy_window.deactivate();
config.lock_no_poison().save_if_dirty()?;
last_close = Instant::now();
}
CustomEvent::ClickedOutside => {
flyout.close();
}
CustomEvent::ThemeChange => {
colors = SystemSettings::new()
.map_err(|err| log::warn!("Failed to read system settings: {err}"))
.ok()
.map_or_else(ColorSet::dark, |system_settings| ColorSet::system(&system_settings, &ui_settings));
flyout.update_theme(&colors)?;
tray.set_icon(Icon::from_resource(
if colors.theme == ElementTheme::Light {
BRIGHTNESS_LIGHT_ICON
} else {
BRIGHTNESS_DARK_ICON
},
None
)?);
if let Some(window) = settings_window.as_ref() {
window
.sync_theme()
.unwrap_or_else(|e| warn!("Failed to sync theme: {e}"));
}
}
CustomEvent::Refresh => {
info!("Restarting backend...");
flyout.clear_monitors()?;
controller = MonitorController::new(wnd_sender.clone(), config.clone());
}
CustomEvent::OpenSettings => {
info!("Open Settings");
if settings_window.is_none() {
trace!("Creating settings window");
settings_window = Some(SettingsWindow::new(wnd_sender.clone(), config.clone())?);
}
if let Some(window) = settings_window.as_ref() {
window.focus();
}
}
CustomEvent::CloseSettings => {
settings_window = None;
config.lock_no_poison().save_if_dirty()?;
if settings_mode {
return Ok(());
}
}
CustomEvent::MonitorAdded { path, name } => {
let mut lock = config.lock_no_poison();
let settings = lock.monitor(&path);
let display_name = settings.custom_name.clone().unwrap_or_else(|| name.clone());
let position = settings.position.unwrap_or(0);
info!("Found monitor: {} [{}]", name, display_name);
flyout.register_monitor(display_name, path, position, controller.create_proxy())?;
}
CustomEvent::MonitorRemoved { path } => {
info!("Monitor removed: {:?}", path);
flyout.unregister_monitor(&path)?;
}
CustomEvent::BrightnessChanged { path, value } => {
flyout.update_brightness(path, value)?;
}
CustomEvent::ChangeGeneralBrightness(value) => {
flyout.change_brightness(value.round() as i32)?;
}
CustomEvent::ReinitializeControls => {
let lock = config.lock_no_poison();
scroll_callback = None;
hotkey_inc = Box::pin(pending());
hotkey_dec = Box::pin(pending());
if lock.icon_scoll_enabled {
let factor = lock.icon_scroll_step_size;
let callback_result = TrayIconScrollCallback::new(cloned!([wnd_sender] move |delta| {
wnd_sender.send_ignore(CustomEvent::ChangeGeneralBrightness(factor * delta))
}));
match callback_result {
Ok(r) => scroll_callback = Some(r),
Err(err) => {
error!("{:?}", err);
panic::show_msg(format_args!("Failed to enable icon scroll:\n{}", err.message()));
}
}
}
if lock.hotkeys_enabled {
let factor = lock.hotkey_step_size;
match HotKey::register(lock.brightness_increase_hotkey) {
Ok(hk) => hotkey_inc = Box::pin(hk.map(move |_| CustomEvent::ChangeGeneralBrightness(factor))),
Err(err) => {
error!("{:?}", err);
panic::show_msg(format_args!("Failed to register hotkey {}:\n{}",
lock.brightness_increase_hotkey.display(true),
err.message()));
}
}
match HotKey::register(lock.brightness_decrease_hotkey) {
Ok(hk) => hotkey_dec = Box::pin(hk.map(move |_| CustomEvent::ChangeGeneralBrightness(-factor))),
Err(err) => {
error!("{:?}", err);
panic::show_msg(format_args!("Failed to register hotkey {}:\n{}",
lock.brightness_decrease_hotkey.display(true),
err.message()));
}
}
}
}
}
}
Ok(())
})?;
controller.shutdown();
config.lock_no_poison().save_if_dirty()?;
unsafe { RoUninitialize() }
Ok(())
}
fn main() -> ExitCode {
panic::set_hook();
let level = std::env::args()
.find(|arg| arg.starts_with("--log-level="))
.and_then(|arg| arg.split('=').nth(1).map(|level| level.parse().expect("Invalid log level")))
.unwrap_or(LevelFilter::Warn);
logger::init(LevelFilter::Trace, level);
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(err) => {
log::error!("{:?}", err);
panic::show_msg(format_args!("{}\n at {}", err.message(), err.trace()));
ExitCode::FAILURE
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/watchers/power.rs | src/watchers/power.rs | use log::trace;
use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::Power::{RegisterPowerSettingNotification, UnregisterPowerSettingNotification, HPOWERNOTIFY, POWERBROADCAST_SETTING};
use windows::Win32::System::SystemServices::GUID_SESSION_DISPLAY_STATUS;
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{
DEVICE_NOTIFY_WINDOW_HANDLE, PBT_APMRESUMEAUTOMATIC, PBT_APMRESUMESUSPEND, PBT_APMSUSPEND, PBT_POWERSETTINGCHANGE, WM_DESTROY, WM_POWERBROADCAST
};
use crate::Result;
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[allow(clippy::enum_variant_names)]
pub enum PowerEvent {
MonitorOff,
MonitorOn,
MonitorDim,
Resume
}
pub struct PowerEventRegistration(HPOWERNOTIFY);
impl PowerEventRegistration {
pub fn register<F: FnMut(PowerEvent)>(hwnd: HWND, callback: F) -> Result<Self> {
unsafe {
SetWindowSubclass(
hwnd,
Some(Self::wnd_proc::<F>),
super::POWER_SUBCLASS_ID,
Box::into_raw(Box::new((true, callback))) as _
)
.ok()?;
}
let registration = unsafe { RegisterPowerSettingNotification(HANDLE(hwnd.0), &GUID_SESSION_DISPLAY_STATUS, DEVICE_NOTIFY_WINDOW_HANDLE.0)? };
Ok(Self(registration))
}
unsafe extern "system" fn wnd_proc<F: FnMut(PowerEvent)>(
hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, _id: usize, subclass_input_ptr: usize
) -> LRESULT {
let callback_ptr = subclass_input_ptr as *mut (bool, F);
match msg {
WM_DESTROY => {
drop(Box::from_raw(callback_ptr));
}
WM_POWERBROADCAST => {
let (first, callback) = &mut *callback_ptr;
match wparam.0 as u32 {
PBT_APMRESUMEAUTOMATIC => callback(PowerEvent::Resume),
PBT_POWERSETTINGCHANGE => {
let data = &*(lparam.0 as *const POWERBROADCAST_SETTING);
match data.PowerSetting {
GUID_SESSION_DISPLAY_STATUS => {
let event = match data.Data[0] {
0 => Some(PowerEvent::MonitorOff),
1 => Some(PowerEvent::MonitorOn),
2 => Some(PowerEvent::MonitorDim),
_ => None
};
if let Some(event) = event {
if *first {
*first = false;
} else {
callback(event);
}
}
}
e => trace!("Unknown power setting: {e:?}")
}
}
PBT_APMSUSPEND | PBT_APMRESUMESUSPEND => { /* Ignore */ }
e => trace!("Unknown power event: {e}")
}
}
_ => {}
}
DefSubclassProc(hwnd, msg, wparam, lparam)
}
}
impl Drop for PowerEventRegistration {
fn drop(&mut self) {
unsafe {
UnregisterPowerSettingNotification(self.0).unwrap_or_else(|err| log::warn!("Failed to remove power notification registration: {err}"));
};
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/watchers/display_change.rs | src/watchers/display_change.rs | use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::UI::Shell::{DefSubclassProc, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{WM_DESTROY, WM_DISPLAYCHANGE};
use crate::Result;
pub struct DisplayChangeEventRegistration;
impl DisplayChangeEventRegistration {
pub fn register<F: FnMut()>(hwnd: HWND, callback: F) -> Result<Self> {
unsafe {
SetWindowSubclass(
hwnd,
Some(Self::wnd_proc::<F>),
super::DISPLAY_CHANGE_SUBCLASS_ID,
Box::into_raw(Box::new(callback)) as _
)
.ok()?;
}
Ok(Self)
}
unsafe extern "system" fn wnd_proc<F: FnMut()>(
hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM, _id: usize, subclass_input_ptr: usize
) -> LRESULT {
let callback_ptr = subclass_input_ptr as *mut F;
match msg {
WM_DESTROY => {
drop(Box::from_raw(callback_ptr));
}
WM_DISPLAYCHANGE => {
let callback = &mut *callback_ptr;
callback();
}
_ => {}
}
DefSubclassProc(hwnd, msg, wparam, lparam)
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/watchers/mod.rs | src/watchers/mod.rs | mod display_change;
mod power;
use std::sync::Once;
use display_change::DisplayChangeEventRegistration;
pub use power::PowerEvent;
use power::PowerEventRegistration;
use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{HMODULE, HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, IsWindow, RegisterClassW, HMENU, WINDOW_STYLE, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE,
WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT
};
use crate::Result;
pub struct EventWatcher {
hwnd: HWND,
power_state_listener: Option<PowerEventRegistration>,
display_change_listener: Option<DisplayChangeEventRegistration>
}
const POWER_SUBCLASS_ID: usize = 6666;
const DISPLAY_CHANGE_SUBCLASS_ID: usize = 6667;
impl EventWatcher {
pub fn new() -> Result<Self> {
let instance = unsafe { GetModuleHandleW(None)? };
let hwnd = unsafe {
CreateWindowExW(
WS_EX_NOACTIVATE | WS_EX_TRANSPARENT | WS_EX_LAYERED | WS_EX_TOOLWINDOW,
Self::build_class(instance),
PCWSTR::null(),
WINDOW_STYLE::default(),
0,
0,
0,
0,
HWND::default(),
HMENU::default(),
instance,
None
)
};
Ok(Self {
hwnd,
power_state_listener: None,
display_change_listener: None
})
}
pub fn on_power_event<F: FnMut(PowerEvent)>(mut self, callback: F) -> Result<Self> {
assert!(self.power_state_listener.is_none(), "Power event listener already registered");
self.power_state_listener = Some(PowerEventRegistration::register(self.hwnd, callback)?);
Ok(self)
}
pub fn on_display_change<F: FnMut()>(mut self, callback: F) -> Result<Self> {
assert!(self.display_change_listener.is_none(), "Display change listener already registered");
self.display_change_listener = Some(DisplayChangeEventRegistration::register(self.hwnd, callback)?);
Ok(self)
}
fn build_class(hinstance: HMODULE) -> PCWSTR {
static INITIALIZED: Once = Once::new();
let class_name = w!("tt_event_watcher");
INITIALIZED.call_once(|| {
unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
DefWindowProcW(hwnd, msg, wparam, lparam)
}
let wnd_class = WNDCLASSW {
lpfnWndProc: Some(wnd_proc),
hInstance: hinstance.into(),
lpszClassName: class_name,
..Default::default()
};
unsafe { RegisterClassW(&wnd_class) };
});
class_name
}
}
impl Drop for EventWatcher {
#[allow(clippy::drop_non_drop)]
fn drop(&mut self) {
drop(self.power_state_listener.take());
drop(self.display_change_listener.take());
unsafe {
if IsWindow(self.hwnd).as_bool() {
DestroyWindow(self.hwnd).unwrap_or_else(|err| log::warn!("Failed to destroy message window: {err}"));
}
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/windowing/hotkey.rs | src/windowing/hotkey.rs | use std::cell::RefCell;
use std::char::REPLACEMENT_CHARACTER;
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter, Write};
use std::marker::PhantomData;
use std::num::{NonZeroU32, NonZeroUsize};
use std::pin::Pin;
use std::str::FromStr;
use std::sync::atomic::{AtomicI32, Ordering};
use std::task::{Context, Poll, Waker};
use futures_lite::Stream;
use log::{trace, warn};
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyNameTextW, MapVirtualKeyW, RegisterHotKey, UnregisterHotKey, HOT_KEY_MODIFIERS, MAPVK_VK_TO_VSC, MOD_ALT, MOD_CONTROL, MOD_SHIFT, MOD_WIN, VIRTUAL_KEY, VK_CONTROL, VK_ESCAPE, VK_F1, VK_F2, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_RCONTROL, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SHIFT};
use crate::Result;
#[derive(Debug)]
pub struct HotKey {
id: i32,
_unsend: PhantomData<*const ()>,
}
impl HotKey {
pub fn register(combo: impl Into<KeyCombination>) -> Result<Self> {
static NEXT_ID: AtomicI32 = AtomicI32::new(0);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let KeyCombination { modifiers, key } = combo.into();
unsafe {
RegisterHotKey(None, id, modifiers.as_raw(), key.0)?;
}
Ok(Self {
id,
_unsend: PhantomData
})
}
}
impl Drop for HotKey {
fn drop(&mut self) {
LOCAL_STATE.with(|hotkeys| {
hotkeys.borrow_mut().remove(&self.id);
});
unsafe {
UnregisterHotKey(None, self.id)
.unwrap_or_else(|e| warn!("Failed to unregister hotkey: {:?}", e));
}
}
}
impl Stream for HotKey {
type Item = ();
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
LOCAL_STATE.with(|hotkeys| {
let mut hotkeys = hotkeys.borrow_mut();
let (triggered, waker) = hotkeys.entry(self.id).or_default();
if *triggered > 0 {
*triggered -= 1;
Poll::Ready(Some(()))
} else {
*waker = Some(cx.waker().clone());
Poll::Pending
}
})
}
}
thread_local! { static LOCAL_STATE: RefCell<HashMap<i32, (u32, Option<Waker>)>> = RefCell::new(HashMap::new()); }
pub fn process_hotkey_for_current_thread(id: i32) {
trace!("Processing hotkey (id: {id})");
LOCAL_STATE.with(|hotkeys| {
let mut hotkeys = hotkeys.borrow_mut();
let (triggered, waker) = hotkeys.entry(id).or_default();
*triggered += 1;
if let Some(waker) = waker {
waker.wake_by_ref();
}
});
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct KeyCombination {
pub modifiers: ModifierSet,
pub key: VirtualKey,
}
impl From<VirtualKey> for KeyCombination {
fn from(value: VirtualKey) -> Self {
Self {
modifiers: ModifierSet::empty(),
key: value,
}
}
}
impl From<VIRTUAL_KEY> for KeyCombination {
fn from(value: VIRTUAL_KEY) -> Self {
Self::from(VirtualKey::from(value))
}
}
impl<const N: usize> From<([Modifier; N], VirtualKey)> for KeyCombination {
fn from((modifiers, key): ([Modifier; N], VirtualKey)) -> Self {
Self { modifiers: ModifierSet::from_iter(modifiers), key }
}
}
impl<const N: usize> From<([Modifier; N], VIRTUAL_KEY)> for KeyCombination {
fn from((modifiers, key): ([Modifier; N], VIRTUAL_KEY)) -> Self {
Self::from((modifiers, VirtualKey::from(key)))
}
}
impl KeyCombination {
pub fn display(self, use_key_name: bool) -> impl Display {
struct KeyCombinationDisplay(KeyCombination, bool);
impl Display for KeyCombinationDisplay {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for m in self.0.modifiers {
f.write_fmt(format_args!("{} + ", m.name()))?;
}
if self.1 {
f.write_fmt(format_args!("{}", self.0.key.name()))?;
} else {
f.write_fmt(format_args!("0x{:X}", self.0.key.0))?;
}
Ok(())
}
}
KeyCombinationDisplay(self, use_key_name)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ParseKeyCombinationError {
UnknownModifier,
MalformattedKeyCode
}
impl Display for ParseKeyCombinationError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::UnknownModifier => f.write_str("Unknown modifier"),
Self::MalformattedKeyCode => f.write_str("Malformatted key code")
}
}
}
impl std::error::Error for ParseKeyCombinationError {}
impl FromStr for KeyCombination {
type Err = ParseKeyCombinationError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let mut tokens = s.rsplit('+');
let keycode = tokens
.next()
.ok_or(ParseKeyCombinationError::MalformattedKeyCode)?
.trim()
.trim_start_matches("0x");
let keycode = u32::from_str_radix(keycode, 16)
.map_err(|_| ParseKeyCombinationError::MalformattedKeyCode)?;
let modifiers: ModifierSet = tokens
.map(str::trim)
.map(|s| [Modifier::Alt, Modifier::Ctrl, Modifier::Shift, Modifier::Shift]
.into_iter()
.find(|&m| m.name().eq_ignore_ascii_case(s))
.ok_or(ParseKeyCombinationError::UnknownModifier))
.collect::<std::result::Result<_, _>>()?;
Ok(Self {
modifiers,
key: VirtualKey(keycode),
})
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct VirtualKey(u32);
impl VirtualKey {
pub const ESCAPE: VirtualKey = Self::from_vk(VK_ESCAPE);
pub const F1: VirtualKey = Self::from_vk(VK_F1);
pub const F2: VirtualKey = Self::from_vk(VK_F2);
const fn from_vk(vk: VIRTUAL_KEY) -> Self { Self(vk.0 as u32) }
const fn as_vk(self) -> VIRTUAL_KEY { VIRTUAL_KEY(self.0 as u16) }
pub fn name(self) -> impl Display {
struct KeyName(u32);
impl Display for KeyName {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut buf = [0u16; 32];
let success = NonZeroU32::new(unsafe { MapVirtualKeyW(self.0, MAPVK_VK_TO_VSC) })
.map(|sc| (sc.get() as i32) << 16)
.and_then(|sc| NonZeroUsize::new(unsafe { GetKeyNameTextW(sc, &mut buf) } as usize))
.is_some();
if success {
std::char::decode_utf16(buf.into_iter().take_while(|&c| c != 0))
.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
.try_for_each(|c| f.write_char(c))
} else {
f.write_fmt(format_args!("0x{:X}", self.0))
}
}
}
KeyName(self.0)
}
pub fn is_modifier(self) -> bool {
matches!(self.as_vk(),
VK_LMENU | VK_RMENU | VK_MENU |
VK_LSHIFT | VK_RSHIFT | VK_SHIFT |
VK_LCONTROL | VK_RCONTROL | VK_CONTROL |
VK_LWIN | VK_RWIN)
}
}
impl From<VIRTUAL_KEY> for VirtualKey {
fn from(value: VIRTUAL_KEY) -> Self {
Self::from_vk(value)
}
}
impl From<windows::System::VirtualKey> for VirtualKey {
fn from(value: windows::System::VirtualKey) -> Self {
Self(value.0 as u32)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u8)]
pub enum Modifier {
Shift = MOD_SHIFT.0 as u8,
Ctrl = MOD_CONTROL.0 as u8,
Alt = MOD_ALT.0 as u8,
Win = MOD_WIN.0 as u8,
}
impl Modifier {
const fn as_raw(self) -> HOT_KEY_MODIFIERS {
HOT_KEY_MODIFIERS(self as u8 as u32)
}
const fn from_raw(raw: HOT_KEY_MODIFIERS) -> Option<Self> {
match raw {
MOD_SHIFT => Some(Self::Shift),
MOD_CONTROL => Some(Self::Ctrl),
MOD_ALT => Some(Self::Alt),
MOD_WIN => Some(Self::Win),
_ => None
}
}
pub const fn name(self) -> &'static str {
match self {
Self::Shift => "Shift",
Self::Ctrl => "Ctrl",
Self::Alt => "Alt",
Self::Win => "Win",
}
}
}
#[derive(Default, Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct ModifierSet(HOT_KEY_MODIFIERS);
impl ModifierSet {
const fn as_raw(self) -> HOT_KEY_MODIFIERS { self.0 }
pub const fn empty() -> Self { Self(HOT_KEY_MODIFIERS(0)) }
pub const fn insert(&mut self, modifier: Modifier) {
self.0.0 |= modifier.as_raw().0;
}
pub const fn remove(&mut self, modifier: Modifier) {
self.0.0 &= !modifier.as_raw().0;
}
#[cfg(test)]
pub const fn contains(&self, modifier: Modifier) -> bool {
self.0.0 & modifier.as_raw().0 != 0
}
}
impl Debug for ModifierSet {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_set().entries(self.into_iter()).finish()
}
}
impl FromIterator<Modifier> for ModifierSet {
fn from_iter<T: IntoIterator<Item=Modifier>>(iter: T) -> Self {
let mut set = Self::empty();
for modifier in iter {
set.insert(modifier);
}
set
}
}
impl IntoIterator for ModifierSet {
type Item = Modifier;
type IntoIter = ModifierSetIter;
fn into_iter(self) -> Self::IntoIter {
ModifierSetIter(self)
}
}
#[derive(Copy, Clone)]
#[repr(transparent)]
pub struct ModifierSetIter(ModifierSet);
impl Iterator for ModifierSetIter {
type Item = Modifier;
fn next(&mut self) -> Option<Self::Item> {
let next = Modifier::from_raw(HOT_KEY_MODIFIERS(1u32.unbounded_shl(self.0.0.0.trailing_zeros())))?;
self.0.remove(next);
Some(next)
}
}
#[cfg(test)]
mod tests {
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyNameTextW, MapVirtualKeyW, MAPVK_VK_TO_VSC, MOD_NOREPEAT, VK_F1, VK_OEM_1, VK_SHIFT, VK_Y};
use super::*;
#[test]
fn test_modifier_set() {
let mut set = ModifierSet::empty();
set.insert(Modifier::Shift);
set.insert(Modifier::Ctrl);
assert_eq!(set.contains(Modifier::Shift), true);
assert_eq!(set.contains(Modifier::Ctrl), true);
assert_eq!(set.contains(Modifier::Alt), false);
}
#[test]
fn test_modifier_set_iter() {
let mut iter = ModifierSetIter(ModifierSet(MOD_WIN | MOD_SHIFT | MOD_ALT | MOD_CONTROL | MOD_NOREPEAT));
assert_eq!(iter.next(), Some(Modifier::Alt));
assert_eq!(iter.next(), Some(Modifier::Ctrl));
assert_eq!(iter.next(), Some(Modifier::Shift));
assert_eq!(iter.next(), Some(Modifier::Win));
assert_eq!(iter.next(), None);
}
#[test]
fn test_vk_to_unicode() {
let vk = VirtualKey::from(VK_Y);
println!("Name: {}", vk.name());
}
} | rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/windowing/mod.rs | src/windowing/mod.rs | mod event_loop;
mod window;
pub mod hotkey;
use std::mem::size_of;
use std::time::Duration;
pub use event_loop::event_loop;
use log::{trace, warn};
#[allow(unused_imports)]
pub use window::{Window, WindowBuilder, WindowLevel};
use windows::Win32::Foundation::{POINT, RECT};
use windows::Win32::Graphics::Gdi::{GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTOPRIMARY};
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VK_LBUTTON};
use windows::Win32::UI::WindowsAndMessaging::GetCursorPos;
use crate::runtime::Timer;
use crate::Result;
pub fn get_primary_work_area() -> Result<RECT> {
unsafe {
let primary_monitor = MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY);
let mut mi = MONITORINFO {
cbSize: size_of::<MONITORINFO>() as u32,
..Default::default()
};
GetMonitorInfoW(primary_monitor, &mut mi).ok()?;
Ok(mi.rcWork)
}
}
pub async fn poll_for_click_outside_of_rect(interval: Duration, rect: RECT) {
trace!("Polling for click outside of rect {:?}", rect);
let mut last = None;
loop {
let kc = unsafe { GetKeyState(VK_LBUTTON.0 as _) } & 1 != 0;
if Some(kc) != last {
if last.is_some() {
let mut pt = POINT::default();
if let Err(err) = unsafe { GetCursorPos(&mut pt) } {
warn!("Failed to get cursor position: {}", err);
continue;
}
trace!("Click at {}, {} (inside: {})", pt.x, pt.y, pt_in_rect(pt, rect));
if !pt_in_rect(pt, rect) {
break;
}
}
last = Some(kc);
}
Timer::after(interval).await;
}
}
fn pt_in_rect(pt: POINT, rect: RECT) -> bool {
pt.x >= rect.left && pt.x <= rect.right && pt.y >= rect.top && pt.y <= rect.bottom
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/windowing/window.rs | src/windowing/window.rs | use std::cell::Cell;
use std::mem::size_of;
use std::sync::Once;
use log::trace;
use windows::core::{h, w, ComInterface, TryIntoParam, HSTRING, PCWSTR};
use windows::Win32::Foundation::{BOOL, COLORREF, HANDLE, HMODULE, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows::Win32::Graphics::Dwm::{
DwmSetWindowAttribute, DWMSBT_MAINWINDOW, DWMWA_CAPTION_COLOR, DWMWA_COLOR_NONE, DWMWA_SYSTEMBACKDROP_TYPE, DWMWA_USE_IMMERSIVE_DARK_MODE,
DWM_SYSTEMBACKDROP_TYPE
};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::HiDpi::GetDpiForWindow;
use windows::Win32::UI::Input::KeyboardAndMouse::SetFocus;
use windows::Win32::UI::WindowsAndMessaging::*;
use windows_ext::Win32::System::WinRT::Xaml::IDesktopWindowXamlSourceNative;
use windows_ext::UI::Xaml::Hosting::DesktopWindowXamlSource;
use windows_ext::UI::Xaml::UIElement;
use crate::{win_assert, Result};
#[derive(Default)]
pub struct WindowBuilder {
hidden: bool,
close_handler: Option<Box<dyn FnMut() + 'static>>,
title: Option<HSTRING>,
icon: Option<u16>,
x: Option<i32>,
y: Option<i32>,
w: Option<i32>,
h: Option<i32>
}
impl WindowBuilder {
pub fn with_hidden(mut self, hidden: bool) -> Self {
self.hidden = hidden;
self
}
pub fn with_close_handler<F: FnMut() + 'static>(mut self, handler: F) -> Self {
self.close_handler = Some(Box::new(handler));
self
}
pub fn with_position(mut self, x: i32, y: i32) -> Self {
self.x = Some(x);
self.y = Some(y);
self
}
pub fn with_size(mut self, w: i32, h: i32) -> Self {
self.w = Some(w);
self.h = Some(h);
self
}
pub fn with_title<T: Into<HSTRING>>(mut self, title: T) -> Self {
self.title = Some(title.into());
self
}
pub fn with_icon_resource(mut self, icon: u16) -> Self {
self.icon = Some(icon);
self
}
pub fn build(self) -> Result<Window> {
Window::new(self)
}
}
#[derive(Default, Debug, Copy, Clone, Eq, PartialEq)]
pub enum WindowLevel {
AlwaysOnTop,
#[default]
Normal
}
impl From<WindowLevel> for HWND {
fn from(value: WindowLevel) -> Self {
match value {
WindowLevel::AlwaysOnTop => HWND_TOPMOST,
WindowLevel::Normal => HWND_TOP
}
}
}
pub struct Window {
pub hwnd: HWND,
source: DesktopWindowXamlSource,
icon: Option<HANDLE>
}
impl Window {
const CLASS_NAME: PCWSTR = w!("rusty-twinkle-tray.window");
fn new(builder: WindowBuilder) -> Result<Self> {
let instance = unsafe { GetModuleHandleW(None)? };
static REGISTER_WINDOW_CLASS: Once = Once::new();
REGISTER_WINDOW_CLASS.call_once(|| {
Self::register(instance).unwrap_or_else(|err| log::warn!("Failed to register window class: {}", err));
});
let mut ex_style = WS_EX_NOREDIRECTIONBITMAP; // | WS_EX_TOPMOST;
if builder.hidden {
ex_style |= WS_EX_LAYERED | WS_EX_NOACTIVATE;
}
let style = match builder.hidden {
true => WS_POPUP,
false => WS_OVERLAPPEDWINDOW
};
let hwnd = unsafe {
CreateWindowExW(
ex_style,
Self::CLASS_NAME,
builder.title.as_ref().unwrap_or(h!("XAML Island Window")),
style,
builder.x.unwrap_or(CW_USEDEFAULT),
builder.y.unwrap_or(CW_USEDEFAULT),
builder.w.unwrap_or(CW_USEDEFAULT),
builder.h.unwrap_or(CW_USEDEFAULT),
None,
None,
instance,
None
)
};
win_assert!(hwnd != HWND::default());
if builder.hidden {
unsafe {
SetLayeredWindowAttributes(hwnd, COLORREF::default(), 0, LWA_ALPHA)?;
}
}
let desktop_source = DesktopWindowXamlSource::new()?;
let interop = desktop_source.cast::<IDesktopWindowXamlSourceNative>()?;
unsafe {
interop.AttachToWindow(hwnd)?;
let island = interop.WindowHandle()?;
let window_data = Box::new(WindowData {
island,
close_handler: Cell::new(builder.close_handler)
});
SetWindowLongPtrW(hwnd, GWLP_USERDATA, Box::into_raw(window_data) as _);
sync_size(hwnd, island)?;
}
let icon = match builder.icon {
None => None,
Some(id) => unsafe {
let icon = LoadImageW(instance, PCWSTR(id as *const u16), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE)?;
SendMessageW(hwnd, WM_SETICON, WPARAM(ICON_BIG as usize), LPARAM(icon.0));
SendMessageW(hwnd, WM_SETICON, WPARAM(ICON_SMALL as usize), LPARAM(icon.0));
Some(icon)
}
};
Ok(Self {
hwnd,
source: desktop_source,
icon
})
}
pub fn hwnd(&self) -> HWND {
self.hwnd
}
pub fn set_foreground(&self) -> bool {
unsafe { SetForegroundWindow(self.hwnd).as_bool() }
}
pub fn set_window_pos(&self, order: Option<WindowLevel>, pos: Option<(i32, i32)>, size: Option<(i32, i32)>, visible: Option<bool>) {
let (x, y) = pos.unwrap_or_default();
let (w, h) = size.unwrap_or_default();
let after = HWND::from(order.unwrap_or_default());
let mut flags = SET_WINDOW_POS_FLAGS::default();
if pos.is_none() {
flags |= SWP_NOMOVE;
}
if size.is_none() {
flags |= SWP_NOSIZE;
}
if order.is_none() {
flags |= SWP_NOZORDER;
}
if let Some(visible) = visible {
flags |= if visible { SWP_SHOWWINDOW } else { SWP_HIDEWINDOW };
}
unsafe {
SetWindowPos(self.hwnd, after, x, y, w, h, flags).unwrap_or_else(|err| log::warn!("Failed to set window position: {}", err));
}
}
pub fn set_visible(&self, visible: bool) {
self.set_window_pos(None, None, None, Some(visible))
}
pub fn focus(&self) {
unsafe {
SetFocus(self.hwnd);
}
}
pub fn dpi(&self) -> f32 {
unsafe { GetDpiForWindow(self.hwnd) as f32 / USER_DEFAULT_SCREEN_DPI as f32 }
}
pub fn set_content<T: TryIntoParam<UIElement>>(&self, content: T) -> Result<()> {
self.source.SetContent(content)?;
Ok(())
}
pub fn apply_mica_backdrop(&self) -> Result<()> {
unsafe {
DwmSetWindowAttribute(
self.hwnd,
DWMWA_SYSTEMBACKDROP_TYPE,
&DWMSBT_MAINWINDOW as *const _ as _,
size_of::<DWM_SYSTEMBACKDROP_TYPE>() as u32
)?
}
Ok(())
}
pub fn make_titlebar_transparent(&self) -> Result<()> {
unsafe {
DwmSetWindowAttribute(
self.hwnd,
DWMWA_CAPTION_COLOR,
&DWMWA_COLOR_NONE as *const _ as _,
size_of::<COLORREF>() as u32
)?
}
Ok(())
}
pub fn enable_immersive_dark_mode(&self, enabled: bool) -> Result<()> {
unsafe {
DwmSetWindowAttribute(
self.hwnd,
DWMWA_USE_IMMERSIVE_DARK_MODE,
&BOOL::from(&enabled) as *const _ as _,
size_of::<BOOL>() as u32
)?
}
Ok(())
}
fn register(instance: HMODULE) -> Result<()> {
let class = WNDCLASSEXW {
cbSize: size_of::<WNDCLASSEXW>() as u32,
lpfnWndProc: Some(Self::wnd_proc),
hInstance: instance.into(),
lpszClassName: Self::CLASS_NAME,
..Default::default()
};
win_assert!(unsafe { RegisterClassExW(&class) } != 0);
Ok(())
}
unsafe extern "system" fn wnd_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
// Treat the pointer as 'const' instead of 'mut' as I'm not sure if this function is reentrant
let window_data = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const WindowData;
match msg {
WM_NCCREATE => {
SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
}
WM_SIZING | WM_SIZE => {
if let Some(data) = window_data.as_ref() {
sync_size(hwnd, data.island).unwrap_or_else(|err| log::warn!("Failed to sync window size: {}", err));
}
}
/*
This doesn't seem to produce correct results on Win11 despite what the docs say:
https://learn.microsoft.com/en-us/windows/win32/hidpi/wm-dpichanged
WM_DPICHANGED => {
let suggested_rect = *(lparam.0 as *const RECT);
SetWindowPos(
hwnd,
None,
suggested_rect.left,
suggested_rect.right,
suggested_rect.right - suggested_rect.left,
suggested_rect.bottom- suggested_rect.top,
SWP_NOZORDER | SWP_NOACTIVATE
).unwrap();
},
*/
WM_CLOSE => {
if let Some(data) = window_data.as_ref() {
if let Some(mut callback) = data.close_handler.take() {
callback();
data.close_handler.set(Some(callback))
}
}
return LRESULT::default();
}
WM_DESTROY => {
trace!("Destroying window data");
// Here we really need a 'mut' pointer, but we erase the pointer first so it should be fine
SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
drop(Box::from_raw(window_data as *mut WindowData));
// the event loop implementation currently doesn't handle quit messages
// PostQuitMessage(0);
}
_ => {}
}
DefWindowProcW(hwnd, msg, wparam, lparam)
}
}
impl Drop for Window {
fn drop(&mut self) {
unsafe {
if IsWindow(self.hwnd).as_bool() {
DestroyWindow(self.hwnd).unwrap_or_else(|err| log::warn!("Failed to destroy window: {}", err));
}
if let Some(icon) = self.icon.take() {
DestroyIcon(HICON(icon.0)).unwrap_or_else(|err| log::warn!("Failed to destroy window icon: {}", err))
}
}
}
}
fn sync_size(hwnd: HWND, island: HWND) -> Result<()> {
unsafe {
let mut rect = RECT::default();
GetClientRect(hwnd, &mut rect)?;
SetWindowPos(
island,
HWND::default(),
0,
0,
rect.right - rect.left,
rect.bottom - rect.top,
SWP_SHOWWINDOW
)?;
Ok(())
}
}
struct WindowData {
island: HWND,
close_handler: Cell<Option<Box<dyn FnMut() + 'static>>>
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/windowing/event_loop.rs | src/windowing/event_loop.rs | use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::time::Duration;
use futures_lite::pin;
use windows::core::Error;
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_ABANDONED_0, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::System::Threading::{
CreateEventExW, ResetEvent, SetEvent, CREATE_EVENT_INITIAL_SET, CREATE_EVENT_MANUAL_RESET, EVENT_MODIFY_STATE, INFINITE,
SYNCHRONIZATION_SYNCHRONIZE
};
use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, MsgWaitForMultipleObjects, PeekMessageW, TranslateMessage, MSG, PM_REMOVE, QS_ALLINPUT, WM_HOTKEY};
use crate::runtime::process_timers_for_current_thread;
use crate::Result;
use crate::windowing::hotkey::process_hotkey_for_current_thread;
struct LoopWaker {
event: HANDLE,
awake: AtomicBool,
notified: AtomicBool
}
impl LoopWaker {
pub fn new() -> Result<Self> {
let handle = unsafe {
CreateEventExW(
None,
None,
CREATE_EVENT_MANUAL_RESET | CREATE_EVENT_INITIAL_SET,
(EVENT_MODIFY_STATE | SYNCHRONIZATION_SYNCHRONIZE).0
)?
};
Ok(Self {
event: handle,
awake: AtomicBool::new(false),
notified: AtomicBool::new(true)
})
}
fn notify(&self) {
if self.notified.swap(true, Ordering::SeqCst) || self.awake.load(Ordering::SeqCst) {
return;
}
unsafe {
SetEvent(self.event).unwrap_or_else(|err| log::warn!("Failed to signal event: {}", err));
}
}
fn reset(&self) {
unsafe {
ResetEvent(self.event).unwrap_or_else(|err| log::warn!("Failed to reset event: {}", err));
}
}
fn handle(&self) -> HANDLE {
self.event
}
}
impl Drop for LoopWaker {
fn drop(&mut self) {
unsafe {
CloseHandle(self.event).unwrap_or_else(|err| log::warn!("Failed to close handle: {}", err));
}
}
}
impl Wake for LoopWaker {
fn wake(self: Arc<Self>) {
self.notify();
}
fn wake_by_ref(self: &Arc<Self>) {
self.notify();
}
}
pub fn event_loop<F: Future<Output = Result<()>>>(fut: F) -> Result<()> {
pin!(fut);
let notifier = Arc::new(LoopWaker::new()?);
let waker = Waker::from(notifier.clone());
loop {
notifier.awake.store(true, Ordering::SeqCst);
let mut next_timer;
while {
let mut cont = !pump_events();
next_timer = process_timers_for_current_thread();
if notifier.notified.swap(false, Ordering::SeqCst) {
let mut cx = Context::from_waker(&waker);
match fut.as_mut().poll(&mut cx) {
Poll::Ready(result) => return result,
Poll::Pending => {
cont = true;
} //pump_events()
}
}
cont
} {}
notifier.reset();
notifier.awake.store(false, Ordering::SeqCst);
match wait_for(&[notifier.handle()], next_timer)? {
WaitResult::Handle(_) => {}
WaitResult::Message => {}
WaitResult::Timeout => {}
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum WaitResult {
Handle(usize),
Message,
Timeout
}
fn wait_for(handles: &[HANDLE], timeout: Option<Duration>) -> windows::core::Result<WaitResult> {
const SUCCESS: u32 = WAIT_OBJECT_0.0;
const ABANDONED: u32 = WAIT_ABANDONED_0.0;
let timeout = timeout
.and_then(|d| d.as_millis().try_into().ok())
.unwrap_or(INFINITE);
let result = unsafe { MsgWaitForMultipleObjects(Some(handles), false, timeout, QS_ALLINPUT) };
match result {
r if (SUCCESS..SUCCESS + handles.len() as u32).contains(&r.0) => Ok(WaitResult::Handle((r.0 - SUCCESS) as usize)),
r if r.0 == SUCCESS + handles.len() as u32 => Ok(WaitResult::Message),
r if (ABANDONED..ABANDONED + handles.len() as u32).contains(&r.0) => panic!("One of the handles was abandoned"),
WAIT_TIMEOUT => Ok(WaitResult::Timeout),
WAIT_FAILED => Err(Error::from_win32()),
_ => unreachable!()
}
}
fn pump_events() -> bool {
let mut limit = 10;
let mut message = MSG::default();
unsafe {
while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).into() {
TranslateMessage(&message);
DispatchMessageW(&message);
if message.message == WM_HOTKEY {
process_hotkey_for_current_thread(message.wParam.0 as i32);
}
limit -= 1;
if limit <= 0 {
return false;
}
}
}
true
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/runtime/timer.rs | src/runtime/timer.rs | use std::cell::RefCell;
use std::collections::BTreeMap;
use std::future::Future;
use std::marker::PhantomData;
use std::mem::replace;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};
#[derive(Default)]
struct TimerState {
timers: BTreeMap<(Instant, usize), Waker>,
next_id: usize
}
impl TimerState {
pub fn insert_timer(&mut self, at: Instant, waker: Waker) -> usize {
let id = self.next_id;
self.next_id += 1;
self.timers.insert((at, id), waker);
id
}
pub fn remove_timer(&mut self, at: Instant, id: usize) {
self.timers.remove(&(at, id));
}
pub fn process_timers(&mut self) -> Option<Duration> {
let now = Instant::now();
let pending = self.timers.split_off(&(now + Duration::from_nanos(1), 0));
let ready = replace(&mut self.timers, pending);
ready.values().for_each(Waker::wake_by_ref);
self.timers
.keys()
.next()
.map(|(when, _)| when.saturating_duration_since(now))
}
}
thread_local! { static LOCAL_STATE: RefCell<TimerState> = RefCell::new(TimerState::default()); }
pub fn process_timers_for_current_thread() -> Option<Duration> {
LOCAL_STATE.with(|timers| timers.borrow_mut().process_timers())
}
pub struct Timer {
at: Option<Instant>,
id: Option<usize>,
_unsend: PhantomData<*const ()>,
}
impl Timer {
pub const fn never() -> Self {
Self { at: None, id: None, _unsend: PhantomData }
}
pub const fn at(instant: Instant) -> Self {
Self { at: Some(instant), id: None, _unsend: PhantomData }
}
pub fn after(duration: Duration) -> Self {
Instant::now()
.checked_add(duration)
.map_or_else(Self::never, Self::at)
}
}
impl Future for Timer {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.at {
None => Poll::Pending,
Some(at) => match Instant::now() >= at {
true => Poll::Ready(()),
false => {
if self.id.is_none() {
self.id = LOCAL_STATE
.with(|timers| timers.borrow_mut().insert_timer(at, cx.waker().clone()))
.into();
}
Poll::Pending
}
}
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
if let Some((at, id)) = self.at.zip(self.id) {
LOCAL_STATE.with(|timers| {
timers.borrow_mut().remove_timer(at, id);
});
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/runtime/executor.rs | src/runtime/executor.rs | use std::cell::Cell;
use std::collections::VecDeque;
use std::future::{poll_fn, Future};
use std::mem::take;
use std::pin::Pin;
use std::task::Poll;
use futures_lite::pin;
type Task = Pin<Box<dyn Future<Output = ()> + 'static>>;
/// A simple executor that runs tasks on the current thread.
///
/// It doesn't scale very well with many tasks, but it's good enough for our use case
/// as we are only spawning one task per monitor and people *hopefully* do not have thousands of monitors.
#[derive(Default)]
pub struct LocalExecutor {
tasks: Cell<VecDeque<Task>>
}
impl LocalExecutor {
fn queue_task(&self, task: Task) {
let mut tasks = self.tasks.take();
tasks.push_back(task);
self.tasks.set(tasks);
}
pub async fn run<T>(&self, fut: impl Future<Output = T>) -> T {
pin!(fut);
let mut local_buffer = VecDeque::new();
poll_fn(|cx| {
local_buffer = self.tasks.replace(take(&mut local_buffer));
while let Some(mut task) = local_buffer.pop_front() {
match task.as_mut().poll(cx) {
Poll::Ready(()) => { /* task done; don't requeue */ }
Poll::Pending => self.queue_task(task)
}
}
fut.as_mut().poll(cx)
})
.await
}
pub fn spawn(&self, fut: impl Future<Output = ()> + 'static) {
self.queue_task(Box::pin(fut));
}
pub fn clean_pending_tasks(&self) {
let mut tasks = self.tasks.take();
tasks.clear();
self.tasks.set(tasks);
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/runtime/reducing_spsc.rs | src/runtime/reducing_spsc.rs | use std::cell::Cell;
use std::error::Error;
use std::fmt::Display;
use std::future::{poll_fn, Future};
use std::rc::Rc;
use std::task::{Poll, Waker};
pub trait Reducible {
fn reduce(self, other: Self) -> Self;
}
pub fn channel<T: Reducible>() -> (ReducingSender<T>, ReducingReceiver<T>) {
let shared = Rc::new(Shared {
value: Cell::new(None),
closed: Cell::new(false),
waiter: Cell::new(None)
});
(ReducingSender(shared.clone()), ReducingReceiver(shared))
}
struct Shared<T> {
value: Cell<Option<T>>,
closed: Cell<bool>,
waiter: Cell<Option<Waker>>
}
pub struct ReducingSender<T>(Rc<Shared<T>>);
impl<T: Reducible> ReducingSender<T> {
pub fn try_send(&self, value: T) -> Result<(), TrySendError> {
if self.0.closed.get() {
return Err(TrySendError::Closed);
}
self.0.value.set(match self.0.value.take() {
None => Some(value),
Some(current) => Some(current.reduce(value))
});
if let Some(waker) = self.0.waiter.take() {
waker.wake();
}
Ok(())
}
}
impl<T> Drop for ReducingSender<T> {
fn drop(&mut self) {
self.0.closed.set(true);
if let Some(waker) = self.0.waiter.take() {
waker.wake();
}
}
}
pub struct ReducingReceiver<T>(Rc<Shared<T>>);
impl<T> ReducingReceiver<T> {
pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
match self.0.value.take() {
None => match self.0.closed.get() {
true => Err(TryRecvError::Closed),
false => Err(TryRecvError::Empty)
},
Some(v) => Ok(v)
}
}
pub fn recv(&mut self) -> impl Future<Output = Option<T>> + '_ {
poll_fn(move |cx| match self.try_recv() {
Ok(v) => Poll::Ready(Some(v)),
Err(TryRecvError::Closed) => Poll::Ready(None),
Err(TryRecvError::Empty) => {
self.0.waiter.replace(Some(cx.waker().clone()));
Poll::Pending
}
})
}
}
impl<T> Drop for ReducingReceiver<T> {
fn drop(&mut self) {
self.0.closed.set(true);
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TrySendError {
Closed
}
impl Display for TrySendError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Channel is closed")
}
}
impl Error for TrySendError {}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TryRecvError {
Closed,
Empty
}
impl Display for TryRecvError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
TryRecvError::Closed => write!(f, "Channel is closed"),
TryRecvError::Empty => write!(f, "Channel is empty")
}
}
}
impl Error for TryRecvError {}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/runtime/mod.rs | src/runtime/mod.rs | use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{current, park, park_timeout, Thread};
pub use executor::LocalExecutor;
use futures_lite::{pin, Stream};
pub use timer::{process_timers_for_current_thread, Timer};
mod executor;
pub mod reducing_spsc;
mod timer;
#[derive(Default)]
pub enum FutureStream<T> {
#[default]
Empty,
Waiting(Pin<Box<dyn Future<Output = Option<T>>>>)
}
impl<T> FutureStream<T> {
pub const fn new() -> Self {
Self::Empty
}
pub fn clear(&mut self) {
*self = FutureStream::Empty;
}
pub fn set<F>(&mut self, future: F)
where
F: Future<Output = Option<T>> + 'static
{
*self = FutureStream::Waiting(Box::pin(future));
}
}
impl<T> Stream for FutureStream<T> {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.as_mut().get_mut() {
FutureStream::Waiting(fut) => match fut.as_mut().poll(cx) {
Poll::Ready(result) => {
self.set(FutureStream::Empty);
match result {
Some(item) => Poll::Ready(Some(item)),
None => Poll::Pending
}
}
Poll::Pending => Poll::Pending
},
FutureStream::Empty => Poll::Pending
}
}
}
struct Signal {
thread: Thread,
signaled: AtomicBool
}
impl Signal {
fn new() -> Self {
Self {
thread: current(),
signaled: AtomicBool::new(false)
}
}
fn ready(&self) -> bool {
self.signaled.load(Ordering::SeqCst)
}
fn reset(&self) {
self.signaled.store(false, Ordering::SeqCst)
}
}
impl Wake for Signal {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}
fn wake_by_ref(self: &Arc<Self>) {
self.signaled.store(true, Ordering::SeqCst);
self.thread.unpark();
}
}
pub fn block_on<F: Future>(fut: F) -> F::Output {
pin!(fut);
let signal = Arc::new(Signal::new());
let waker = Waker::from(signal.clone());
let mut context = Context::from_waker(&waker);
loop {
signal.reset();
match fut.as_mut().poll(&mut context) {
Poll::Pending => {
let sleep_dur = process_timers_for_current_thread();
match signal.ready() {
true => continue,
false => match sleep_dur {
None => park(),
Some(dur) => park_timeout(dur)
}
}
}
Poll::Ready(item) => break item
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/elevation.rs | src/utils/elevation.rs | use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{CloseHandle, HANDLE, HWND, WAIT_FAILED};
use windows::Win32::System::Threading::{WaitForSingleObject, INFINITE};
use windows::Win32::UI::Shell::{ShellExecuteExW, SEE_MASK_NOCLOSEPROCESS, SEE_MASK_NO_CONSOLE, SHELLEXECUTEINFOW};
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
use crate::Result;
pub fn relaunch_as_elevated(parent: HWND, cmd: &str) -> Result<()> {
let exe_path = std::env::current_exe()
.expect("Failed to get current exe")
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect::<Vec<_>>();
let args = cmd.encode_utf16().chain(Some(0)).collect::<Vec<_>>();
let handle = unsafe {
let mut options = SHELLEXECUTEINFOW {
cbSize: size_of::<SHELLEXECUTEINFOW>() as u32,
fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
hwnd: parent,
lpVerb: w!("runas"),
lpFile: PCWSTR(exe_path.as_ptr()),
lpParameters: PCWSTR(args.as_ptr()),
lpDirectory: PCWSTR::null(),
nShow: SW_SHOWNORMAL.0,
hInstApp: Default::default(),
lpIDList: null_mut(),
lpClass: PCWSTR::null(),
hkeyClass: Default::default(),
dwHotKey: 0,
Anonymous: Default::default(),
hProcess: Default::default()
};
ShellExecuteExW(&mut options)?;
ProcessHandle(options.hProcess)
};
handle.wait()?;
Ok(())
}
struct ProcessHandle(HANDLE);
impl ProcessHandle {
pub fn wait(&self) -> Result<()> {
unsafe {
if WaitForSingleObject(self.0, INFINITE) == WAIT_FAILED {
return Err(windows::core::Error::from_win32().into());
}
}
Ok(())
}
}
impl Drop for ProcessHandle {
fn drop(&mut self) {
unsafe {
CloseHandle(self.0).unwrap_or_else(|e| log::warn!("Failed to close process handle: {e}"));
};
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/string.rs | src/utils/string.rs | use std::cell::Cell;
use std::ffi::OsString;
use std::fmt::{Arguments, Debug, Display, Formatter, Write};
use std::os::windows::ffi::OsStringExt;
use std::path::PathBuf;
use windows::core::{HSTRING, PCWSTR};
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct WStr<const N: usize>([u16; N]);
impl<const N: usize> From<[u16; N]> for WStr<N> {
fn from(value: [u16; N]) -> Self {
Self(value)
}
}
impl<const N: usize> Display for WStr<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for c in char::decode_utf16(self.as_slice().iter().copied()) {
f.write_char(c.unwrap_or(std::char::REPLACEMENT_CHARACTER))?
}
Ok(())
}
}
impl<const N: usize> Debug for WStr<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "\"{}\"", self)
}
}
impl<const N: usize> From<WStr<N>> for OsString {
fn from(value: WStr<N>) -> Self {
OsString::from_wide(value.as_slice())
}
}
impl<const N: usize> From<WStr<N>> for PathBuf {
fn from(value: WStr<N>) -> Self {
PathBuf::from(OsString::from(value))
}
}
impl<const N: usize> WStr<N> {
pub fn as_slice(&self) -> &[u16] {
let end = self.0.iter().position(|c| *c == 0).unwrap_or(self.0.len());
&self.0[..end]
}
#[allow(clippy::wrong_self_convention)]
pub fn to_string_lossy(&self) -> String {
String::from_utf16_lossy(self.as_slice())
}
}
#[derive(Default)]
pub struct U16TextBuffer {
inner: Vec<u16>
}
impl U16TextBuffer {
pub fn clear(&mut self) {
self.inner.clear();
}
pub fn finish(&mut self) -> PCWSTR {
self.inner.push(0);
PCWSTR(self.inner.as_ptr())
}
pub fn as_wide(&self) -> &[u16] {
self.inner.as_slice()
}
pub fn write<S: AsRef<str>>(&mut self, text: S) {
self.inner.extend(text.as_ref().encode_utf16());
}
pub fn with_local<R, F: FnOnce(&mut U16TextBuffer) -> R>(callback: F) -> R {
thread_local! { static LOCAL_BUFFER: Cell<Option<U16TextBuffer>> = Default::default() }
let mut buffer = LOCAL_BUFFER
.try_with(|tls| tls.take())
.ok()
.flatten()
.unwrap_or_default();
buffer.clear();
let result = callback(&mut buffer);
let _ = LOCAL_BUFFER.try_with(move |tls| tls.set(Some(buffer)));
result
}
}
impl Write for U16TextBuffer {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.write(s);
Ok(())
}
}
#[must_use]
#[inline]
pub fn hformat(args: Arguments<'_>) -> HSTRING {
U16TextBuffer::with_local(move |buffer| {
buffer.write_fmt(args).expect("Failed to format");
HSTRING::from_wide(buffer.as_wide()).unwrap()
})
}
#[macro_export]
macro_rules! hformat {
($($arg:tt)*) => {{
$crate::utils::string::hformat(std::format_args!($($arg)*))
}}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/logger.rs | src/utils/logger.rs | use std::sync::OnceLock;
use log::{LevelFilter, Log, Metadata, Record};
struct ConsoleLogger(LevelFilter);
impl Log for ConsoleLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= self.0
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("[{:<5}] {}", record.level(), record.args());
}
}
fn flush(&self) {}
}
struct DebuggerLogger(LevelFilter);
impl Log for DebuggerLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= self.0
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
debugger::print(format_args!("[{:<5}] {}", record.level(), record.args()))
}
}
fn flush(&self) {}
}
struct CombinedLogger {
console: ConsoleLogger,
debugger: DebuggerLogger
}
impl CombinedLogger {
pub const fn new(console_level: LevelFilter, debugger_level: LevelFilter) -> Self {
Self {
console: ConsoleLogger(console_level),
debugger: DebuggerLogger(debugger_level)
}
}
pub fn max_level(&self) -> LevelFilter {
self.console.0.max(self.debugger.0)
}
}
impl Log for CombinedLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
self.console.enabled(metadata) || self.debugger.enabled(metadata)
}
fn log(&self, record: &Record) {
self.console.log(record);
self.debugger.log(record);
}
fn flush(&self) {
self.console.flush();
self.debugger.flush();
}
}
pub fn init(console_level: LevelFilter, debugger_level: LevelFilter) -> bool {
static LOGGER: OnceLock<CombinedLogger> = OnceLock::new();
if LOGGER.get().is_some() {
return false;
}
let logger = LOGGER.get_or_init(|| CombinedLogger::new(console_level, debugger_level));
log::set_logger(logger).expect("Failed to set logger");
log::set_max_level(logger.max_level());
true
}
mod debugger {
use std::fmt::{Arguments, Write};
use windows::Win32::System::Diagnostics::Debug::OutputDebugStringW;
use crate::utils::string::U16TextBuffer;
pub fn print(args: Arguments<'_>) {
U16TextBuffer::with_local(move |buffer| {
buffer.write_fmt(args).expect("Failed to format log string");
unsafe { OutputDebugStringW(buffer.finish()) }
})
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/panic.rs | src/utils/panic.rs | use std::backtrace::{Backtrace, BacktraceStatus};
use std::fmt::{Arguments, Write};
//use std::panic::take_hook as take_panic_hook;
use std::panic::set_hook as set_panic_hook;
use windows::core::w;
use windows::Win32::UI::WindowsAndMessaging::{MessageBoxW, MB_ICONERROR, MB_OK, MB_TASKMODAL};
use crate::utils::string::U16TextBuffer;
pub fn set_hook() {
//let hook = take_panic_hook();
set_panic_hook(Box::new(move |info| {
let capture = Backtrace::capture();
match capture.status() {
BacktraceStatus::Captured => log::error!("{info}\n{capture}"),
_ => log::error!("{info}")
}
//hook(info);
show_msg(format_args!("{info}"));
}))
}
//pub fn abort_on_panic<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> R {
// match catch_unwind(f) {
// Ok(r) => r,
// Err(panic) => {
// let msg = panic
// .downcast_ref::<&'static str>()
// .unwrap_or("")
// }
// }
//}
pub fn show_msg(args: Arguments<'_>) {
if cfg!(debug_assertions) {
return;
}
let mut buffer = U16TextBuffer::default();
buffer.write_fmt(args).unwrap_or_else(|_| {
buffer.clear();
buffer.write("Failed to format message!");
});
unsafe {
MessageBoxW(None, buffer.finish(), w!("Panic"), MB_OK | MB_ICONERROR | MB_TASKMODAL);
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/error.rs | src/utils/error.rs | use std::backtrace::Backtrace;
use std::borrow::Cow;
use std::fmt::{Debug, Display, Formatter};
use std::num::{ParseFloatError, ParseIntError};
use std::panic::Location;
use std::str::ParseBoolError;
use betrayer::{ErrorSource, TrayError};
use windows::core::{Error, HRESULT};
use windows::Win32::Foundation::{NO_ERROR, WIN32_ERROR};
use crate::windowing::hotkey::ParseKeyCombinationError;
pub type Result<T> = std::result::Result<T, TracedError>;
pub enum Trace {
Backtrace(Box<Backtrace>),
Location(Location<'static>)
}
impl Trace {
#[track_caller]
pub fn capture() -> Self {
//let capture = Backtrace::capture();
//match capture.status() {
// BacktraceStatus::Captured => Self::Backtrace(Box::new(capture)),
// _ => Self::Location(*Location::caller())
//}
Self::Location(*Location::caller())
}
pub fn is_backtrace(&self) -> bool {
matches!(self, Self::Backtrace(_))
}
}
impl Debug for Trace {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Trace::Backtrace(capture) => Debug::fmt(capture, f),
Trace::Location(location) => Debug::fmt(location, f)
}
}
}
impl Display for Trace {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Trace::Backtrace(capture) => Display::fmt(capture, f),
Trace::Location(location) => Display::fmt(location, f)
}
}
}
enum InnerError {
Win(Error),
String(Cow<'static, str>),
External(Box<dyn std::error::Error + 'static>)
}
pub struct TracedError {
inner: InnerError,
backtrace: Trace
}
impl TracedError {
pub fn message(&self) -> String {
match &self.inner {
InnerError::Win(err) => err.message().to_string_lossy(),
InnerError::String(msg) => msg.clone().into_owned(),
InnerError::External(msg) => msg.to_string()
}
}
pub fn trace(&self) -> &Trace {
&self.backtrace
}
}
impl Debug for TracedError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut debug = f.debug_struct("Error");
match &self.inner {
InnerError::Win(err) => debug
.field("code", &err.code())
.field("message", &err.message()),
InnerError::String(msg) => debug.field("message", &FromDisplay(msg)),
InnerError::External(err) => debug.field("message", &FromDisplay(err))
};
if !self.backtrace.is_backtrace() {
debug.field("location", &FromDisplay(&self.backtrace));
}
debug.finish()?;
if self.backtrace.is_backtrace() {
write!(f, "\n{}", self.backtrace)?;
}
Ok(())
}
}
impl Display for TracedError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.inner {
InnerError::Win(inner) => Display::fmt(inner, f),
InnerError::String(inner) => Display::fmt(inner, f),
InnerError::External(inner) => Display::fmt(inner, f)
}
}
}
impl std::error::Error for TracedError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.inner {
InnerError::Win(err) => Some(err),
InnerError::String(_) => None,
InnerError::External(err) => Some(err.as_ref())
}
}
}
impl From<&'static str> for TracedError {
#[track_caller]
fn from(value: &'static str) -> Self {
Self {
inner: InnerError::String(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<String> for TracedError {
#[track_caller]
fn from(value: String) -> Self {
Self {
inner: InnerError::String(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<Error> for TracedError {
#[track_caller]
fn from(value: Error) -> Self {
Self {
inner: InnerError::Win(value),
backtrace: Trace::capture()
}
}
}
impl From<ParseBoolError> for TracedError {
#[track_caller]
fn from(value: ParseBoolError) -> Self {
Self {
inner: InnerError::External(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<ParseIntError> for TracedError {
#[track_caller]
fn from(value: ParseIntError) -> Self {
Self {
inner: InnerError::External(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<ParseFloatError> for TracedError {
#[track_caller]
fn from(value: ParseFloatError) -> Self {
Self {
inner: InnerError::External(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<ParseKeyCombinationError> for TracedError {
#[track_caller]
fn from(value: ParseKeyCombinationError) -> Self {
Self {
inner: InnerError::External(value.into()),
backtrace: Trace::capture()
}
}
}
impl From<TrayError> for TracedError {
fn from(value: TrayError) -> Self {
let inner = match value.source() {
ErrorSource::Os(err) => {
let code = HRESULT(err.code().0);
InnerError::Win(Error::from(code))
}
ErrorSource::Custom(inner) => InnerError::String(inner.clone())
};
Self {
inner,
backtrace: Trace::Location(*value.location())
}
}
}
impl From<std::io::Error> for TracedError {
#[track_caller]
fn from(value: std::io::Error) -> Self {
Self {
inner: match value.raw_os_error() {
None => InnerError::External(Box::new(value)),
Some(raw) => InnerError::Win(Error::from(WIN32_ERROR(raw as _)))
},
backtrace: Trace::capture()
}
}
}
struct FromDisplay<T>(pub T);
impl<T: Display> Debug for FromDisplay<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self.0, f)
}
}
pub trait TracedResultEx<T> {
fn to_win_result(self) -> windows::core::Result<T>;
}
impl<T> TracedResultEx<T> for Result<T> {
fn to_win_result(self) -> windows::core::Result<T> {
self.map_err(|err| match err.inner {
InnerError::Win(err) => err,
_ => Error::from(NO_ERROR)
})
}
}
pub trait WinOptionExt<T> {
fn some(self) -> windows::core::Result<T>;
}
impl<T> WinOptionExt<T> for Option<T> {
fn some(self) -> windows::core::Result<T> {
self.ok_or(Error::from(NO_ERROR))
}
}
#[macro_export]
macro_rules! win_assert {
($cond:expr) => {
if !($cond) {
Err(windows::core::Error::from(windows::Win32::Foundation::ERROR_ASSERTION_FAILURE))?;
}
};
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/extensions.rs | src/utils/extensions.rs | use std::sync::{Mutex, MutexGuard};
use crate::runtime::reducing_spsc::{Reducible, ReducingSender};
pub trait ChannelExt<T> {
#[track_caller]
fn filter_send_ignore(&self, msg: Option<T>) {
if let Some(msg) = msg {
self.send_ignore(msg);
}
}
fn send_ignore(&self, msg: T);
}
impl<T> ChannelExt<T> for loole::Sender<T> {
#[track_caller]
fn send_ignore(&self, msg: T) {
self.send(msg)
.unwrap_or_else(|err| log::warn!("Failed to send message: {}", err));
}
}
impl<T: Reducible> ChannelExt<T> for ReducingSender<T> {
#[track_caller]
fn send_ignore(&self, msg: T) {
self.try_send(msg)
.unwrap_or_else(|err| log::warn!("Failed to send message: {:?}", err));
}
}
pub trait FunctionalExt: Sized {
fn apply_or<R, Y: FnOnce(Self) -> R, N: FnOnce(Self) -> R>(self, condition: bool, y: Y, n: N) -> R;
fn apply_if<E, Y: FnOnce(Self) -> Result<Self, E>>(self, condition: bool, y: Y) -> Result<Self, E> {
self.apply_or(condition, y, Ok)
}
}
impl<T: Sized> FunctionalExt for T {
fn apply_or<R, Y: FnOnce(Self) -> R, N: FnOnce(Self) -> R>(self, condition: bool, y: Y, n: N) -> R {
match condition {
true => y(self),
false => n(self)
}
}
}
/*
pub trait OptionExt<T> {
fn or_future(self, fut: impl Future<Output = Option<T>>) -> impl Future<Output = Option<T>>;
}
impl<T> OptionExt<T> for Option<T> {
fn or_future(self, fut: impl Future<Output = Option<T>>) -> impl Future<Output = Option<T>> {
async move {
match self {
Some(v) => Some(v),
None => fut.await,
}
}
}
}
*/
pub trait MutexExt {
type Guard<'a>
where
Self: 'a;
fn lock_no_poison(&self) -> Self::Guard<'_>;
}
impl<T> MutexExt for Mutex<T> {
type Guard<'a>
= MutexGuard<'a, T>
where
T: 'a;
fn lock_no_poison(&self) -> Self::Guard<'_> {
self.lock().unwrap_or_else(|err| err.into_inner())
}
}
/*
pub trait ArcExt<T> {
fn try_new_cyclic<F, E>(data_fn: F) -> std::result::Result<Arc<T>, E>
where
F: FnOnce(&Weak<T>) -> std::result::Result<T, E>;
}
impl<T> ArcExt<T> for Arc<T> {
fn try_new_cyclic<F, E>(data_fn: F) -> std::result::Result<Arc<T>, E>
where F: FnOnce(&Weak<T>) -> std::result::Result<T, E> {
// hopefully this is safe
let mut error: std::result::Result<(), E> = Ok(());
let arc = Arc::<MaybeUninit<T>>::new_cyclic(|inner| {
match data_fn(unsafe { std::mem::transmute(inner) }) {
Ok(r) => MaybeUninit::new(r),
Err(e) => {
error = Err(e);
MaybeUninit::uninit()
}
}
});
error.map(|_| {
let md_self = Arc::into_raw(arc);
unsafe { Arc::<T>::from_raw(md_self.cast()) }
})
//Ok(Arc::new_cyclic(|i| data_fn(i).unwrap_or_else(|_| panic!("Closure panic"))))
}
}
*/
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/ordered_map.rs | src/utils/ordered_map.rs | use std::fmt::{Debug, Formatter};
#[derive(Default, Clone, Eq, PartialEq)]
pub struct OrderedMap<K, V> {
items: Vec<(K, V)>
}
impl<K: PartialEq, V: SortKeyExtract> OrderedMap<K, V> {
pub const fn new() -> Self {
Self { items: Vec::new() }
}
pub fn clear(&mut self) {
self.items.clear()
}
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
let prev = self.remove(&key);
self.items.push((key, value));
self.items
.sort_by(|(_, a), (_, b)| a.sort_key().cmp(&b.sort_key()));
prev
}
pub fn get(&self, key: &K) -> Option<&V> {
self.items.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
pub fn remove(&mut self, key: &K) -> Option<V> {
if let Some(index) = self.items.iter().position(|(k, _)| k == key) {
Some(self.items.remove(index).1)
} else {
None
}
}
pub fn values(&self) -> impl Iterator<Item = &V> {
self.items.iter().map(|(_, v)| v)
}
pub fn len(&self) -> usize {
self.items.len()
}
}
impl<K: Debug, V: Debug> Debug for OrderedMap<K, V> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_map()
.entries(self.items.iter().map(|(k, v)| (k, v)))
.finish()
}
}
pub trait SortKeyExtract {
type Key: Ord;
fn sort_key(&self) -> Self::Key;
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/mod.rs | src/utils/mod.rs | pub mod elevation;
pub mod error;
pub mod extensions;
pub mod logger;
pub mod ordered_map;
pub mod panic;
pub mod string;
pub mod winrt;
#[macro_export]
macro_rules! cloned {
([$($vars:ident),+] $e:expr) => {
{
$( let $vars = $vars.clone(); )+
$e
}
};
}
#[macro_export]
macro_rules! log_assert {
($cond:expr) => {{
if !$cond {
log::warn!("Assertion failed: {}", stringify!($cond));
}
}};
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/utils/winrt.rs | src/utils/winrt.rs | use windows::core::{RuntimeName, HSTRING};
use windows_ext::UI::Xaml::Interop::{TypeKind, TypeName};
pub trait GetTypeName {
fn type_name() -> TypeName;
}
impl<T: RuntimeName> GetTypeName for T {
fn type_name() -> TypeName {
TypeName {
Name: HSTRING::from(Self::NAME),
Kind: TypeKind::Metadata
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/views/settings.rs | src/views/settings.rs | use std::sync::{Arc, Mutex};
use log::warn;
use loole::Sender;
use windows::core::{ComInterface, HSTRING};
use windows::UI::Color;
use windows::Win32::UI::Input::KeyboardAndMouse::{GetKeyState, VIRTUAL_KEY, VK_CONTROL, VK_LWIN, VK_MENU, VK_RWIN, VK_SHIFT};
use windows_ext::IXamlSourceTransparency;
use windows_ext::UI::Xaml::Media::SolidColorBrush;
use windows_ext::UI::Xaml::{ElementTheme, TextAlignment, Thickness, VerticalAlignment, Window as XamlWindow};
use windows_ext::UI::Xaml::Controls::{TextBox};
use windows_ext::UI::Xaml::Input::KeyEventHandler;
use crate::config::{autostart, Config};
use crate::ui::container::StackPanel;
use crate::ui::controls::{TextBlock, ToggleSwitch};
use crate::ui::FontWeight;
use crate::utils::elevation::relaunch_as_elevated;
use crate::utils::extensions::{ChannelExt, FunctionalExt, MutexExt};
use crate::windowing::{Window, WindowBuilder};
use crate::{cloned, CustomEvent, Result, APP_ICON};
use crate::windowing::hotkey::{KeyCombination, Modifier, ModifierSet, VirtualKey};
use crate::utils::error::{WinOptionExt};
thread_local! {
static TRANSPARENT_BACKGROUND: bool = XamlWindow::Current()
.and_then(|w| w.cast::<IXamlSourceTransparency>())
.and_then(|t| t.SetIsBackgroundTransparent(true))
.map_err(|e| warn!("Failed to make XAML island background transparent: {e}"))
.is_ok();
}
pub struct SettingsWindow {
window: Window,
mica: bool,
content: Option<StackPanel>,
background_brush: SolidColorBrush
}
impl SettingsWindow {
pub fn new(sender: Sender<CustomEvent>, config: Arc<Mutex<Config>>) -> Result<Self> {
let mut mica = TRANSPARENT_BACKGROUND.with(|t| *t);
//mica = false;
let window = WindowBuilder::default()
.with_size(900, 800)
.with_title("Rusty Twinkle Tray Settings")
.with_icon_resource(APP_ICON)
.with_close_handler(cloned!([sender] move || sender
.send(CustomEvent::CloseSettings)
.unwrap_or_default()))
.build()?;
if mica {
mica &= window
.apply_mica_backdrop()
.map_err(|e| warn!("Failed to set DWM system backdrop attribute: {e}"))
.is_ok();
}
if mica {
window
.make_titlebar_transparent()
.unwrap_or_else(|e| warn!("Failed to set DWM caption color attribute: {e}"));
}
let mut result = Self {
window,
mica,
content: None,
background_brush: SolidColorBrush::new()?
};
result.build_gui(sender, config)?;
result
.sync_theme()
.unwrap_or_else(|e| warn!("Failed to sync theme: {e}"));
result.window.set_visible(true);
Ok(result)
}
pub fn focus(&self) {
self.window.focus();
}
pub fn sync_theme(&self) -> Result<()> {
let theme = self
.content
.as_ref()
.and_then(|c| c.theme().ok())
.filter(|t| *t != ElementTheme::Default)
.unwrap_or(ElementTheme::Light);
let (color, dark) = match theme {
ElementTheme::Dark => (Color { R: 45, G: 45, B: 45, A: 255 }, true),
ElementTheme::Light => (
Color {
R: 251,
G: 251,
B: 251,
A: 255
},
false
),
_ => unreachable!()
};
self.background_brush.SetColor(color)?;
if self.mica {
self.window.enable_immersive_dark_mode(dark)?;
}
Ok(())
}
fn build_gui(&mut self, sender: Sender<CustomEvent>, config: Arc<Mutex<Config>>) -> Result<()> {
const TOGGLE_WIDTH: f64 = 100.0;
let border_brush = SolidColorBrush::CreateInstanceWithColor(Color { R: 0, G: 0, B: 0, A: 30 })?;
let section = |title| {
StackPanel::vertical()?
.apply_if(self.mica, |p| p.with_win11_style(&self.background_brush, &border_brush))?
.with_padding(10.0)?
.with_spacing(7.0)?
.with_child(
&TextBlock::with_text(title)?
.with_font_size(24.0)?
.with_font_weight(FontWeight::SemiLight)?
)
};
let auto_start_priority = config.lock_no_poison().use_prioritized_autostart;
let auto_start_enabled = autostart::is_enabled(!auto_start_priority);
let autostart_priority_toggle = ToggleSwitch::new()?
.with_width(TOGGLE_WIDTH)?
.with_state(auto_start_priority)?
.with_enabled(!auto_start_enabled)?
.with_toggled_handler(cloned!([config] move |ts | {
let mut config = config.lock_no_poison();
config.use_prioritized_autostart = ts.get_state()?;
config.dirty = true;
Ok(())
}))?;
let hwnd = self.window.hwnd();
let auto_start_toggle = ToggleSwitch::new()?
.with_width(TOGGLE_WIDTH)?
.with_state(auto_start_enabled)?
.with_toggled_handler(cloned!([config, autostart_priority_toggle] move |ts| {
let user = !config.lock_no_poison().use_prioritized_autostart;
match user {
true => autostart::set_enabled(true, ts.get_state()?)
.unwrap_or_else(|e| warn!("Failed to set autostart: {e}")),
false => relaunch_as_elevated(hwnd, match ts.get_state()? {
true => "--config-autostart enable",
false => "--config-autostart disable"
}).unwrap_or_else(|e| warn!("Failed to relaunch as elevated: {e}"))
}
let enabled = autostart::is_enabled(user);
ts.set_state(enabled)?;
autostart_priority_toggle.set_enabled(!enabled)?;
Ok(())
}))?;
let enable_icon_scroll = ToggleSwitch::new()?
.with_width(TOGGLE_WIDTH)?
.with_state(config.lock_no_poison().icon_scoll_enabled)?
.with_toggled_handler(cloned!([config, sender] move |ts | {
let mut config = config.lock_no_poison();
config.icon_scoll_enabled = ts.get_state()?;
config.dirty = true;
sender.send_ignore(CustomEvent::ReinitializeControls);
Ok(())
}))?;
let hotkey_increase = make_hotkey_editor(sender.clone(), config.clone(), |c| &mut c.brightness_increase_hotkey)?;
let hotkey_decrease = make_hotkey_editor(sender.clone(), config.clone(), |c| &mut c.brightness_decrease_hotkey)?;
let hotkey_toggle = ToggleSwitch::new()?
.with_width(TOGGLE_WIDTH)?
.with_state(config.lock_no_poison().hotkeys_enabled)?
.with_toggled_handler(cloned!([config, sender, hotkey_increase, hotkey_decrease] move |ts| {
config.lock_no_poison().hotkeys_enabled = ts.get_state()?;
config.lock_no_poison().dirty = true;
sender.send_ignore(CustomEvent::ReinitializeControls);
hotkey_increase.SetIsEnabled(ts.get_state()?)?;
hotkey_decrease.SetIsEnabled(ts.get_state()?)?;
Ok(())
}))?;
let general = section("General")?
.with_child(
&StackPanel::horizontal()?
.with_child(&auto_start_toggle)?
.with_child(&TextBlock::with_text("Automatically run on startup")?.with_vertical_alignment(VerticalAlignment::Center)?)?
)?
.with_child(
&StackPanel::horizontal()?
.with_child(
&ToggleSwitch::new()?
.with_width(TOGGLE_WIDTH)?
.with_state(config.lock_no_poison().restore_from_config)?
.with_toggled_handler(cloned!([config] move |state| {
let mut config = config.lock_no_poison();
config.restore_from_config = state.get_state()?;
config.dirty = true;
Ok(())
}))?
)?
.with_child(
&TextBlock::with_text("Automatically restore saved brightness")?.with_vertical_alignment(VerticalAlignment::Center)?
)?
)?;
let controls = section("Controls")?
.with_child(
&StackPanel::horizontal()?
.with_child(&enable_icon_scroll)?
.with_child(&TextBlock::with_text("Adjust the brightness of all displays by scrolling over the tray icon")?
.with_vertical_alignment(VerticalAlignment::Center)?)?
)?
.with_child(
&StackPanel::vertical()?
.with_spacing(5.0)?
.with_child(
&StackPanel::horizontal()?
.with_child(&hotkey_toggle)?
.with_child(&TextBlock::with_text("Adjust the brightness of all displays by pressing the following hotkeys:")?
.with_vertical_alignment(VerticalAlignment::Center)?)?
)?
.with_child(
&StackPanel::horizontal()?
.with_child(&hotkey_increase)?
.with_child(&TextBlock::with_text("Increase brightness")?
.with_vertical_alignment(VerticalAlignment::Center)?)?
)?
.with_child(
&StackPanel::horizontal()?
.with_child(&hotkey_decrease)?
.with_child(&TextBlock::with_text("Decrease brightness")?
.with_vertical_alignment(VerticalAlignment::Center)?)?
)?
)?;
let advanced = section("Advanced")?.with_child(
&StackPanel::horizontal()?
.with_child(&autostart_priority_toggle)?
.with_child(
&TextBlock::with_text("Use higher autostart priority (requires admin permissions)")?
.with_vertical_alignment(VerticalAlignment::Center)?
)?
)?;
let main = StackPanel::vertical()?
.apply_if(!self.mica, |p| p.with_background(&self.background_brush))?
.with_padding(10.0)?
.with_spacing(7.0)?
.with_child(&general)?
.with_child(&controls)?
.with_child(&advanced)?;
self.window.set_content(&main)?;
self.content = Some(main);
Ok(())
}
}
fn make_hotkey_editor(sender: Sender<CustomEvent>, config: Arc<Mutex<Config>>, mapper: fn(&mut Config) -> &mut KeyCombination) -> Result<TextBox> {
let hotkey = TextBox::new()?;
hotkey.SetIsReadOnly(true)?;
hotkey.SetText(&HSTRING::from(format!("{}", mapper(&mut config.lock_no_poison()).display(true)).to_uppercase()))?;
hotkey.SetIsEnabled(config.lock_no_poison().hotkeys_enabled)?;
hotkey.SetTextAlignment(TextAlignment::Center)?;
hotkey.SetWidth(200.0)?;
hotkey.SetMargin(Thickness {
Left: 30.0,
Top: 0.0,
Right: 20.0,
Bottom: 0.0,
})?;
hotkey.PreviewKeyDown(&KeyEventHandler::new(cloned!([sender, config] move |this, args| {
let args = args.some()?;
args.SetHandled(true)?;
let key = VirtualKey::from(args.Key()?);
if key.is_modifier() || key == VirtualKey::ESCAPE {
return Ok(());
}
let modifiers = get_modifier_state();
let key_combo = KeyCombination { modifiers, key };
this
.some()?
.cast::<TextBox>()?
.SetText(&HSTRING::from(format!("{}", key_combo.display(true)).to_uppercase()))?;
let mut config = config.lock_no_poison();
*mapper(&mut config) = key_combo;
config.dirty = true;
sender.send_ignore(CustomEvent::ReinitializeControls);
Ok(())
})))?;
Ok(hotkey)
}
trait StackPanelExt: Sized {
fn with_win11_style(self, background: &SolidColorBrush, border: &SolidColorBrush) -> Result<Self>;
}
impl StackPanelExt for StackPanel {
fn with_win11_style(self, background: &SolidColorBrush, border: &SolidColorBrush) -> Result<Self> {
self.with_background(background)?
.with_border_thickness(1.0)?
.with_border_brush(border)?
.with_corner_radius(5.0)
}
}
fn get_modifier_state() -> ModifierSet {
fn is_key_down(key: VIRTUAL_KEY) -> bool {
unsafe { GetKeyState(key.0 as i32) & (1 << 15) != 0 }
}
const MODIFIER_KEYS: &[(Modifier, &[VIRTUAL_KEY])] = &[
(Modifier::Shift, &[VK_SHIFT]),
(Modifier::Ctrl, &[VK_CONTROL]),
(Modifier::Alt, &[VK_MENU]),
(Modifier::Win, &[VK_LWIN, VK_RWIN]),
];
MODIFIER_KEYS
.into_iter()
.copied()
.filter_map(|(m, keys)| keys
.iter()
.copied()
.any(is_key_down)
.then_some(m))
.collect()
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/views/flyout.rs | src/views/flyout.rs | use log::{debug, warn};
use loole::Sender;
use windows::core::{h, IInspectable};
use windows::Foundation::Size;
use windows::UI::Color;
use windows_ext::UI::Xaml::Controls::Control;
use windows_ext::UI::Xaml::Controls::Primitives::FlyoutPlacementMode;
use windows_ext::UI::Xaml::Media::{AcrylicBackgroundSource, AcrylicBrush, SolidColorBrush};
use windows_ext::UI::Xaml::{TextAlignment, VerticalAlignment};
use crate::backend::MonitorControllerProxy;
use crate::monitors::MonitorPath;
use crate::theme::ColorSet;
use crate::ui::container::{Grid, GridSize, StackPanel};
use crate::ui::controls::{AppBarButton, Flyout, FontIcon, Slider, TextBlock};
use crate::ui::FontWeight;
use crate::utils::extensions::ChannelExt;
use crate::utils::ordered_map::{OrderedMap, SortKeyExtract};
use crate::windowing::{Window, WindowBuilder, WindowLevel};
use crate::{cloned, hformat, log_assert, CustomEvent, Result};
pub struct ProxyWindow {
window: Window,
content: TextBlock
}
impl ProxyWindow {
pub fn new() -> Result<Self> {
let window = WindowBuilder::default()
.with_position(0, 0)
.with_size(10, 10)
.with_hidden(true)
.build()?;
let content = TextBlock::with_text("This should be invisible!")?;
window.set_content(&content)?;
Ok(Self { window, content })
}
pub fn activate(&self) -> bool {
self.window
.set_window_pos(Some(WindowLevel::AlwaysOnTop), Some((0, 0)), None, Some(true));
self.window.focus();
self.window.set_foreground()
}
pub fn deactivate(&self) {
self.window.set_window_pos(None, None, None, Some(false))
}
pub fn dpi(&self) -> f32 {
self.window.dpi()
}
}
pub struct BrightnessFlyout {
flyout: Flyout,
background: AcrylicBrush,
container: StackPanel,
monitor_panel: StackPanel,
monitor_controls: OrderedMap<MonitorPath, MonitorEntry>
}
impl BrightnessFlyout {
const WIDTH: f64 = 400.0;
pub fn new(sender: Sender<CustomEvent>, colors: &ColorSet) -> Result<Self> {
let settings = AppBarButton::new()?
.with_icon(&FontIcon::new('\u{E713}')?)?
.with_label("Settings")?
//.with_enabled(false)?;
.with_click_handler(cloned!([sender] move|| {
sender
.send(CustomEvent::OpenSettings)
.unwrap_or_else(|_| log::warn!("Failed to send settings event"));
Ok(())
}))?;
let refresh = AppBarButton::new()?
.with_icon(&FontIcon::new('\u{E72C}')?)?
.with_label("Refresh")?
.with_click_handler(cloned!([sender] move || {
sender
.send(CustomEvent::Refresh)
.unwrap_or_else(|_| log::warn!("Failed to send refresh event"));
Ok(())
}))?;
// Create a new stack panel for the bottom bar
let bottom_bar = Grid::new()?
//.with_padding(20.0)?
.with_column_widths([GridSize::Fraction(1.0), GridSize::Auto])?
.with_background(&SolidColorBrush::CreateInstanceWithColor(Color { R: 0, G: 0, B: 0, A: 70 })?)?
.with_child(
&TextBlock::with_text("Adjust Brightness")?
.with_font_size(15.0)?
.with_vertical_alignment(VerticalAlignment::Center)?
.with_padding((20.0, 0.0, 0.0, 0.0))?,
0,
0
)?
.with_child(
&StackPanel::horizontal()?
.with_child(&refresh)?
.with_child(&settings)?,
0,
1
)?;
let monitor_panel = StackPanel::vertical()?
.with_spacing(20.0)?
.with_padding((20.0, 14.0))?;
let container = StackPanel::vertical()?
.with_theme(colors.theme)?
.with_width(Self::WIDTH)?
.with_child(
&Grid::new()?
.with_row_heights([GridSize::Auto, GridSize::Fraction(1.0), GridSize::Auto])?
.with_child(&monitor_panel, 0, 0)?
.with_child(&bottom_bar, 2, 0)?
)?;
let background = {
let brush = AcrylicBrush::new()?;
brush.SetBackgroundSource(AcrylicBackgroundSource::HostBackdrop)?;
brush.SetFallbackColor(colors.fallback)?;
brush.SetTintColor(colors.tint)?;
brush.SetTintOpacity(colors.opacity)?;
brush
};
let flyout = Flyout::new(&container)?
.with_style(|style| {
style
.with_setter(&Control::BackgroundProperty()?, &background)?
.with_setter(&Control::CornerRadiusProperty()?, &IInspectable::try_from(h!("10.0"))?)?
.with_setter(&Control::PaddingProperty()?, &IInspectable::try_from(h!("0.0"))?)
})?
.with_closed_handler(cloned!([sender] move || {
sender.filter_send_ignore(Some(CustomEvent::FocusLost));
Ok(())
}))?;
Ok(Self {
flyout,
background,
container,
monitor_panel,
monitor_controls: OrderedMap::new()
})
}
pub fn update_theme(&self, colors: &ColorSet) -> Result<()> {
self.container.set_theme(colors.theme)?;
self.background.SetFallbackColor(colors.fallback)?;
self.background.SetTintColor(colors.tint)?;
self.background.SetTintOpacity(colors.opacity)?;
Ok(())
}
pub fn is_open(&self) -> bool {
self.flyout
.is_open()
.map_err(|e| warn!("Failed to check if flyout is open: {}", e))
.unwrap_or(false)
}
pub fn close(&self) {
self.flyout
.close()
.unwrap_or_else(|e| warn!("Failed to close flyout: {}", e));
}
pub fn show(&self, proxy_window: &ProxyWindow, x: f32, y: f32) {
self.flyout
.show_at(&proxy_window.content, x, y, FlyoutPlacementMode::LeftEdgeAlignedBottom)
.unwrap_or_else(|e| warn!("Failed to show flyout: {}", e));
}
pub fn size(&self) -> Size {
self.container.measure().unwrap_or_else(|e| {
debug!("Failed to get measured size of flyout: {}", e);
// Make a guess
Size {
Width: Self::WIDTH as f32,
Height: 62.0 + 86.0 * self.monitor_controls.len() as f32
}
})
}
fn repopulate_monitor_list(&self) -> Result<()> {
self.monitor_panel.clear_children()?;
for monitor in self.monitor_controls.values() {
self.monitor_panel.add_child(monitor.ui())?;
}
Ok(())
}
pub fn register_monitor(&mut self, name: String, path: MonitorPath, position: i32, proxy: MonitorControllerProxy) -> Result<()> {
log_assert!(self
.monitor_controls
.insert(path.clone(), MonitorEntry::create(name, path, position, proxy)?)
.is_none());
self.repopulate_monitor_list()?;
Ok(())
}
pub fn unregister_monitor(&mut self, path: &MonitorPath) -> Result<()> {
log_assert!(self.monitor_controls.remove(path).is_some());
self.repopulate_monitor_list()?;
Ok(())
}
pub fn clear_monitors(&mut self) -> Result<()> {
self.monitor_controls.clear();
self.repopulate_monitor_list()?;
Ok(())
}
pub fn update_brightness(&self, path: MonitorPath, new_brightness: u32) -> Result<()> {
match self.monitor_controls.get(&path) {
None => warn!("Monitor is not registered: {:?}", path),
Some(entry) => entry.set_brightness(new_brightness)?
}
Ok(())
}
pub fn change_brightness(&self, new_brightness: i32) -> Result<()> {
for entry in self.monitor_controls.values() {
entry.change_brightness(new_brightness)?;
}
Ok(())
}
}
struct MonitorEntry {
position: i32,
ui: StackPanel,
slider: Slider
}
impl MonitorEntry {
pub fn create(name: String, path: MonitorPath, position: i32, proxy: MonitorControllerProxy) -> Result<Self> {
let label = TextBlock::new()?
.with_vertical_alignment(VerticalAlignment::Center)?
.with_text_alignment(TextAlignment::Center)?
.with_font_size(20.0)?
.with_font_weight(FontWeight::Medium)?;
let slider = Slider::new()?
.with_vertical_alignment(VerticalAlignment::Center)?
.with_value(0.0)?
.with_mouse_scrollable()?
.with_value_changed_handler(cloned!([label] move |args| {
let new = args.NewValue()? as u32;
label.set_text(hformat!("{}", new))?;
proxy.set_brightness(path.clone(), new);
Ok(())
}))?;
label.set_text(hformat!("{}", slider.get_value()?))?;
let ui = StackPanel::vertical()?
.with_spacing(4.0)?
.with_child(
&StackPanel::horizontal()?
.with_spacing(8.0)?
.with_child(&FontIcon::new('\u{E7f4}')?.with_font_weight(FontWeight::Medium)?)?
.with_child(&TextBlock::with_text(&name)?.with_font_size(20.0)?)?
)?
.with_child(
&Grid::new()?
.with_column_widths([GridSize::Fraction(1.0), GridSize::Pixel(40.0)])?
.with_column_spacing(8.0)?
.with_child(&slider, 0, 0)?
.with_child(&label, 0, 1)?
)?;
Ok(Self { position, ui, slider })
}
pub fn set_brightness(&self, value: u32) -> Result<()> {
self.slider.set_value(value as f64)
}
pub fn change_brightness(&self, value: i32) -> Result<()> {
self.slider.set_value(self.slider.get_value()? + value as f64)
}
pub fn ui(&self) -> &StackPanel {
&self.ui
}
}
impl SortKeyExtract for MonitorEntry {
type Key = i32;
fn sort_key(&self) -> i32 {
self.position
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/views/mod.rs | src/views/mod.rs | mod flyout;
mod settings;
pub use flyout::{BrightnessFlyout, ProxyWindow};
pub use settings::SettingsWindow;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/ui/controls.rs | src/ui/controls.rs | use windows::core::{ComInterface, TryIntoParam, HSTRING};
use windows::Foundation::{EventHandler, IReference, Point, PropertyValue};
use windows::Win32::UI::WindowsAndMessaging::WHEEL_DELTA;
use windows_ext::UI::Xaml::Controls::Primitives::{FlyoutShowOptions, RangeBaseValueChangedEventArgs, RangeBaseValueChangedEventHandler};
use windows_ext::UI::Xaml::Controls::{FlyoutPresenter, IconElement};
use windows_ext::UI::Xaml::Input::PointerEventHandler;
use windows_ext::UI::Xaml::{DependencyObject, RoutedEventHandler, TextWrapping, UIElement};
use super::{FontWeight, Padding, TextAlignment, VerticalAlignment};
use crate::ui::style::Style;
use crate::ui::NewType;
use crate::utils::error::{TracedResultEx, WinOptionExt};
use crate::Result;
new_type!(Slider, windows_ext::UI::Xaml::Controls::Slider);
impl Slider {
pub fn new() -> Result<Self> {
let slider = <Self as NewType>::Inner::new()?;
Ok(Self(slider))
}
pub fn with_value(self, value: f64) -> Result<Self> {
self.0.SetValue2(value)?;
Ok(self)
}
pub fn with_vertical_alignment(self, alignment: VerticalAlignment) -> Result<Self> {
self.0.SetVerticalAlignment(alignment)?;
Ok(self)
}
pub fn with_mouse_scrollable(self) -> Result<Self> {
self.0
.PointerWheelChanged(&PointerEventHandler::new(move |sender, args| {
let args = args.some()?;
args.SetHandled(true)?;
let delta = args
.GetCurrentPoint(None)?
.Properties()?
.MouseWheelDelta()?
/ WHEEL_DELTA as i32;
let slider = sender.some()?.cast::<Self>()?;
slider
.set_value(slider.get_value().to_win_result()? + delta as f64)
.to_win_result()?;
Ok(())
}))?;
Ok(self)
}
pub fn with_value_changed_handler<F>(self, mut handler: F) -> Result<Self>
where
F: FnMut(/*Option<&::windows_core::IInspectable>, */ &RangeBaseValueChangedEventArgs) -> Result<()> + Send + 'static
{
self.0
.ValueChanged(&RangeBaseValueChangedEventHandler::new(move |_sender, args| {
handler(args.some()?).to_win_result()
}))?;
Ok(self)
}
pub fn get_value(&self) -> Result<f64> {
Ok(self.0.Value()?)
}
pub fn set_value(&self, value: f64) -> Result<()> {
Ok(self.0.SetValue2(value)?)
}
}
new_type!(TextBlock, windows_ext::UI::Xaml::Controls::TextBlock);
impl TextBlock {
pub fn new() -> Result<Self> {
Ok(Self(<Self as NewType>::Inner::new()?))
}
pub fn with_text<T: Into<HSTRING>>(text: T) -> Result<Self> {
let block = Self::new()?;
block.0.SetText(&text.into())?;
block.0.SetTextWrapping(TextWrapping::Wrap)?;
Ok(block)
}
pub fn with_vertical_alignment(self, alignment: VerticalAlignment) -> Result<Self> {
self.0.SetVerticalAlignment(alignment)?;
Ok(self)
}
pub fn with_text_alignment(self, alignment: TextAlignment) -> Result<Self> {
self.0.SetTextAlignment(alignment)?;
Ok(self)
}
pub fn with_padding<P: Into<Padding>>(self, padding: P) -> Result<Self> {
self.0.SetPadding(padding.into().into())?;
Ok(self)
}
pub fn with_font_size(self, size: f64) -> Result<Self> {
self.0.SetFontSize(size)?;
Ok(self)
}
pub fn with_font_weight<W: Into<FontWeight>>(self, weight: W) -> Result<Self> {
self.0.SetFontWeight(weight.into().into())?;
Ok(self)
}
pub fn set_text<T: Into<HSTRING>>(&self, text: T) -> Result<()> {
Ok(self.0.SetText(&text.into())?)
}
}
new_type!(FontIcon, windows_ext::UI::Xaml::Controls::FontIcon);
impl windows::core::CanTryInto<IconElement> for FontIcon {
const CAN_INTO: bool = <windows_ext::UI::Xaml::Controls::FontIcon as windows::core::CanTryInto<IconElement>>::CAN_INTO;
}
impl FontIcon {
pub fn new(icon: char) -> Result<Self> {
let mut buffer = [0u16; 2];
let font_icon = <Self as NewType>::Inner::new()?;
font_icon.SetGlyph(&HSTRING::from_wide(icon.encode_utf16(&mut buffer))?)?;
Ok(Self(font_icon))
}
//pub fn with_font_size(self, size: f64) -> Result<Self> {
// self.0.SetFontSize(size)?;
// Ok(self)
//}
pub fn with_font_weight<W: Into<FontWeight>>(self, weight: W) -> Result<Self> {
self.0.SetFontWeight(weight.into().into())?;
Ok(self)
}
pub fn with_vertical_alignment(self, alignment: VerticalAlignment) -> Result<Self> {
self.0.SetVerticalAlignment(alignment)?;
Ok(self)
}
}
new_type!(AppBarButton, windows_ext::UI::Xaml::Controls::AppBarButton);
impl AppBarButton {
pub fn new() -> Result<Self> {
let button = <Self as NewType>::Inner::new()?;
Ok(Self(button))
}
pub fn with_label<T: Into<HSTRING>>(self, text: T) -> Result<Self> {
self.0.SetLabel(&text.into())?;
Ok(self)
}
pub fn with_icon<T: TryIntoParam<IconElement>>(self, icon: T) -> Result<Self> {
self.0.SetIcon(icon)?;
Ok(self)
}
pub fn with_enabled(self, enabled: bool) -> Result<Self> {
self.0.SetIsEnabled(enabled)?;
Ok(self)
}
pub fn with_click_handler<F>(self, mut handler: F) -> Result<Self>
where
F: FnMut(/*Option<&::windows_core::IInspectable>, &RoutedEventArgs*/) -> Result<()> + Send + 'static
{
self.0
.Click(&RoutedEventHandler::new(move |_sender, _args| handler().to_win_result()))?;
Ok(self)
}
}
new_type!(ToggleSwitch, windows_ext::UI::Xaml::Controls::ToggleSwitch);
impl ToggleSwitch {
pub fn new() -> Result<Self> {
let switch = <Self as NewType>::Inner::new()?;
Ok(Self(switch))
}
pub fn with_state(self, on: bool) -> Result<Self> {
self.0.SetIsOn(on)?;
Ok(self)
}
pub fn with_enabled(self, enabled: bool) -> Result<Self> {
self.0.SetIsEnabled(enabled)?;
Ok(self)
}
pub fn with_toggled_handler<F>(self, mut handler: F) -> Result<Self>
where
F: FnMut(&Self) -> Result<()> + Send + 'static
{
self.0.Toggled(&RoutedEventHandler::new(move |sender, _| {
let state = sender.some()?.cast::<Self>()?;
handler(&state).to_win_result()
}))?;
Ok(self)
}
pub fn with_width(self, width: f64) -> Result<Self> {
self.0.SetWidth(width)?;
Ok(self)
}
pub fn get_state(&self) -> Result<bool> {
Ok(self.0.IsOn()?)
}
pub fn set_state(&self, on: bool) -> Result<()> {
Ok(self.0.SetIsOn(on)?)
}
pub fn set_enabled(&self, enabled: bool) -> Result<()> {
Ok(self.0.SetIsEnabled(enabled)?)
}
}
pub use windows_ext::UI::Xaml::Controls::Primitives::FlyoutPlacementMode;
new_type!(Flyout, windows_ext::UI::Xaml::Controls::Flyout, no_ui);
impl Flyout {
pub fn new<T: TryIntoParam<UIElement>>(content: T) -> Result<Self> {
let flyout = <Self as NewType>::Inner::new()?;
flyout.SetContent(content)?;
flyout.SetShouldConstrainToRootBounds(false)?;
flyout.SetAreOpenCloseAnimationsEnabled(true)?;
Ok(Self(flyout))
}
pub fn with_closed_handler<F>(self, mut handler: F) -> Result<Self>
where
F: FnMut() -> Result<()> + Send + 'static
{
self.0
.Closed(&EventHandler::new(move |_, _| handler().to_win_result()))?;
Ok(self)
}
pub fn with_style<F: FnOnce(Style) -> Result<Style>>(self, f: F) -> Result<Self> {
let style = f(Style::new::<FlyoutPresenter>()?)?;
self.0.SetFlyoutPresenterStyle(style.as_inner())?;
Ok(self)
}
pub fn show_at<E>(&self, base: E, x: f32, y: f32, mode: FlyoutPlacementMode) -> Result<()>
where
E: TryIntoParam<DependencyObject>
{
let options = FlyoutShowOptions::new()?;
let pt = Point { X: x, Y: y };
options.SetPosition(&PropertyValue::CreatePoint(pt)?.cast::<IReference<Point>>()?)?;
options.SetPlacement(mode)?;
self.0.ShowAt2(base, &options)?;
Ok(())
}
pub fn is_open(&self) -> Result<bool> {
Ok(self.0.IsOpen()?)
}
pub fn close(&self) -> Result<()> {
Ok(self.0.Hide()?)
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/ui/container.rs | src/ui/container.rs | use windows::core::TryIntoParam;
use windows::Foundation::Size;
use windows_ext::UI::Xaml::Controls::{ColumnDefinition, Orientation, RowDefinition};
use windows_ext::UI::Xaml::Media::Brush;
use windows_ext::UI::Xaml::{CornerRadius, FrameworkElement, GridUnitType, UIElement};
use crate::ui::{ElementTheme, NewType, Padding};
use crate::utils::error::Result;
new_type!(StackPanel, windows_ext::UI::Xaml::Controls::StackPanel);
impl StackPanel {
pub fn vertical() -> Result<Self> {
let inner = <Self as NewType>::Inner::new()?;
inner.SetOrientation(Orientation::Vertical)?;
Ok(Self(inner))
}
pub fn horizontal() -> Result<Self> {
let inner = <Self as NewType>::Inner::new()?;
inner.SetOrientation(Orientation::Horizontal)?;
Ok(Self(inner))
}
pub fn with_spacing(self, spacing: f64) -> Result<Self> {
self.0.SetSpacing(spacing)?;
Ok(self)
}
pub fn with_padding<P: Into<Padding>>(self, padding: P) -> Result<Self> {
self.0.SetPadding(padding.into().into())?;
Ok(self)
}
pub fn with_border_thickness<P: Into<Padding>>(self, thickness: P) -> Result<Self> {
self.0.SetBorderThickness(thickness.into().into())?;
Ok(self)
}
pub fn with_corner_radius(self, radius: f64) -> Result<Self> {
self.0.SetCornerRadius(CornerRadius {
TopLeft: radius,
TopRight: radius,
BottomRight: radius,
BottomLeft: radius
})?;
Ok(self)
}
pub fn add_child<T: TryIntoParam<UIElement>>(&self, child: T) -> Result<()> {
self.0.Children()?.Append(child)?;
Ok(())
}
pub fn clear_children(&self) -> Result<()> {
self.0.Children()?.Clear()?;
Ok(())
}
pub fn with_child<T: TryIntoParam<UIElement>>(self, child: T) -> Result<Self> {
self.0.Children()?.Append(child)?;
Ok(self)
}
pub fn with_theme(self, theme: ElementTheme) -> Result<Self> {
self.0.SetRequestedTheme(theme)?;
Ok(self)
}
pub fn with_width(self, width: f64) -> Result<Self> {
self.0.SetWidth(width)?;
Ok(self)
}
pub fn set_theme(&self, theme: ElementTheme) -> Result<()> {
self.0.SetRequestedTheme(theme)?;
Ok(())
}
pub fn theme(&self) -> Result<ElementTheme> {
Ok(self.0.ActualTheme()?)
}
pub fn with_background<B: TryIntoParam<Brush>>(self, brush: B) -> Result<Self> {
self.0.SetBackground(brush)?;
Ok(self)
}
pub fn with_border_brush<B: TryIntoParam<Brush>>(self, brush: B) -> Result<Self> {
self.0.SetBorderBrush(brush)?;
Ok(self)
}
//pub fn with_children<T: TryIntoParam<UIElement>, I: IntoIterator<Item=T>>(mut self, children: I) -> Result<Self> {
// for child in children {
// self.add_child(child)?;
// }
// Ok(self)
//}
pub fn get_actual_height(&self) -> Result<f64> {
Ok(self.0.ActualHeight()?)
}
pub fn get_actual_width(&self) -> Result<f64> {
Ok(self.0.ActualWidth()?)
}
pub fn measure(&self) -> Result<Size> {
self.0.Measure(Size {
Width: f32::INFINITY,
Height: f32::INFINITY
})?;
let s = self.0.DesiredSize()?;
Ok(s)
}
}
pub enum GridSize {
Auto,
Pixel(f64),
Fraction(f64)
}
impl From<GridSize> for windows_ext::UI::Xaml::GridLength {
fn from(value: GridSize) -> Self {
Self {
Value: match value {
GridSize::Auto => 1.0,
GridSize::Pixel(v) => v,
GridSize::Fraction(v) => v
},
GridUnitType: match value {
GridSize::Auto => GridUnitType::Auto,
GridSize::Pixel(_) => GridUnitType::Pixel,
GridSize::Fraction(_) => GridUnitType::Star
}
}
}
}
new_type!(Grid, windows_ext::UI::Xaml::Controls::Grid);
impl Grid {
pub fn new() -> Result<Self> {
Ok(Self(<Self as NewType>::Inner::new()?))
}
pub fn with_column_widths<I: IntoIterator<Item = GridSize>>(self, sizes: I) -> Result<Self> {
let definitions = self.0.ColumnDefinitions()?;
definitions.Clear()?;
for size in sizes {
definitions.Append(&{
let def = ColumnDefinition::new()?;
def.SetWidth(size.into())?;
def
})?;
}
Ok(self)
}
pub fn with_row_heights<I: IntoIterator<Item = GridSize>>(self, sizes: I) -> Result<Self> {
let definitions = self.0.RowDefinitions()?;
definitions.Clear()?;
for size in sizes {
definitions.Append(&{
let def = RowDefinition::new()?;
def.SetHeight(size.into())?;
def
})?;
}
Ok(self)
}
pub fn with_column_spacing(self, spacing: f64) -> Result<Self> {
self.0.SetColumnSpacing(spacing)?;
Ok(self)
}
pub fn with_padding<P: Into<Padding>>(self, padding: P) -> Result<Self> {
self.0.SetPadding(padding.into().into())?;
Ok(self)
}
pub fn with_child<T: TryIntoParam<UIElement> + TryIntoParam<FrameworkElement> + Copy>(self, child: T, row: i32, column: i32) -> Result<Self> {
<Self as NewType>::Inner::SetColumn(child, column)?;
<Self as NewType>::Inner::SetRow(child, row)?;
self.0.Children()?.Append(child)?;
Ok(self)
}
pub fn with_background<B: TryIntoParam<Brush>>(self, brush: B) -> Result<Self> {
self.0.SetBackground(brush)?;
Ok(self)
}
pub fn with_theme(self, theme: ElementTheme) -> Result<Self> {
self.0.SetRequestedTheme(theme)?;
Ok(self)
}
pub fn set_theme(&self, theme: ElementTheme) -> Result<()> {
self.0.SetRequestedTheme(theme)?;
Ok(())
}
pub fn get_actual_height(&self) -> Result<f64> {
Ok(self.0.ActualHeight()?)
}
pub fn get_actual_width(&self) -> Result<f64> {
Ok(self.0.ActualWidth()?)
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/src/ui/mod.rs | src/ui/mod.rs | #![allow(dead_code)]
pub use windows_ext::UI::Xaml::{ElementTheme, TextAlignment, VerticalAlignment};
#[macro_export]
macro_rules! new_type {
($name:ident, $orig:ty, no_ui) => {
#[derive(Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct $name($orig);
unsafe impl windows::core::ComInterface for $name {
const IID: windows::core::GUID = <$orig as windows::core::ComInterface>::IID;
}
unsafe impl windows::core::Interface for $name {
type Vtable = <$orig as windows::core::Interface>::Vtable;
}
impl windows::core::RuntimeType for $name {
const SIGNATURE: windows::core::imp::ConstBuffer = <$orig as windows::core::RuntimeType>::SIGNATURE;
}
impl $crate::ui::NewType for $name {
type Inner = $orig;
fn as_inner(&self) -> &Self::Inner {
&self.0
}
}
impl windows::core::RuntimeName for $name {
const NAME: &'static str = <$orig as windows::core::RuntimeName>::NAME;
}
impl std::fmt::Debug for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
<$orig as std::fmt::Debug>::fmt(&self.0, f)
}
}
impl windows::core::CanTryInto<windows_ext::UI::Xaml::DependencyObject> for $name {
const CAN_INTO: bool = <$orig as windows::core::CanTryInto<windows_ext::UI::Xaml::DependencyObject>>::CAN_INTO;
}
};
($name:ident, $orig:ty) => {
new_type!($name, $orig, no_ui);
impl windows::core::CanTryInto<windows_ext::UI::Xaml::UIElement> for $name {
const CAN_INTO: bool = <$orig as windows::core::CanTryInto<windows_ext::UI::Xaml::UIElement>>::CAN_INTO;
}
impl windows::core::CanTryInto<windows_ext::UI::Xaml::FrameworkElement> for $name {
const CAN_INTO: bool = <$orig as windows::core::CanTryInto<windows_ext::UI::Xaml::FrameworkElement>>::CAN_INTO;
}
};
}
pub mod container;
pub mod controls;
pub trait NewType {
type Inner;
fn as_inner(&self) -> &Self::Inner;
fn apply<F, E>(self, f: F) -> Result<Self, E>
where
F: FnOnce(&Self::Inner) -> Result<(), E>,
Self: Sized
{
f(self.as_inner())?;
Ok(self)
}
}
//pub use dispatcher::DispatchTarget;
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Padding {
pub left: f64,
pub top: f64,
pub right: f64,
pub bottom: f64
}
impl From<f64> for Padding {
fn from(value: f64) -> Self {
Self {
left: value,
top: value,
right: value,
bottom: value
}
}
}
impl From<(f64, f64)> for Padding {
fn from((horizontal, vertical): (f64, f64)) -> Self {
Self {
left: horizontal,
top: vertical,
right: horizontal,
bottom: vertical
}
}
}
impl From<(f64, f64, f64, f64)> for Padding {
fn from((l, t, r, b): (f64, f64, f64, f64)) -> Self {
Self {
left: l,
top: t,
right: r,
bottom: b
}
}
}
impl From<Padding> for windows_ext::UI::Xaml::Thickness {
fn from(value: Padding) -> Self {
Self {
Left: value.left,
Top: value.top,
Right: value.right,
Bottom: value.bottom
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct FontWeight(pub u16);
#[allow(non_upper_case_globals)]
impl FontWeight {
pub const ExtraBlack: Self = Self(950);
pub const Black: Self = Self(900);
pub const ExtraBold: Self = Self(800);
pub const Bold: Self = Self(700);
pub const SemiBold: Self = Self(600);
pub const Medium: Self = Self(500);
pub const Normal: Self = Self(500);
pub const SemiLight: Self = Self(350);
pub const Light: Self = Self(300);
pub const ExtraLight: Self = Self(200);
pub const Thin: Self = Self(100);
}
impl From<u16> for FontWeight {
fn from(value: u16) -> Self {
Self(value)
}
}
impl From<FontWeight> for windows::UI::Text::FontWeight {
fn from(value: FontWeight) -> Self {
Self { Weight: value.0 }
}
}
mod dispatcher {
use windows::core::CanTryInto;
use windows::Foundation::IAsyncAction;
use windows::UI::Core::IdleDispatchedHandler;
use windows_ext::UI::Xaml::UIElement;
pub trait DispatchTarget {
fn run_on_idle<F: FnMut() -> crate::Result<()> + Send + 'static>(&self, callback: F) -> windows::core::Result<IAsyncAction>;
}
impl<T: CanTryInto<UIElement>> DispatchTarget for T {
fn run_on_idle<F: FnMut() -> crate::Result<()> + Send + 'static>(&self, mut callback: F) -> windows::core::Result<IAsyncAction> {
let dispatcher = self.cast::<UIElement>()?.Dispatcher()?;
dispatcher.RunIdleAsync(&IdleDispatchedHandler::new(move |_| {
callback().unwrap_or_else(|err| log::warn!("Error in callback: {err}"));
Ok(())
}))
}
}
}
mod style {
use windows::core::{IInspectable, IntoParam};
use windows_ext::UI::Xaml::{DependencyProperty, Setter};
use crate::ui::NewType;
use crate::utils::winrt::GetTypeName;
use crate::Result;
new_type!(Style, windows_ext::UI::Xaml::Style, no_ui);
impl Style {
pub fn new<T: GetTypeName>() -> Result<Self> {
Ok(Self(<Self as NewType>::Inner::CreateInstance(&T::type_name())?))
}
pub fn with_setter<P, V>(self, property: P, value: V) -> Result<Self>
where
P: IntoParam<DependencyProperty>,
V: IntoParam<IInspectable>
{
let setter = Setter::CreateInstance(property, value)?;
self.0.Setters()?.Append(&setter)?;
Ok(self)
}
}
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/assets/ids.rs | assets/ids.rs |
#[allow(dead_code)]
const APP_ICON: u16 = 1;
const BRIGHTNESS_LIGHT_ICON: u16 = 2;
const BRIGHTNESS_DARK_ICON: u16 = 3;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/lib.rs | lib/windows-ext/src/lib.rs | #![allow(non_snake_case, clashing_extern_declarations, non_upper_case_globals, non_camel_case_types, clippy::all)]
include!("Windows/mod.rs");
pub trait FontFamilyExt: Sized {
fn new(name: &windows_core::HSTRING) -> windows_core::Result<Self>;
}
impl FontFamilyExt for crate::UI::Xaml::Media::FontFamily {
fn new(name: &windows_core::HSTRING) -> windows_core::Result<Self> {
IFontFamilyFactoryFn(|this| unsafe {
let mut result__ = ::std::mem::zeroed();
(::windows_core::Interface::vtable(this).CreateInstanceWithName)(
::windows_core::Interface::as_raw(this),
::core::mem::transmute_copy(name),
::core::ptr::null_mut(),
&mut Option::<::windows::core::IInspectable>::None as *mut _ as _,
&mut result__
)
.from_abi(result__)
})
}
}
fn IFontFamilyFactoryFn<R, F: FnOnce(&crate::UI::Xaml::Media::IFontFamilyFactory) -> windows_core::Result<R>>(
callback: F
) -> windows_core::Result<R> {
static SHARED: ::windows_core::imp::FactoryCache<crate::UI::Xaml::Media::FontFamily, crate::UI::Xaml::Media::IFontFamilyFactory> =
::windows_core::imp::FactoryCache::new();
SHARED.call(callback)
}
#[doc(hidden)]
#[repr(C)]
pub struct IXamlSourceTransparency_Vtbl {
pub base: windows_core::IInspectable_Vtbl,
pub IsBackgroundTransparent: unsafe extern "system" fn(this: *mut std::ffi::c_void, *mut bool) -> windows_core::HRESULT,
pub SetIsBackgroundTransparent: unsafe extern "system" fn(this: *mut std::ffi::c_void, bool) -> windows_core::HRESULT
}
#[repr(transparent)]
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct IXamlSourceTransparency(windows_core::IUnknown);
impl IXamlSourceTransparency {
pub fn IsBackgroundTransparent(&self) -> windows_core::Result<bool> {
unsafe {
let mut result__ = ::std::mem::zeroed();
(::windows_core::Interface::vtable(self).IsBackgroundTransparent)(::windows_core::Interface::as_raw(self), &mut result__)
.from_abi(result__)
}
}
pub fn SetIsBackgroundTransparent(&self, transparent: bool) -> windows_core::Result<()> {
unsafe { (::windows_core::Interface::vtable(self).SetIsBackgroundTransparent)(::windows_core::Interface::as_raw(self), transparent).ok() }
}
}
windows_core::imp::interface_hierarchy!(IXamlSourceTransparency, windows_core::IUnknown, windows_core::IInspectable);
unsafe impl windows_core::Interface for IXamlSourceTransparency {
type Vtable = IXamlSourceTransparency_Vtbl;
}
unsafe impl windows_core::ComInterface for IXamlSourceTransparency {
const IID: windows_core::GUID = windows_core::GUID::from_u128(0x06636c29_5a17_458d_8ea2_2422d997a922);
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/mod.rs | lib/windows-ext/src/Windows/mod.rs | pub mod UI;
pub mod Win32;
pub mod Foundation;pub mod System; | rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/mod.rs | lib/windows-ext/src/Windows/UI/mod.rs | pub mod Xaml;
pub use windows::UI::*;
pub mod Input;pub mod Core;pub mod Text; | rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/mod.rs | pub mod Controls;
pub mod Hosting;
pub mod Input;
pub mod Interop;
pub mod Media;
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAdaptiveTrigger(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAdaptiveTrigger {
type Vtable = IAdaptiveTrigger_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAdaptiveTrigger {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xa5f04119_0cd9_49f1_a23f_44e547ab9f1a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAdaptiveTrigger_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub MinWindowWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetMinWindowWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub MinWindowHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetMinWindowHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAdaptiveTriggerFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAdaptiveTriggerFactory {
type Vtable = IAdaptiveTriggerFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAdaptiveTriggerFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc966d482_5aeb_4841_9247_c1a0bdd6f59f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAdaptiveTriggerFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAdaptiveTriggerStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAdaptiveTriggerStatics {
type Vtable = IAdaptiveTriggerStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAdaptiveTriggerStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb92e29ea_1615_4350_9c3b_92b2986bf444,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAdaptiveTriggerStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub MinWindowWidthProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MinWindowHeightProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplication(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplication {
type Vtable = IApplication_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplication {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x74b861a1_7487_46a9_9a6e_c78b512726c5,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplication_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Resources: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetResources: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub DebugSettings: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RequestedTheme: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ApplicationTheme,
) -> ::windows_core::HRESULT,
pub SetRequestedTheme: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ApplicationTheme,
) -> ::windows_core::HRESULT,
pub UnhandledException: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveUnhandledException: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
Suspending: usize,
pub RemoveSuspending: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub Resuming: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveResuming: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub Exit: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplication2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplication2 {
type Vtable = IApplication2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplication2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x019104be_522a_5904_f52f_de72010429e0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplication2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub FocusVisualKind: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut FocusVisualKind,
) -> ::windows_core::HRESULT,
pub SetFocusVisualKind: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: FocusVisualKind,
) -> ::windows_core::HRESULT,
pub RequiresPointerMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ApplicationRequiresPointerMode,
) -> ::windows_core::HRESULT,
pub SetRequiresPointerMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ApplicationRequiresPointerMode,
) -> ::windows_core::HRESULT,
LeavingBackground: usize,
pub RemoveLeavingBackground: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
EnteredBackground: usize,
pub RemoveEnteredBackground: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplication3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplication3 {
type Vtable = IApplication3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplication3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb775ad7c_18b8_45ca_a1b0_dc483e4b1028,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplication3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub HighContrastAdjustment: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ApplicationHighContrastAdjustment,
) -> ::windows_core::HRESULT,
pub SetHighContrastAdjustment: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ApplicationHighContrastAdjustment,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplicationFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplicationFactory {
type Vtable = IApplicationFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplicationFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x93bbe361_be5a_4ee3_b4a3_95118dc97a89,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplicationInitializationCallbackParams(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplicationInitializationCallbackParams {
type Vtable = IApplicationInitializationCallbackParams_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplicationInitializationCallbackParams {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x751b792e_5772_4488_8b87_f547faa64474,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationInitializationCallbackParams_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplicationOverrides(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplicationOverrides {
type Vtable = IApplicationOverrides_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplicationOverrides {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x25f99ff7_9347_459a_9fac_b2d0e11c1a0f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationOverrides_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
OnActivated: usize,
OnLaunched: usize,
OnFileActivated: usize,
OnSearchActivated: usize,
OnShareTargetActivated: usize,
OnFileOpenPickerActivated: usize,
OnFileSavePickerActivated: usize,
OnCachedFileUpdaterActivated: usize,
pub OnWindowCreated: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
args: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplicationOverrides2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplicationOverrides2 {
type Vtable = IApplicationOverrides2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplicationOverrides2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xdb5cd2b9_d3b4_558c_c64e_0434fd1bd889,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationOverrides2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
OnBackgroundActivated: usize,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IApplicationStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IApplicationStatics {
type Vtable = IApplicationStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IApplicationStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x06499997_f7b4_45fe_b763_7577d1d3cb4a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IApplicationStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Current: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Start: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
callback: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LoadComponent: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
component: *mut ::core::ffi::c_void,
resourcelocator: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LoadComponentWithResourceLocation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
component: *mut ::core::ffi::c_void,
resourcelocator: *mut ::core::ffi::c_void,
componentresourcelocation: Controls::Primitives::ComponentResourceLocation,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindingFailedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBindingFailedEventArgs {
type Vtable = IBindingFailedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindingFailedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x32c1d013_4dbd_446d_bbb8_0de35048a449,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindingFailedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Message: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBringIntoViewOptions(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBringIntoViewOptions {
type Vtable = IBringIntoViewOptions_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBringIntoViewOptions {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x19bdd1b5_c7cb_46d9_a4dd_a1bbe83ef2fb,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBringIntoViewOptions_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub AnimationDesired: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetAnimationDesired: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub TargetRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetTargetRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBringIntoViewOptions2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBringIntoViewOptions2 {
type Vtable = IBringIntoViewOptions2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBringIntoViewOptions2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xe855e08e_64b6_1211_bddb_1fddbb6e8231,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBringIntoViewOptions2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub HorizontalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetHorizontalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub VerticalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetVerticalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub HorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetHorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub VerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetVerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBringIntoViewRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBringIntoViewRequestedEventArgs {
type Vtable = IBringIntoViewRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBringIntoViewRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x0e629ec4_2206_4c8b_94ae_bdb66a4ebfd1,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBringIntoViewRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TargetElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetTargetElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AnimationDesired: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetAnimationDesired: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub TargetRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub SetTargetRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub HorizontalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub VerticalAlignmentRatio: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub HorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetHorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub VerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetVerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrushTransition(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrushTransition {
type Vtable = IBrushTransition_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrushTransition {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1116972c_9dad_5429_a7dd_b2b7d061ab8e,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrushTransition_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Duration: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Foundation::TimeSpan,
) -> ::windows_core::HRESULT,
pub SetDuration: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::Foundation::TimeSpan,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrushTransitionFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrushTransitionFactory {
type Vtable = IBrushTransitionFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrushTransitionFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x3dbe7368_13d4_510c_a215_7539f4787b52,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrushTransitionFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorPaletteResources(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorPaletteResources {
type Vtable = IColorPaletteResources_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorPaletteResources {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x258088c4_aef2_5d3f_833b_c36db6278ed9,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorPaletteResources_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub AltHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAltHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AltLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAltLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AltMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAltMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AltMediumHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAltMediumHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AltMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAltMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub BaseHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetBaseHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub BaseLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetBaseLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub BaseMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetBaseMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub BaseMediumHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetBaseMediumHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub BaseMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetBaseMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeAltLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeAltLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeBlackHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeBlackHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeBlackLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeBlackLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeBlackMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeBlackMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeBlackMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeBlackMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeDisabledHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeDisabledHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeDisabledLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeDisabledLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeHigh: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeMediumLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeWhite: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeWhite: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ChromeGray: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetChromeGray: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ListLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetListLow: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ListMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetListMedium: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ErrorText: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetErrorText: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Accent: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAccent: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorPaletteResourcesFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorPaletteResourcesFactory {
type Vtable = IColorPaletteResourcesFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorPaletteResourcesFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xa57f0783_1876_5cc0_8ea5_bc77b17e0f7e,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorPaletteResourcesFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Hosting/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Hosting/mod.rs | #[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesignerAppExitedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesignerAppExitedEventArgs {
type Vtable = IDesignerAppExitedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesignerAppExitedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xf6aac86a_0cad_410c_8f62_dc2936151c74,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesignerAppExitedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ExitCode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut u32,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesignerAppManager(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesignerAppManager {
type Vtable = IDesignerAppManager_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesignerAppManager {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xa6272caa_d5c6_40cb_abd9_27ba43831bb7,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesignerAppManager_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub AppUserModelId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub DesignerAppExited: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveDesignerAppExited: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub CreateNewViewAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
initialviewstate: DesignerAppViewState,
initialviewsize: super::super::super::Foundation::Size,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LoadObjectIntoAppAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
dllname: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
classid: ::windows_core::GUID,
initializationdata: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesignerAppManagerFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesignerAppManagerFactory {
type Vtable = IDesignerAppManagerFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesignerAppManagerFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x8f9d633b_1266_4c0e_8499_0db85bbd4c43,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesignerAppManagerFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Create: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
appusermodelid: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesignerAppView(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesignerAppView {
type Vtable = IDesignerAppView_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesignerAppView {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x5c777cea_dd71_4a84_a56f_dacb4b14706f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesignerAppView_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ApplicationViewId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub AppUserModelId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub ViewState: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut DesignerAppViewState,
) -> ::windows_core::HRESULT,
pub ViewSize: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Size,
) -> ::windows_core::HRESULT,
pub UpdateViewAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
viewstate: DesignerAppViewState,
viewsize: super::super::super::Foundation::Size,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesktopWindowXamlSource(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesktopWindowXamlSource {
type Vtable = IDesktopWindowXamlSource_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesktopWindowXamlSource {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xd585bfe1_00ff_51be_ba1d_a1329956ea0a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesktopWindowXamlSource_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Content: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetContent: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub HasFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub TakeFocusRequested: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveTakeFocusRequested: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub GotFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveGotFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub NavigateFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
request: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesktopWindowXamlSourceFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesktopWindowXamlSourceFactory {
type Vtable = IDesktopWindowXamlSourceFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesktopWindowXamlSourceFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x5cd61dc0_2561_56e1_8e75_6e44173805e3,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesktopWindowXamlSourceFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesktopWindowXamlSourceGotFocusEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDesktopWindowXamlSourceGotFocusEventArgs {
type Vtable = IDesktopWindowXamlSourceGotFocusEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDesktopWindowXamlSourceGotFocusEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x39be4849_d9cc_5b70_8f05_1ad9a4aaa342,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesktopWindowXamlSourceGotFocusEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Request: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDesktopWindowXamlSourceTakeFocusRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface
for IDesktopWindowXamlSourceTakeFocusRequestedEventArgs {
type Vtable = IDesktopWindowXamlSourceTakeFocusRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface
for IDesktopWindowXamlSourceTakeFocusRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfe61e4b9_a7af_52b3_bdb9_c3305c0b8df2,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDesktopWindowXamlSourceTakeFocusRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Request: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IElementCompositionPreview(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IElementCompositionPreview {
type Vtable = IElementCompositionPreview_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IElementCompositionPreview {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb6f1a676_cfe6_46ac_acf6_c4687bb65e60,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IElementCompositionPreview_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IElementCompositionPreviewStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IElementCompositionPreviewStatics {
type Vtable = IElementCompositionPreviewStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IElementCompositionPreviewStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x08c92b38_ec99_4c55_bc85_a1c180b27646,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IElementCompositionPreviewStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
GetElementVisual: usize,
GetElementChildVisual: usize,
SetElementChildVisual: usize,
GetScrollViewerManipulationPropertySet: usize,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IElementCompositionPreviewStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IElementCompositionPreviewStatics2 {
type Vtable = IElementCompositionPreviewStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IElementCompositionPreviewStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x24148fbb_23d6_4f37_ba0c_0733e799722d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IElementCompositionPreviewStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
SetImplicitShowAnimation: usize,
SetImplicitHideAnimation: usize,
pub SetIsTranslationEnabled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
element: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
GetPointerPositionPropertySet: usize,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IElementCompositionPreviewStatics3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IElementCompositionPreviewStatics3 {
type Vtable = IElementCompositionPreviewStatics3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IElementCompositionPreviewStatics3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x843bc4c3_c105_59fe_a3d1_373c1d3e6fbc,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IElementCompositionPreviewStatics3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
SetAppWindowContent: usize,
GetAppWindowContent: usize,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IWindowsXamlManager(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IWindowsXamlManager {
type Vtable = IWindowsXamlManager_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IWindowsXamlManager {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x56096c31_1aa0_5288_8818_6e74a2dcaff5,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IWindowsXamlManager_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IWindowsXamlManagerStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IWindowsXamlManagerStatics {
type Vtable = IWindowsXamlManagerStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IWindowsXamlManagerStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x28258a12_7d82_505b_b210_712b04a58882,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IWindowsXamlManagerStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub InitializeForCurrentThread: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlSourceFocusNavigationRequest(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlSourceFocusNavigationRequest {
type Vtable = IXamlSourceFocusNavigationRequest_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlSourceFocusNavigationRequest {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfbb93bb5_1496_5a80_ac00_e757359755e6,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlSourceFocusNavigationRequest_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Reason: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut XamlSourceFocusNavigationReason,
) -> ::windows_core::HRESULT,
pub HintRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub CorrelationId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::windows_core::GUID,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlSourceFocusNavigationRequestFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlSourceFocusNavigationRequestFactory {
type Vtable = IXamlSourceFocusNavigationRequestFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlSourceFocusNavigationRequestFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xe746ab8f_b4ef_5390_97e5_cc0a2779c574,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlSourceFocusNavigationRequestFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
reason: XamlSourceFocusNavigationReason,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CreateInstanceWithHintRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
reason: XamlSourceFocusNavigationReason,
hintrect: super::super::super::Foundation::Rect,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CreateInstanceWithHintRectAndCorrelationId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
reason: XamlSourceFocusNavigationReason,
hintrect: super::super::super::Foundation::Rect,
correlationid: ::windows_core::GUID,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlSourceFocusNavigationResult(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlSourceFocusNavigationResult {
type Vtable = IXamlSourceFocusNavigationResult_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlSourceFocusNavigationResult {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x88d55a5f_9603_5d8f_9cc7_d1c4070d9801,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlSourceFocusNavigationResult_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub WasFocusMoved: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlSourceFocusNavigationResultFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlSourceFocusNavigationResultFactory {
type Vtable = IXamlSourceFocusNavigationResultFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlSourceFocusNavigationResultFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x43bbadbf_f9e1_5527_b8c5_09339ff2ca76,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlSourceFocusNavigationResultFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusmoved: bool,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenter(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlUIPresenter {
type Vtable = IXamlUIPresenter_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenter {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xa714944a_1619_4fc6_b31b_89512ef022a2,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenter_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub RootElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetRootElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ThemeKey: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetThemeKey: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub ThemeResourcesXaml: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetThemeResourcesXaml: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetSize: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
width: i32,
height: i32,
) -> ::windows_core::HRESULT,
pub Render: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Present: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenterHost(::windows_core::IUnknown);
impl IXamlUIPresenterHost {}
::windows_core::imp::interface_hierarchy!(
IXamlUIPresenterHost, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for IXamlUIPresenterHost {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{aafb84cd-9f6d-4f80-ac2c-0e6cb9f31659}",
);
}
unsafe impl ::windows_core::Interface for IXamlUIPresenterHost {
type Vtable = IXamlUIPresenterHost_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenterHost {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xaafb84cd_9f6d_4f80_ac2c_0e6cb9f31659,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenterHost_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ResolveFileResource: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
path: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenterHost2(::windows_core::IUnknown);
impl IXamlUIPresenterHost2 {}
::windows_core::imp::interface_hierarchy!(
IXamlUIPresenterHost2, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for IXamlUIPresenterHost2 {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{61595672-7ca4-4a21-b56a-88f4812388ca}",
);
}
unsafe impl ::windows_core::Interface for IXamlUIPresenterHost2 {
type Vtable = IXamlUIPresenterHost2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenterHost2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x61595672_7ca4_4a21_b56a_88f4812388ca,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenterHost2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetGenericXamlFilePath: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenterHost3(::windows_core::IUnknown);
impl IXamlUIPresenterHost3 {}
::windows_core::imp::interface_hierarchy!(
IXamlUIPresenterHost3, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for IXamlUIPresenterHost3 {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{b14292bf-7320-41bb-9f26-4d6fd34db45a}",
);
}
unsafe impl ::windows_core::Interface for IXamlUIPresenterHost3 {
type Vtable = IXamlUIPresenterHost3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenterHost3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb14292bf_7320_41bb_9f26_4d6fd34db45a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenterHost3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ResolveDictionaryResource: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
dictionary: *mut ::core::ffi::c_void,
dictionarykey: *mut ::core::ffi::c_void,
suggestedvalue: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenterStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlUIPresenterStatics {
type Vtable = IXamlUIPresenterStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenterStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x71eaeac8_45e1_4192_85aa_3a422edd23cf,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenterStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CompleteTimelinesAutomatically: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetCompleteTimelinesAutomatically: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub SetHost: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
host: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub NotifyWindowSizeChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IXamlUIPresenterStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IXamlUIPresenterStatics2 {
type Vtable = IXamlUIPresenterStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IXamlUIPresenterStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x5c6b68d2_cf1c_4f53_bf09_6a745f7a9703,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IXamlUIPresenterStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetFlyoutPlacementTargetInfo: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
placementtarget: *mut ::core::ffi::c_void,
preferredplacement: super::Controls::Primitives::FlyoutPlacementMode,
targetpreferredplacement: *mut super::Controls::Primitives::FlyoutPlacementMode,
allowfallbacks: *mut bool,
result__: *mut super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub GetFlyoutPlacement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
placementtargetbounds: super::super::super::Foundation::Rect,
controlsize: super::super::super::Foundation::Size,
mincontrolsize: super::super::super::Foundation::Size,
containerrect: super::super::super::Foundation::Rect,
targetpreferredplacement: super::Controls::Primitives::FlyoutPlacementMode,
allowfallbacks: bool,
chosenplacement: *mut super::Controls::Primitives::FlyoutPlacementMode,
result__: *mut super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct DesignerAppExitedEventArgs(::windows_core::IUnknown);
impl DesignerAppExitedEventArgs {}
impl ::windows_core::RuntimeType for DesignerAppExitedEventArgs {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"rc(Windows.UI.Xaml.Hosting.DesignerAppExitedEventArgs;{f6aac86a-0cad-410c-8f62-dc2936151c74})",
);
}
unsafe impl ::windows_core::Interface for DesignerAppExitedEventArgs {
type Vtable = IDesignerAppExitedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for DesignerAppExitedEventArgs {
const IID: ::windows_core::GUID = <IDesignerAppExitedEventArgs as ::windows_core::ComInterface>::IID;
}
impl ::windows_core::RuntimeName for DesignerAppExitedEventArgs {
const NAME: &'static str = "Windows.UI.Xaml.Hosting.DesignerAppExitedEventArgs";
}
::windows_core::imp::interface_hierarchy!(
DesignerAppExitedEventArgs, ::windows_core::IUnknown, ::windows_core::IInspectable
);
unsafe impl ::core::marker::Send for DesignerAppExitedEventArgs {}
unsafe impl ::core::marker::Sync for DesignerAppExitedEventArgs {}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct DesignerAppManager(::windows_core::IUnknown);
impl DesignerAppManager {}
impl ::windows_core::RuntimeType for DesignerAppManager {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"rc(Windows.UI.Xaml.Hosting.DesignerAppManager;{a6272caa-d5c6-40cb-abd9-27ba43831bb7})",
);
}
unsafe impl ::windows_core::Interface for DesignerAppManager {
type Vtable = IDesignerAppManager_Vtbl;
}
unsafe impl ::windows_core::ComInterface for DesignerAppManager {
const IID: ::windows_core::GUID = <IDesignerAppManager as ::windows_core::ComInterface>::IID;
}
impl ::windows_core::RuntimeName for DesignerAppManager {
const NAME: &'static str = "Windows.UI.Xaml.Hosting.DesignerAppManager";
}
::windows_core::imp::interface_hierarchy!(
DesignerAppManager, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::CanTryInto<super::super::super::Foundation::IClosable>
for DesignerAppManager {}
unsafe impl ::core::marker::Send for DesignerAppManager {}
unsafe impl ::core::marker::Sync for DesignerAppManager {}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct DesignerAppView(::windows_core::IUnknown);
impl DesignerAppView {}
impl ::windows_core::RuntimeType for DesignerAppView {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"rc(Windows.UI.Xaml.Hosting.DesignerAppView;{5c777cea-dd71-4a84-a56f-dacb4b14706f})",
);
}
unsafe impl ::windows_core::Interface for DesignerAppView {
type Vtable = IDesignerAppView_Vtbl;
}
unsafe impl ::windows_core::ComInterface for DesignerAppView {
const IID: ::windows_core::GUID = <IDesignerAppView as ::windows_core::ComInterface>::IID;
}
impl ::windows_core::RuntimeName for DesignerAppView {
const NAME: &'static str = "Windows.UI.Xaml.Hosting.DesignerAppView";
}
::windows_core::imp::interface_hierarchy!(
DesignerAppView, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::CanTryInto<super::super::super::Foundation::IClosable>
for DesignerAppView {}
unsafe impl ::core::marker::Send for DesignerAppView {}
unsafe impl ::core::marker::Sync for DesignerAppView {}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct DesktopWindowXamlSource(::windows_core::IUnknown);
impl DesktopWindowXamlSource {
pub fn SetContent<P0>(&self, value: P0) -> ::windows_core::Result<()>
where
P0: ::windows_core::TryIntoParam<super::UIElement>,
{
let this = self;
unsafe {
(::windows_core::Interface::vtable(this)
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Interop/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Interop/mod.rs | #[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindableIterable(::windows_core::IUnknown);
impl IBindableIterable {}
::windows_core::imp::interface_hierarchy!(
IBindableIterable, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for IBindableIterable {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{036d2c08-df29-41af-8aa2-d774be62ba6f}",
);
}
unsafe impl ::windows_core::Interface for IBindableIterable {
type Vtable = IBindableIterable_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindableIterable {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x036d2c08_df29_41af_8aa2_d774be62ba6f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindableIterable_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub First: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindableIterator(::windows_core::IUnknown);
impl IBindableIterator {}
::windows_core::imp::interface_hierarchy!(
IBindableIterator, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for IBindableIterator {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{6a1d6c07-076d-49f2-8314-f52c9c9a8331}",
);
}
unsafe impl ::windows_core::Interface for IBindableIterator {
type Vtable = IBindableIterator_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindableIterator {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x6a1d6c07_076d_49f2_8314_f52c9c9a8331,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindableIterator_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Current: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub HasCurrent: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub MoveNext: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindableObservableVector(::windows_core::IUnknown);
impl IBindableObservableVector {}
::windows_core::imp::interface_hierarchy!(
IBindableObservableVector, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::CanTryInto<IBindableIterable> for IBindableObservableVector {}
impl ::windows_core::CanTryInto<IBindableVector> for IBindableObservableVector {}
impl ::windows_core::RuntimeType for IBindableObservableVector {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{fe1eb536-7e7f-4f90-ac9a-474984aae512}",
);
}
unsafe impl ::windows_core::Interface for IBindableObservableVector {
type Vtable = IBindableObservableVector_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindableObservableVector {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfe1eb536_7e7f_4f90_ac9a_474984aae512,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindableObservableVector_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub VectorChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveVectorChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindableVector(::windows_core::IUnknown);
impl IBindableVector {}
::windows_core::imp::interface_hierarchy!(
IBindableVector, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::CanTryInto<IBindableIterable> for IBindableVector {}
impl ::windows_core::RuntimeType for IBindableVector {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{393de7de-6fd0-4c0d-bb71-47244a113e93}",
);
}
unsafe impl ::windows_core::Interface for IBindableVector {
type Vtable = IBindableVector_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindableVector {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x393de7de_6fd0_4c0d_bb71_47244a113e93,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindableVector_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetAt: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
index: u32,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Size: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut u32,
) -> ::windows_core::HRESULT,
pub GetView: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IndexOf: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
index: *mut u32,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetAt: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
index: u32,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub InsertAt: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
index: u32,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RemoveAt: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
index: u32,
) -> ::windows_core::HRESULT,
pub Append: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RemoveAtEnd: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Clear: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBindableVectorView(::windows_core::IUnknown);
impl IBindableVectorView {}
::windows_core::imp::interface_hierarchy!(
IBindableVectorView, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::CanTryInto<IBindableIterable> for IBindableVectorView {}
impl ::windows_core::RuntimeType for IBindableVectorView {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{346dd6e7-976e-4bc3-815d-ece243bc0f33}",
);
}
unsafe impl ::windows_core::Interface for IBindableVectorView {
type Vtable = IBindableVectorView_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBindableVectorView {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x346dd6e7_976e_4bc3_815d_ece243bc0f33,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBindableVectorView_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetAt: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
index: u32,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Size: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut u32,
) -> ::windows_core::HRESULT,
pub IndexOf: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
index: *mut u32,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct INotifyCollectionChanged(::windows_core::IUnknown);
impl INotifyCollectionChanged {}
::windows_core::imp::interface_hierarchy!(
INotifyCollectionChanged, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for INotifyCollectionChanged {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{28b167d5-1a31-465b-9b25-d5c3ae686c40}",
);
}
unsafe impl ::windows_core::Interface for INotifyCollectionChanged {
type Vtable = INotifyCollectionChanged_Vtbl;
}
unsafe impl ::windows_core::ComInterface for INotifyCollectionChanged {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x28b167d5_1a31_465b_9b25_d5c3ae686c40,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct INotifyCollectionChanged_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CollectionChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveCollectionChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct INotifyCollectionChangedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for INotifyCollectionChangedEventArgs {
type Vtable = INotifyCollectionChangedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for INotifyCollectionChangedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4cf68d33_e3f2_4964_b85e_945b4f7e2f21,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct INotifyCollectionChangedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Action: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut NotifyCollectionChangedAction,
) -> ::windows_core::HRESULT,
pub NewItems: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub OldItems: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub NewStartingIndex: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub OldStartingIndex: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct INotifyCollectionChangedEventArgsFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for INotifyCollectionChangedEventArgsFactory {
type Vtable = INotifyCollectionChangedEventArgsFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for INotifyCollectionChangedEventArgsFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb30c3e3a_df8d_44a5_9a38_7ac0d08ce63d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct INotifyCollectionChangedEventArgsFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstanceWithAllParameters: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
action: NotifyCollectionChangedAction,
newitems: *mut ::core::ffi::c_void,
olditems: *mut ::core::ffi::c_void,
newindex: i32,
oldindex: i32,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct NotifyCollectionChangedEventArgs(::windows_core::IUnknown);
impl NotifyCollectionChangedEventArgs {}
impl ::windows_core::RuntimeType for NotifyCollectionChangedEventArgs {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"rc(Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs;{4cf68d33-e3f2-4964-b85e-945b4f7e2f21})",
);
}
unsafe impl ::windows_core::Interface for NotifyCollectionChangedEventArgs {
type Vtable = INotifyCollectionChangedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for NotifyCollectionChangedEventArgs {
const IID: ::windows_core::GUID = <INotifyCollectionChangedEventArgs as ::windows_core::ComInterface>::IID;
}
impl ::windows_core::RuntimeName for NotifyCollectionChangedEventArgs {
const NAME: &'static str = "Windows.UI.Xaml.Interop.NotifyCollectionChangedEventArgs";
}
::windows_core::imp::interface_hierarchy!(
NotifyCollectionChangedEventArgs, ::windows_core::IUnknown,
::windows_core::IInspectable
);
unsafe impl ::core::marker::Send for NotifyCollectionChangedEventArgs {}
unsafe impl ::core::marker::Sync for NotifyCollectionChangedEventArgs {}
#[repr(transparent)]
#[derive(::core::cmp::PartialEq, ::core::cmp::Eq)]
pub struct NotifyCollectionChangedAction(pub i32);
impl NotifyCollectionChangedAction {
pub const Add: Self = Self(0i32);
pub const Remove: Self = Self(1i32);
pub const Replace: Self = Self(2i32);
pub const Move: Self = Self(3i32);
pub const Reset: Self = Self(4i32);
}
impl ::core::marker::Copy for NotifyCollectionChangedAction {}
impl ::core::clone::Clone for NotifyCollectionChangedAction {
fn clone(&self) -> Self {
*self
}
}
impl ::core::default::Default for NotifyCollectionChangedAction {
fn default() -> Self {
Self(0)
}
}
impl ::windows_core::TypeKind for NotifyCollectionChangedAction {
type TypeKind = ::windows_core::CopyType;
}
impl ::core::fmt::Debug for NotifyCollectionChangedAction {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_tuple("NotifyCollectionChangedAction").field(&self.0).finish()
}
}
impl ::windows_core::RuntimeType for NotifyCollectionChangedAction {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"enum(Windows.UI.Xaml.Interop.NotifyCollectionChangedAction;i4)",
);
}
#[repr(transparent)]
#[derive(::core::cmp::PartialEq, ::core::cmp::Eq)]
pub struct TypeKind(pub i32);
impl TypeKind {
pub const Primitive: Self = Self(0i32);
pub const Metadata: Self = Self(1i32);
pub const Custom: Self = Self(2i32);
}
impl ::core::marker::Copy for TypeKind {}
impl ::core::clone::Clone for TypeKind {
fn clone(&self) -> Self {
*self
}
}
impl ::core::default::Default for TypeKind {
fn default() -> Self {
Self(0)
}
}
impl ::windows_core::TypeKind for TypeKind {
type TypeKind = ::windows_core::CopyType;
}
impl ::core::fmt::Debug for TypeKind {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_tuple("TypeKind").field(&self.0).finish()
}
}
impl ::windows_core::RuntimeType for TypeKind {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"enum(Windows.UI.Xaml.Interop.TypeKind;i4)",
);
}
#[repr(C)]
pub struct TypeName {
pub Name: ::windows_core::HSTRING,
pub Kind: TypeKind,
}
impl ::core::clone::Clone for TypeName {
fn clone(&self) -> Self {
Self {
Name: self.Name.clone(),
Kind: self.Kind,
}
}
}
impl ::core::fmt::Debug for TypeName {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.debug_struct("TypeName")
.field("Name", &self.Name)
.field("Kind", &self.Kind)
.finish()
}
}
impl ::windows_core::TypeKind for TypeName {
type TypeKind = ::windows_core::ValueType;
}
impl ::windows_core::RuntimeType for TypeName {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"struct(Windows.UI.Xaml.Interop.TypeName;string;enum(Windows.UI.Xaml.Interop.TypeKind;i4))",
);
}
impl ::core::cmp::PartialEq for TypeName {
fn eq(&self, other: &Self) -> bool {
self.Name == other.Name && self.Kind == other.Kind
}
}
impl ::core::cmp::Eq for TypeName {}
impl ::core::default::Default for TypeName {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct BindableVectorChangedEventHandler(pub ::windows_core::IUnknown);
impl BindableVectorChangedEventHandler {}
#[repr(C)]
struct BindableVectorChangedEventHandlerBox<
F: FnMut(
::core::option::Option<&IBindableObservableVector>,
::core::option::Option<&::windows_core::IInspectable>,
) -> ::windows_core::Result<()> + ::core::marker::Send + 'static,
> {
vtable: *const BindableVectorChangedEventHandler_Vtbl,
invoke: F,
count: ::windows_core::imp::RefCount,
}
#[allow(dead_code)]
impl<
F: FnMut(
::core::option::Option<&IBindableObservableVector>,
::core::option::Option<&::windows_core::IInspectable>,
) -> ::windows_core::Result<()> + ::core::marker::Send + 'static,
> BindableVectorChangedEventHandlerBox<F> {
const VTABLE: BindableVectorChangedEventHandler_Vtbl = BindableVectorChangedEventHandler_Vtbl {
base__: ::windows_core::IUnknown_Vtbl {
QueryInterface: Self::QueryInterface,
AddRef: Self::AddRef,
Release: Self::Release,
},
Invoke: Self::Invoke,
};
unsafe extern "system" fn QueryInterface(
this: *mut ::core::ffi::c_void,
iid: *const ::windows_core::GUID,
interface: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
if iid.is_null() || interface.is_null() {
return ::windows_core::HRESULT(-2147467261);
}
*interface = if *iid
== <BindableVectorChangedEventHandler as ::windows_core::ComInterface>::IID
|| *iid == <::windows_core::IUnknown as ::windows_core::ComInterface>::IID
|| *iid
== <::windows_core::imp::IAgileObject as ::windows_core::ComInterface>::IID
{
&mut (*this).vtable as *mut _ as _
} else {
::core::ptr::null_mut()
};
if (*interface).is_null() {
::windows_core::HRESULT(-2147467262)
} else {
(*this).count.add_ref();
::windows_core::HRESULT(0)
}
}
unsafe extern "system" fn AddRef(this: *mut ::core::ffi::c_void) -> u32 {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
(*this).count.add_ref()
}
unsafe extern "system" fn Release(this: *mut ::core::ffi::c_void) -> u32 {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
let remaining = (*this).count.release();
if remaining == 0 {
let _ = ::std::boxed::Box::from_raw(this);
}
remaining
}
unsafe extern "system" fn Invoke(
this: *mut ::core::ffi::c_void,
vector: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
((*this)
.invoke)(
::windows_core::from_raw_borrowed(&vector),
::windows_core::from_raw_borrowed(&e),
)
.into()
}
}
unsafe impl ::windows_core::Interface for BindableVectorChangedEventHandler {
type Vtable = BindableVectorChangedEventHandler_Vtbl;
}
unsafe impl ::windows_core::ComInterface for BindableVectorChangedEventHandler {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x624cd4e1_d007_43b1_9c03_af4d3e6258c4,
);
}
impl ::windows_core::RuntimeType for BindableVectorChangedEventHandler {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{624cd4e1-d007-43b1-9c03-af4d3e6258c4}",
);
}
#[repr(C)]
#[doc(hidden)]
pub struct BindableVectorChangedEventHandler_Vtbl {
pub base__: ::windows_core::IUnknown_Vtbl,
pub Invoke: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
vector: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct NotifyCollectionChangedEventHandler(pub ::windows_core::IUnknown);
impl NotifyCollectionChangedEventHandler {}
#[repr(C)]
struct NotifyCollectionChangedEventHandlerBox<
F: FnMut(
::core::option::Option<&::windows_core::IInspectable>,
::core::option::Option<&NotifyCollectionChangedEventArgs>,
) -> ::windows_core::Result<()> + ::core::marker::Send + 'static,
> {
vtable: *const NotifyCollectionChangedEventHandler_Vtbl,
invoke: F,
count: ::windows_core::imp::RefCount,
}
#[allow(dead_code)]
impl<
F: FnMut(
::core::option::Option<&::windows_core::IInspectable>,
::core::option::Option<&NotifyCollectionChangedEventArgs>,
) -> ::windows_core::Result<()> + ::core::marker::Send + 'static,
> NotifyCollectionChangedEventHandlerBox<F> {
const VTABLE: NotifyCollectionChangedEventHandler_Vtbl = NotifyCollectionChangedEventHandler_Vtbl {
base__: ::windows_core::IUnknown_Vtbl {
QueryInterface: Self::QueryInterface,
AddRef: Self::AddRef,
Release: Self::Release,
},
Invoke: Self::Invoke,
};
unsafe extern "system" fn QueryInterface(
this: *mut ::core::ffi::c_void,
iid: *const ::windows_core::GUID,
interface: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
if iid.is_null() || interface.is_null() {
return ::windows_core::HRESULT(-2147467261);
}
*interface = if *iid
== <NotifyCollectionChangedEventHandler as ::windows_core::ComInterface>::IID
|| *iid == <::windows_core::IUnknown as ::windows_core::ComInterface>::IID
|| *iid
== <::windows_core::imp::IAgileObject as ::windows_core::ComInterface>::IID
{
&mut (*this).vtable as *mut _ as _
} else {
::core::ptr::null_mut()
};
if (*interface).is_null() {
::windows_core::HRESULT(-2147467262)
} else {
(*this).count.add_ref();
::windows_core::HRESULT(0)
}
}
unsafe extern "system" fn AddRef(this: *mut ::core::ffi::c_void) -> u32 {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
(*this).count.add_ref()
}
unsafe extern "system" fn Release(this: *mut ::core::ffi::c_void) -> u32 {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
let remaining = (*this).count.release();
if remaining == 0 {
let _ = ::std::boxed::Box::from_raw(this);
}
remaining
}
unsafe extern "system" fn Invoke(
this: *mut ::core::ffi::c_void,
sender: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT {
let this = this as *mut *mut ::core::ffi::c_void as *mut Self;
((*this)
.invoke)(
::windows_core::from_raw_borrowed(&sender),
::windows_core::from_raw_borrowed(&e),
)
.into()
}
}
unsafe impl ::windows_core::Interface for NotifyCollectionChangedEventHandler {
type Vtable = NotifyCollectionChangedEventHandler_Vtbl;
}
unsafe impl ::windows_core::ComInterface for NotifyCollectionChangedEventHandler {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xca10b37c_f382_4591_8557_5e24965279b0,
);
}
impl ::windows_core::RuntimeType for NotifyCollectionChangedEventHandler {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{ca10b37c-f382-4591-8557-5e24965279b0}",
);
}
#[repr(C)]
#[doc(hidden)]
pub struct NotifyCollectionChangedEventHandler_Vtbl {
pub base__: ::windows_core::IUnknown_Vtbl,
pub Invoke: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
sender: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Controls/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Controls/mod.rs | pub mod Primitives;
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAnchorRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAnchorRequestedEventArgs {
type Vtable = IAnchorRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAnchorRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x5175f55d_4785_5a72_b462_eb11e9bdf897,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAnchorRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Anchor: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetAnchor: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AnchorCandidates: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBar(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBar {
type Vtable = IAppBar_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBar {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x7b0fc253_86a5_4b43_9872_0b8a6234b74b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBar_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsOpen: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetIsOpen: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub IsSticky: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetIsSticky: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub Opened: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveOpened: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub Closed: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveClosed: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBar2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBar2 {
type Vtable = IAppBar2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBar2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc3ab17b3_7ad7_4676_9910_7fe3f0e8e993,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBar2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ClosedDisplayMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut AppBarClosedDisplayMode,
) -> ::windows_core::HRESULT,
pub SetClosedDisplayMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: AppBarClosedDisplayMode,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBar3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBar3 {
type Vtable = IAppBar3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBar3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x982b001f_752e_4e7a_b055_54802c9ea749,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBar3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TemplateSettings: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Opening: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveOpening: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub Closing: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveClosing: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBar4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBar4 {
type Vtable = IAppBar4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBar4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x94ebc8cd_0a64_4da3_bf43_f13100a46605,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBar4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LightDismissOverlayMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut LightDismissOverlayMode,
) -> ::windows_core::HRESULT,
pub SetLightDismissOverlayMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: LightDismissOverlayMode,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButton(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButton {
type Vtable = IAppBarButton_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButton {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4459a451_69e8_440c_9896_4bb4f5f642d1,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButton_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Label: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetLabel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub Icon: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetIcon: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButton3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButton3 {
type Vtable = IAppBarButton3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButton3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x0b282150_198b_4e84_8f1c_9f6a8ba267a7,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButton3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LabelPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut CommandBarLabelPosition,
) -> ::windows_core::HRESULT,
pub SetLabelPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: CommandBarLabelPosition,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButton4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButton4 {
type Vtable = IAppBarButton4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButton4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x958fce6b_fd08_4414_8458_9d40866dc84e,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButton4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub KeyboardAcceleratorTextOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetKeyboardAcceleratorTextOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButton5(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButton5 {
type Vtable = IAppBarButton5_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButton5 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4096fc7f_1aec_4b0f_a031_ca8c4e06d2ed,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButton5_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TemplateSettings: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButtonFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButtonFactory {
type Vtable = IAppBarButtonFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButtonFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xbdbb1bb6_cb2e_4276_abd6_7935130510e0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButtonFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButtonStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButtonStatics {
type Vtable = IAppBarButtonStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButtonStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x7ccd13e6_5301_407f_874e_dc9160aa07af,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButtonStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LabelProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IconProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsCompactProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButtonStatics3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButtonStatics3 {
type Vtable = IAppBarButtonStatics3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButtonStatics3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4d7bf314_2ede_4328_8906_752a1f27cdfa,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButtonStatics3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LabelPositionProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsInOverflowProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub DynamicOverflowOrderProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButtonStatics4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButtonStatics4 {
type Vtable = IAppBarButtonStatics4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButtonStatics4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1c0ae26a_c755_4fe6_a3b6_0e3394e952c0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButtonStatics4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub KeyboardAcceleratorTextOverrideProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarElementContainer(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarElementContainer {
type Vtable = IAppBarElementContainer_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarElementContainer {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1d5ba067_a990_5dab_a9c3_e6be56642a1a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarElementContainer_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarElementContainerFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarElementContainerFactory {
type Vtable = IAppBarElementContainerFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarElementContainerFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb506530e_8897_5d6f_a43e_f0586338d282,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarElementContainerFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarElementContainerStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarElementContainerStatics {
type Vtable = IAppBarElementContainerStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarElementContainerStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xebbef840_c745_5a6f_8671_9a41eb2196e7,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarElementContainerStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsCompactProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsInOverflowProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub DynamicOverflowOrderProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarFactory {
type Vtable = IAppBarFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x614708d1_8e65_43cb_92d7_8eee17515f8d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarOverrides(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarOverrides {
type Vtable = IAppBarOverrides_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarOverrides {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xf003e4e2_7b0f_4f4a_970d_ae8a0eaa9b70,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarOverrides_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub OnClosed: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub OnOpened: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarOverrides3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarOverrides3 {
type Vtable = IAppBarOverrides3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarOverrides3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x412bbbc8_51d0_4b49_ab62_a3dd6bdcb298,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarOverrides3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub OnClosing: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub OnOpening: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
e: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarSeparator(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarSeparator {
type Vtable = IAppBarSeparator_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarSeparator {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1b0795a1_1bc1_4d53_95ea_fb0a2cccc905,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarSeparator_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarSeparatorFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarSeparatorFactory {
type Vtable = IAppBarSeparatorFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarSeparatorFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x05da25cd_f407_48de_8b50_ff87d1e2818f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarSeparatorFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarSeparatorStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarSeparatorStatics {
type Vtable = IAppBarSeparatorStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarSeparatorStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x37f23484_5b35_4663_a75d_f2d50cb9c619,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarSeparatorStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsCompactProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarSeparatorStatics3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarSeparatorStatics3 {
type Vtable = IAppBarSeparatorStatics3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarSeparatorStatics3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x36c753f9_7373_4e5e_9ba4_c3622a003c4e,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarSeparatorStatics3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsInOverflowProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub DynamicOverflowOrderProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarStatics {
type Vtable = IAppBarStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x79bb7e8d_dca9_4b5f_a448_37b13238ed76,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsOpenProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsStickyProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarStatics2 {
type Vtable = IAppBarStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x222355e9_0384_49de_8738_dfc9d409ac5d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ClosedDisplayModeProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarStatics4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarStatics4 {
type Vtable = IAppBarStatics4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarStatics4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xba02082e_1165_4451_94b3_eb3ac73e4196,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarStatics4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LightDismissOverlayModeProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButton(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButton {
type Vtable = IAppBarToggleButton_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButton {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x2e914438_fd53_4b8d_858b_3644269f8e4d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButton_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Label: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetLabel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub Icon: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetIcon: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButton3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButton3 {
type Vtable = IAppBarToggleButton3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButton3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xef9a85e5_16ff_4d72_b9e8_9b861eaf84a8,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButton3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LabelPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut CommandBarLabelPosition,
) -> ::windows_core::HRESULT,
pub SetLabelPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: CommandBarLabelPosition,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButton4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButton4 {
type Vtable = IAppBarToggleButton4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButton4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xb86b736e_3eaf_4751_a897_00029f1f6aca,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButton4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub KeyboardAcceleratorTextOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub SetKeyboardAcceleratorTextOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButton5(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButton5 {
type Vtable = IAppBarToggleButton5_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButton5 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x9dca3357_c130_4fb6_a1e2_d2b348fe43be,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButton5_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TemplateSettings: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButtonFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButtonFactory {
type Vtable = IAppBarToggleButtonFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButtonFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x028aa7d4_8f54_45a6_9f90_13605656d793,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButtonFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButtonStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButtonStatics {
type Vtable = IAppBarToggleButtonStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButtonStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfe5aaf96_7929_4da1_aa67_cddf73a3e4b5,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButtonStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub LabelProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IconProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsCompactProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Controls/Primitives/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Controls/Primitives/mod.rs | #[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarButtonTemplateSettings(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarButtonTemplateSettings {
type Vtable = IAppBarButtonTemplateSettings_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarButtonTemplateSettings {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xcbc9b39d_0c95_4951_bff2_13963691c366,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarButtonTemplateSettings_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub KeyboardAcceleratorTextMinWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarTemplateSettings(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarTemplateSettings {
type Vtable = IAppBarTemplateSettings_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarTemplateSettings {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xbcc2a863_eb35_423c_8389_d7827be3bf67,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarTemplateSettings_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ClipRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub CompactVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub CompactRootMargin: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Thickness,
) -> ::windows_core::HRESULT,
pub MinimalVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub MinimalRootMargin: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Thickness,
) -> ::windows_core::HRESULT,
pub HiddenVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub HiddenRootMargin: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Thickness,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarTemplateSettings2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarTemplateSettings2 {
type Vtable = IAppBarTemplateSettings2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarTemplateSettings2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xcbe66259_0399_5bcc_b925_4d5f5c9a4568,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarTemplateSettings2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub NegativeCompactVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub NegativeMinimalVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub NegativeHiddenVerticalDelta: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAppBarToggleButtonTemplateSettings(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAppBarToggleButtonTemplateSettings {
type Vtable = IAppBarToggleButtonTemplateSettings_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAppBarToggleButtonTemplateSettings {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xaaf99c48_d8f4_40d9_9fa3_3a64f0fec5d8,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppBarToggleButtonTemplateSettings_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub KeyboardAcceleratorTextMinWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IButtonBase(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IButtonBase {
type Vtable = IButtonBase_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IButtonBase {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfa002c1a_494e_46cf_91d4_e14a8d798674,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IButtonBase_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ClickMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::ClickMode,
) -> ::windows_core::HRESULT,
pub SetClickMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::ClickMode,
) -> ::windows_core::HRESULT,
pub IsPointerOver: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub IsPressed: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub Command: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetCommand: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CommandParameter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetCommandParameter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Click: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveClick: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IButtonBaseFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IButtonBaseFactory {
type Vtable = IButtonBaseFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IButtonBaseFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x389b7c71_5220_42b2_9992_2690c1a6702f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IButtonBaseFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IButtonBaseStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IButtonBaseStatics {
type Vtable = IButtonBaseStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IButtonBaseStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x67ef17e1_fe37_474f_9e97_3b5e0b30f2df,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IButtonBaseStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ClickModeProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsPointerOverProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsPressedProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CommandProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CommandParameterProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICalendarPanel(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICalendarPanel {
type Vtable = ICalendarPanel_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICalendarPanel {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfcd55a2d_02d3_4ee6_9a90_9df3ead00994,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarPanel_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICalendarViewTemplateSettings(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICalendarViewTemplateSettings {
type Vtable = ICalendarViewTemplateSettings_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICalendarViewTemplateSettings {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x56c71483_64e1_477c_8a0b_cb2f3334b9b0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICalendarViewTemplateSettings_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub MinViewWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub HeaderText: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay1: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay2: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay3: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay4: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay5: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay6: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub WeekDay7: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
pub HasMoreContentAfter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub HasMoreContentBefore: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub HasMoreViews: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub ClipRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub CenterX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub CenterY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICarouselPanel(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICarouselPanel {
type Vtable = ICarouselPanel_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICarouselPanel {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xdeab78b2_373b_4151_8785_e544d0d9362b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICarouselPanel_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CanVerticallyScroll: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetCanVerticallyScroll: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub CanHorizontallyScroll: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetCanHorizontallyScroll: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub ExtentWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub ExtentHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub ViewportWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub ViewportHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub HorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub VerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub ScrollOwner: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetScrollOwner: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LineUp: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LineDown: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LineLeft: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub LineRight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub PageUp: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub PageDown: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub PageLeft: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub PageRight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MouseWheelUp: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MouseWheelDown: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MouseWheelLeft: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MouseWheelRight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetHorizontalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
offset: f64,
) -> ::windows_core::HRESULT,
pub SetVerticalOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
offset: f64,
) -> ::windows_core::HRESULT,
pub MakeVisible: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
visual: *mut ::core::ffi::c_void,
rectangle: super::super::super::super::Foundation::Rect,
result__: *mut super::super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICarouselPanelFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICarouselPanelFactory {
type Vtable = ICarouselPanelFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICarouselPanelFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc1109404_9ae1_440e_a0dd_bbb6e2293cbe,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICarouselPanelFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorPickerSlider(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorPickerSlider {
type Vtable = IColorPickerSlider_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorPickerSlider {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x94394d83_e0df_4c5f_bbcd_8155f4020440,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorPickerSlider_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ColorChannel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::ColorPickerHsvChannel,
) -> ::windows_core::HRESULT,
pub SetColorChannel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::ColorPickerHsvChannel,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorPickerSliderFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorPickerSliderFactory {
type Vtable = IColorPickerSliderFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorPickerSliderFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x06d879a2_8c07_4b1e_a940_9fbce8f49639,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorPickerSliderFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorPickerSliderStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorPickerSliderStatics {
type Vtable = IColorPickerSliderStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorPickerSliderStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x22eafc6a_9fe3_4eee_8734_a1398ec4413a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorPickerSliderStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ColorChannelProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorSpectrum(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorSpectrum {
type Vtable = IColorSpectrum_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorSpectrum {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xce46f271_f509_4f98_8288_e4942fb385df,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorSpectrum_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Color: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Color,
) -> ::windows_core::HRESULT,
pub SetColor: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Color,
) -> ::windows_core::HRESULT,
HsvColor: usize,
SetHsvColor: usize,
pub MinHue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMinHue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub MaxHue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMaxHue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub MinSaturation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMinSaturation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub MaxSaturation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMaxSaturation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub MinValue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMinValue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub MaxValue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut i32,
) -> ::windows_core::HRESULT,
pub SetMaxValue: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: i32,
) -> ::windows_core::HRESULT,
pub Shape: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::ColorSpectrumShape,
) -> ::windows_core::HRESULT,
pub SetShape: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::ColorSpectrumShape,
) -> ::windows_core::HRESULT,
pub Components: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::ColorSpectrumComponents,
) -> ::windows_core::HRESULT,
pub SetComponents: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::ColorSpectrumComponents,
) -> ::windows_core::HRESULT,
pub ColorChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveColorChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorSpectrumFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorSpectrumFactory {
type Vtable = IColorSpectrumFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorSpectrumFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x90c7e61e_904d_42ab_b44f_e68dbf0cdee9,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorSpectrumFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IColorSpectrumStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IColorSpectrumStatics {
type Vtable = IColorSpectrumStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IColorSpectrumStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x906bee7c_2cee_4e90_968b_f0a5bd691b4a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IColorSpectrumStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub ColorProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub HsvColorProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MinHueProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MaxHueProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MinSaturationProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MaxSaturationProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MinValueProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub MaxValueProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ShapeProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ComponentsProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IComboBoxTemplateSettings(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IComboBoxTemplateSettings {
type Vtable = IComboBoxTemplateSettings_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IComboBoxTemplateSettings {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x83285c4e_17f6_4aa3_b61b_e87c718604ea,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IComboBoxTemplateSettings_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub DropDownOpenedHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub DropDownClosedHeight: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub DropDownOffset: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SelectedItemDirection: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut AnimationDirection,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IComboBoxTemplateSettings2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IComboBoxTemplateSettings2 {
type Vtable = IComboBoxTemplateSettings2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IComboBoxTemplateSettings2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x00e90cd7_68be_449d_b5a7_76e26f703e9b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IComboBoxTemplateSettings2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub DropDownContentMinWidth: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICommandBarFlyoutCommandBar(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICommandBarFlyoutCommandBar {
type Vtable = ICommandBarFlyoutCommandBar_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICommandBarFlyoutCommandBar {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x14146e7c_38c4_55c4_b706_ce18f6061e7e,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICommandBarFlyoutCommandBar_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub FlyoutTemplateSettings: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICommandBarFlyoutCommandBarFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICommandBarFlyoutCommandBarFactory {
type Vtable = ICommandBarFlyoutCommandBarFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICommandBarFlyoutCommandBarFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xf8236f9f_5559_5697_8e6f_20d70ca17dd0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICommandBarFlyoutCommandBarFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Input/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Input/mod.rs | #[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyDisplayDismissedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyDisplayDismissedEventArgs {
type Vtable = IAccessKeyDisplayDismissedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyDisplayDismissedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x8a610dc6_d72d_4ca8_9f66_556f35b513da,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyDisplayDismissedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyDisplayRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyDisplayRequestedEventArgs {
type Vtable = IAccessKeyDisplayRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyDisplayRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x0c079e55_13fe_4d03_a61d_e12f06567286,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyDisplayRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub PressedKeys: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyInvokedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyInvokedEventArgs {
type Vtable = IAccessKeyInvokedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyInvokedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xcfe9cd97_c718_4091_b7dd_adf1c072b1e1,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyInvokedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyManager(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyManager {
type Vtable = IAccessKeyManager_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyManager {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xecc973b0_2ee9_4b1c_98d7_6e0e816d334b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyManager_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyManagerStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyManagerStatics {
type Vtable = IAccessKeyManagerStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyManagerStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4ca0efe6_d9c8_4ebc_b4c7_30d1838a81f1,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyManagerStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub IsDisplayModeEnabled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub IsDisplayModeEnabledChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveIsDisplayModeEnabledChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub ExitDisplayMode: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAccessKeyManagerStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAccessKeyManagerStatics2 {
type Vtable = IAccessKeyManagerStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAccessKeyManagerStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x962bb594_2ab3_47c5_954b_7092f355f797,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAccessKeyManagerStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub AreKeyTipsEnabled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetAreKeyTipsEnabled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICanExecuteRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICanExecuteRequestedEventArgs {
type Vtable = ICanExecuteRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICanExecuteRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc8e75256_1950_505d_993b_75907ef96830,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICanExecuteRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Parameter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CanExecute: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetCanExecute: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICharacterReceivedRoutedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICharacterReceivedRoutedEventArgs {
type Vtable = ICharacterReceivedRoutedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICharacterReceivedRoutedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x7849fd82_48e4_444d_9419_93ab8892c107,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICharacterReceivedRoutedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Character: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut u16,
) -> ::windows_core::HRESULT,
pub KeyStatus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Core::CorePhysicalKeyStatus,
) -> ::windows_core::HRESULT,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICommand(::windows_core::IUnknown);
impl ICommand {}
::windows_core::imp::interface_hierarchy!(
ICommand, ::windows_core::IUnknown, ::windows_core::IInspectable
);
impl ::windows_core::RuntimeType for ICommand {
const SIGNATURE: ::windows_core::imp::ConstBuffer = ::windows_core::imp::ConstBuffer::from_slice(
b"{e5af3542-ca67-4081-995b-709dd13792df}",
);
}
unsafe impl ::windows_core::Interface for ICommand {
type Vtable = ICommand_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICommand {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xe5af3542_ca67_4081_995b_709dd13792df,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICommand_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CanExecuteChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveCanExecuteChanged: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub CanExecute: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
parameter: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub Execute: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
parameter: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IContextRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IContextRequestedEventArgs {
type Vtable = IContextRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IContextRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x42618e0a_1cb6_46fb_8374_0aec68aa5e51,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IContextRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub TryGetPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
relativeto: *mut ::core::ffi::c_void,
point: *mut super::super::super::Foundation::Point,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IDoubleTappedRoutedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IDoubleTappedRoutedEventArgs {
type Vtable = IDoubleTappedRoutedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IDoubleTappedRoutedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xaf404424_26df_44f4_8714_9359249b62d3,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDoubleTappedRoutedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
PointerDeviceType: usize,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub GetPosition: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
relativeto: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IExecuteRequestedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IExecuteRequestedEventArgs {
type Vtable = IExecuteRequestedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IExecuteRequestedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xe07fa734_a0b6_5755_9e87_24f54cca9372,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IExecuteRequestedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Parameter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFindNextElementOptions(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFindNextElementOptions {
type Vtable = IFindNextElementOptions_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFindNextElementOptions {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xd88ae22b_46c2_41fc_897e_b5961977b89d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFindNextElementOptions_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub SearchRoot: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetSearchRoot: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ExclusionRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub SetExclusionRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub HintRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub SetHintRect: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Rect,
) -> ::windows_core::HRESULT,
pub XYFocusNavigationStrategyOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut XYFocusNavigationStrategyOverride,
) -> ::windows_core::HRESULT,
pub SetXYFocusNavigationStrategyOverride: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: XYFocusNavigationStrategyOverride,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManager(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManager {
type Vtable = IFocusManager_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManager {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc843f50b_3b83_4da1_9d6f_557c1169f341,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManager_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerGotFocusEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerGotFocusEventArgs {
type Vtable = IFocusManagerGotFocusEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerGotFocusEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x97aa5d83_535b_507a_868e_62b706f06b61,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerGotFocusEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub NewFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CorrelationId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::windows_core::GUID,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerLostFocusEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerLostFocusEventArgs {
type Vtable = IFocusManagerLostFocusEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerLostFocusEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x3e157e7a_9578_5cd3_aaa8_051b3d391978,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerLostFocusEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub OldFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CorrelationId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::windows_core::GUID,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics {
type Vtable = IFocusManagerStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1eccd326_8182_4482_826a_0918e9ed9af7,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics2 {
type Vtable = IFocusManagerStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xa920d761_dd87_4f31_beda_ef417fe7c04a,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TryMoveFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics3 {
type Vtable = IFocusManagerStatics3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x60805ebf_b149_417d_83f1_baeb560e2a47,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub FindNextFocusableElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub FindNextFocusableElementWithHint: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
hintrect: super::super::super::Foundation::Rect,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics4(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics4 {
type Vtable = IFocusManagerStatics4_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics4 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x29276e9c_1c6c_414a_ba1c_96efd5962bcd,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics4_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TryMoveFocusWithOptions: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
focusnavigationoptions: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub FindNextElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub FindFirstFocusableElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
searchscope: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub FindLastFocusableElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
searchscope: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub FindNextElementWithOptions: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
focusnavigationoptions: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics5(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics5 {
type Vtable = IFocusManagerStatics5_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics5 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x280edc61_207a_4d7b_b98f_ce165e1b2015,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics5_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TryFocusAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
element: *mut ::core::ffi::c_void,
value: super::FocusState,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TryMoveFocusAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TryMoveFocusWithOptionsAsync: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
focusnavigationdirection: FocusNavigationDirection,
focusnavigationoptions: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics6(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics6 {
type Vtable = IFocusManagerStatics6_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics6 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x3546a1b6_20bf_5007_929d_e6d32e16afe4,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics6_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GotFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveGotFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub LostFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveLostFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub GettingFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveGettingFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub LosingFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveLosingFocus: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusManagerStatics7(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusManagerStatics7 {
type Vtable = IFocusManagerStatics7_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusManagerStatics7 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x95d6fa97_f0fc_5c32_b29d_07c04ec966b0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusManagerStatics7_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub GetFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
xamlroot: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFocusMovementResult(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFocusMovementResult {
type Vtable = IFocusMovementResult_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFocusMovementResult {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x06dfead3_c2ae_44bb_bfab_9c73de8407a4,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFocusMovementResult_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Succeeded: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IGettingFocusEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IGettingFocusEventArgs {
type Vtable = IGettingFocusEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IGettingFocusEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xfa05b9ce_c67c_4be8_8fd4_c44d67877e0d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGettingFocusEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub OldFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub NewFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetNewFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub FocusState: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::FocusState,
) -> ::windows_core::HRESULT,
pub Direction: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut FocusNavigationDirection,
) -> ::windows_core::HRESULT,
pub Handled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetHandled: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub InputDevice: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut FocusInputDeviceKind,
) -> ::windows_core::HRESULT,
pub Cancel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetCancel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IGettingFocusEventArgs2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IGettingFocusEventArgs2 {
type Vtable = IGettingFocusEventArgs2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IGettingFocusEventArgs2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x88754d7b_b4b9_4959_8bce_89bf212ed4eb,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGettingFocusEventArgs2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TryCancel: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub TrySetNewFocusedElement: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
element: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IGettingFocusEventArgs3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IGettingFocusEventArgs3 {
type Vtable = IGettingFocusEventArgs3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IGettingFocusEventArgs3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x4e024891_db3f_5e78_b75a_62bfc3510735,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IGettingFocusEventArgs3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CorrelationId: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::windows_core::GUID,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IHoldingRoutedEventArgs(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IHoldingRoutedEventArgs {
type Vtable = IHoldingRoutedEventArgs_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IHoldingRoutedEventArgs {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc246ff23_d80d_44de_8db9_0d815e269ac0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IHoldingRoutedEventArgs_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
PointerDeviceType: usize,
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Xaml/Media/mod.rs | lib/windows-ext/src/Windows/UI/Xaml/Media/mod.rs | #[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAcrylicBrush(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAcrylicBrush {
type Vtable = IAcrylicBrush_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAcrylicBrush {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x79bbcf4e_cd66_4f1b_a8b6_cd6d2977c18d,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAcrylicBrush_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub BackgroundSource: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut AcrylicBackgroundSource,
) -> ::windows_core::HRESULT,
pub SetBackgroundSource: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: AcrylicBackgroundSource,
) -> ::windows_core::HRESULT,
pub TintColor: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::Color,
) -> ::windows_core::HRESULT,
pub SetTintColor: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::Color,
) -> ::windows_core::HRESULT,
pub TintOpacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetTintOpacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub TintTransitionDuration: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::TimeSpan,
) -> ::windows_core::HRESULT,
pub SetTintTransitionDuration: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::TimeSpan,
) -> ::windows_core::HRESULT,
pub AlwaysUseFallback: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetAlwaysUseFallback: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAcrylicBrush2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAcrylicBrush2 {
type Vtable = IAcrylicBrush2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAcrylicBrush2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc9645383_b19e_5ac0_86ff_3d90506dbcda,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAcrylicBrush2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TintLuminosityOpacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetTintLuminosityOpacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAcrylicBrushFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAcrylicBrushFactory {
type Vtable = IAcrylicBrushFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAcrylicBrushFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x81a32568_f6cc_4013_8363_928ae23b7a61,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAcrylicBrushFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAcrylicBrushStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAcrylicBrushStatics {
type Vtable = IAcrylicBrushStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAcrylicBrushStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x2787fd79_a3da_423f_b81a_599147971523,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAcrylicBrushStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub BackgroundSourceProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TintColorProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TintOpacityProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TintTransitionDurationProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub AlwaysUseFallbackProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IAcrylicBrushStatics2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IAcrylicBrushStatics2 {
type Vtable = IAcrylicBrushStatics2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IAcrylicBrushStatics2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x129188a8_bf11_5bbc_8445_8c510e5926c0,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAcrylicBrushStatics2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub TintLuminosityOpacityProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IArcSegment(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IArcSegment {
type Vtable = IArcSegment_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IArcSegment {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x07940c5f_63fb_4469_91be_f1097c168052,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IArcSegment_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Point: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub SetPoint: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub Size: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Size,
) -> ::windows_core::HRESULT,
pub SetSize: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Size,
) -> ::windows_core::HRESULT,
pub RotationAngle: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetRotationAngle: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub IsLargeArc: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut bool,
) -> ::windows_core::HRESULT,
pub SetIsLargeArc: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: bool,
) -> ::windows_core::HRESULT,
pub SweepDirection: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut SweepDirection,
) -> ::windows_core::HRESULT,
pub SetSweepDirection: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: SweepDirection,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IArcSegmentStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IArcSegmentStatics {
type Vtable = IArcSegmentStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IArcSegmentStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x82348f6e_8a69_4204_9c12_7207df317643,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IArcSegmentStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub PointProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SizeProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RotationAngleProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub IsLargeArcProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SweepDirectionProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBezierSegment(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBezierSegment {
type Vtable = IBezierSegment_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBezierSegment {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xaf4bb9ee_8984_49b7_81df_3f35994b95eb,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBezierSegment_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Point1: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub SetPoint1: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub Point2: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub SetPoint2: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub Point3: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub SetPoint3: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBezierSegmentStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBezierSegmentStatics {
type Vtable = IBezierSegmentStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBezierSegmentStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc0287bac_1410_4530_8452_1c9d0ad1f341,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBezierSegmentStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Point1Property: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Point2Property: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub Point3Property: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBitmapCache(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBitmapCache {
type Vtable = IBitmapCache_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBitmapCache {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x79c2219e_44d2_4610_9735_9bec83809ecf,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBitmapCache_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrush(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrush {
type Vtable = IBrush_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrush {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x8806a321_1e06_422c_a1cc_01696559e021,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrush_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Opacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetOpacity: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub Transform: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetTransform: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RelativeTransform: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SetRelativeTransform: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrushFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrushFactory {
type Vtable = IBrushFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrushFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x399658a2_14fb_4b8f_83e6_6e3dab12069b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrushFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrushOverrides2(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrushOverrides2 {
type Vtable = IBrushOverrides2_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrushOverrides2 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xd092b151_d83b_5a81_a71e_a1c7f8ad6963,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrushOverrides2_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
PopulatePropertyInfoOverride: usize,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IBrushStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IBrushStatics {
type Vtable = IBrushStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IBrushStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xe70c3102_0225_47f5_b22e_0467619f6a22,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IBrushStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub OpacityProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TransformProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RelativeTransformProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICacheMode(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICacheMode {
type Vtable = ICacheMode_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICacheMode {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x98dc8b11_c6f9_4dab_b838_5fd5ec8c7350,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICacheMode_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICacheModeFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICacheModeFactory {
type Vtable = ICacheModeFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICacheModeFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xeb1f8c5b_0abb_4e70_b8a8_620d0d953ab2,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICacheModeFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstance: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICompositeTransform(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICompositeTransform {
type Vtable = ICompositeTransform_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICompositeTransform {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xc8a4385b_f24a_4701_a265_a78846f142b9,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICompositeTransform_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CenterX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetCenterX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub CenterY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetCenterY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub ScaleX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetScaleX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub ScaleY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetScaleY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub SkewX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetSkewX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub SkewY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetSkewY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub Rotation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetRotation: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub TranslateX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetTranslateX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub TranslateY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetTranslateY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICompositeTransformStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICompositeTransformStatics {
type Vtable = ICompositeTransformStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICompositeTransformStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x2f190c08_8266_496f_9653_a18bd4f836aa,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICompositeTransformStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CenterXProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub CenterYProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ScaleXProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub ScaleYProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SkewXProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub SkewYProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RotationProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TranslateXProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub TranslateYProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICompositionTarget(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICompositionTarget {
type Vtable = ICompositionTarget_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICompositionTarget {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x26cfbff0_713c_4bec_8803_e101f7b14ed3,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICompositionTarget_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICompositionTargetStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICompositionTargetStatics {
type Vtable = ICompositionTargetStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICompositionTargetStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x2b1af03d_1ed2_4b59_bd00_7594ee92832b,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICompositionTargetStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Rendering: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveRendering: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub SurfaceContentsLost: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveSurfaceContentsLost: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct ICompositionTargetStatics3(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for ICompositionTargetStatics3 {
type Vtable = ICompositionTargetStatics3_Vtbl;
}
unsafe impl ::windows_core::ComInterface for ICompositionTargetStatics3 {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xbc0a7cd9_6750_4708_994c_2028e0312ac8,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICompositionTargetStatics3_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Rendered: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
handler: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
pub RemoveRendered: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
token: super::super::super::Foundation::EventRegistrationToken,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IEllipseGeometry(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IEllipseGeometry {
type Vtable = IEllipseGeometry_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IEllipseGeometry {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xd4f61bba_4ea2_40d6_aa6c_8d38aa87651f,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IEllipseGeometry_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Center: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub SetCenter: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: super::super::super::Foundation::Point,
) -> ::windows_core::HRESULT,
pub RadiusX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetRadiusX: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
pub RadiusY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut f64,
) -> ::windows_core::HRESULT,
pub SetRadiusY: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
value: f64,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IEllipseGeometryStatics(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IEllipseGeometryStatics {
type Vtable = IEllipseGeometryStatics_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IEllipseGeometryStatics {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x1744db47_f635_4b16_aee6_e052a65defb2,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IEllipseGeometryStatics_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CenterProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RadiusXProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
pub RadiusYProperty: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFontFamily(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFontFamily {
type Vtable = IFontFamily_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFontFamily {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0x92467e64_d66a_4cf4_9322_3d23b3c0c361,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFontFamily_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub Source: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
result__: *mut ::std::mem::MaybeUninit<::windows_core::HSTRING>,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFontFamilyFactory(::windows_core::IUnknown);
unsafe impl ::windows_core::Interface for IFontFamilyFactory {
type Vtable = IFontFamilyFactory_Vtbl;
}
unsafe impl ::windows_core::ComInterface for IFontFamilyFactory {
const IID: ::windows_core::GUID = ::windows_core::GUID::from_u128(
0xd5603377_3dae_4dcd_af09_f9498e9ec659,
);
}
#[repr(C)]
#[doc(hidden)]
pub struct IFontFamilyFactory_Vtbl {
pub base__: ::windows_core::IInspectable_Vtbl,
pub CreateInstanceWithName: unsafe extern "system" fn(
this: *mut ::core::ffi::c_void,
familyname: ::std::mem::MaybeUninit<::windows_core::HSTRING>,
baseinterface: *mut ::core::ffi::c_void,
innerinterface: *mut *mut ::core::ffi::c_void,
result__: *mut *mut ::core::ffi::c_void,
) -> ::windows_core::HRESULT,
}
#[doc(hidden)]
#[repr(transparent)]
#[derive(
::core::cmp::PartialEq,
::core::cmp::Eq,
::core::fmt::Debug,
::core::clone::Clone
)]
pub struct IFontFamilyStatics2(::windows_core::IUnknown);
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | true |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Text/mod.rs | lib/windows-ext/src/Windows/UI/Text/mod.rs | pub use windows::UI::Text::*;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Input/mod.rs | lib/windows-ext/src/Windows/UI/Input/mod.rs | pub use windows::UI::Input::*;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/UI/Core/mod.rs | lib/windows-ext/src/Windows/UI/Core/mod.rs | pub use windows::UI::Core::*;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/Foundation/mod.rs | lib/windows-ext/src/Windows/Foundation/mod.rs | pub use windows::Foundation::*;
pub mod Collections; | rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
sidit77/rusty-twinkle-tray | https://github.com/sidit77/rusty-twinkle-tray/blob/4c28fca78561979829fd2c88b2f02cc162a2ae41/lib/windows-ext/src/Windows/Foundation/Collections/mod.rs | lib/windows-ext/src/Windows/Foundation/Collections/mod.rs | pub use windows::Foundation::Collections::*;
| rust | MIT | 4c28fca78561979829fd2c88b2f02cc162a2ae41 | 2026-01-04T20:20:01.545651Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.