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
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/tamil.rs
src/snowball/algorithms/tamil.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 10] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B99}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9E}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BA8}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BAE}", -1, -1, None), Among("\u{0BAF}", -1, -1, None), Among("\u{0BB5}", -1, -1, None), ]; static A_1: &'static [Among<Context>; 3] = &[ Among("\u{0BA8}\u{0BCD}\u{0BA4}\u{0BCD}", -1, -1, None), Among("\u{0BA8}\u{0BCD}", -1, -1, None), Among("\u{0BA8}\u{0BCD}\u{0BA4}", -1, -1, None), ]; static A_2: &'static [Among<Context>; 3] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_3: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_4: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_5: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_6: &'static [Among<Context>; 6] = &[ Among("\u{0BAF}", -1, -1, None), Among("\u{0BB0}", -1, -1, None), Among("\u{0BB2}", -1, -1, None), Among("\u{0BB3}", -1, -1, None), Among("\u{0BB4}", -1, -1, None), Among("\u{0BB5}", -1, -1, None), ]; static A_7: &'static [Among<Context>; 6] = &[ Among("\u{0B99}", -1, -1, None), Among("\u{0B9E}", -1, -1, None), Among("\u{0BA3}", -1, -1, None), Among("\u{0BA8}", -1, -1, None), Among("\u{0BA9}", -1, -1, None), Among("\u{0BAE}", -1, -1, None), ]; static A_8: &'static [Among<Context>; 3] = &[ Among("\u{0BB5}\u{0BCD}", -1, -1, None), Among("\u{0BAF}", -1, -1, None), Among("\u{0BB5}", -1, -1, None), ]; static A_9: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_10: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_11: &'static [Among<Context>; 3] = &[ Among("\u{0B85}", -1, -1, None), Among("\u{0B87}", -1, -1, None), Among("\u{0B89}", -1, -1, None), ]; static A_12: &'static [Among<Context>; 10] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B99}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9E}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BA8}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BAE}", -1, -1, None), Among("\u{0BAF}", -1, -1, None), Among("\u{0BB5}", -1, -1, None), ]; static A_13: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_14: &'static [Among<Context>; 3] = &[ Among("\u{0BC7}", -1, -1, None), Among("\u{0BCB}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), ]; static A_15: &'static [Among<Context>; 2] = &[ Among("\u{0BAA}\u{0BBF}", -1, -1, None), Among("\u{0BB5}\u{0BBF}", -1, -1, None), ]; static A_16: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_17: &'static [Among<Context>; 13] = &[ Among("\u{0BAA}\u{0B9F}\u{0BCD}\u{0B9F}\u{0BC1}", -1, -1, None), Among("\u{0BB5}\u{0BBF}\u{0B9F}\u{0BCD}\u{0B9F}\u{0BC1}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BC1}", -1, -1, None), Among("\u{0BB5}\u{0BBF}\u{0B9F}\u{0BC1}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BCD}\u{0B9F}\u{0BA4}\u{0BC1}", -1, -1, None), Among("\u{0BC6}\u{0BB2}\u{0BCD}\u{0BB2}\u{0BBE}\u{0BAE}\u{0BCD}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BCD}\u{0B9F}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BCD}\u{0B9F}\u{0BA3}", -1, -1, None), Among("\u{0BA4}\u{0BBE}\u{0BA9}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BBF}\u{0BA4}\u{0BBE}\u{0BA9}", 8, -1, None), Among("\u{0B95}\u{0BC1}\u{0BB0}\u{0BBF}\u{0BAF}", -1, -1, None), Among("\u{0BAA}\u{0B9F}\u{0BBF}", -1, -1, None), Among("\u{0BAA}\u{0BB1}\u{0BCD}\u{0BB1}\u{0BBF}", -1, -1, None), ]; static A_18: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_19: &'static [Among<Context>; 6] = &[ Among("\u{0B95}", -1, -1, None), Among("\u{0B9A}", -1, -1, None), Among("\u{0B9F}", -1, -1, None), Among("\u{0BA4}", -1, -1, None), Among("\u{0BAA}", -1, -1, None), Among("\u{0BB1}", -1, -1, None), ]; static A_20: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_21: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_22: &'static [Among<Context>; 2] = &[ Among("\u{0BAA}\u{0B9F}\u{0BC1}", -1, -1, None), Among("\u{0B95}\u{0BCA}\u{0BA3}\u{0BCD}\u{0B9F}\u{0BBF}\u{0BB0}\u{0BCD}", -1, -1, None), ]; static A_23: &'static [Among<Context>; 12] = &[ Among("\u{0B85}", -1, -1, None), Among("\u{0B86}", -1, -1, None), Among("\u{0B87}", -1, -1, None), Among("\u{0B88}", -1, -1, None), Among("\u{0B89}", -1, -1, None), Among("\u{0B8A}", -1, -1, None), Among("\u{0B8E}", -1, -1, None), Among("\u{0B8F}", -1, -1, None), Among("\u{0B90}", -1, -1, None), Among("\u{0B92}", -1, -1, None), Among("\u{0B93}", -1, -1, None), Among("\u{0B94}", -1, -1, None), ]; static A_24: &'static [Among<Context>; 8] = &[ Among("\u{0BC0}", -1, -1, None), Among("\u{0BC1}", -1, -1, None), Among("\u{0BC2}", -1, -1, None), Among("\u{0BC6}", -1, -1, None), Among("\u{0BC7}", -1, -1, None), Among("\u{0BC8}", -1, -1, None), Among("\u{0BBE}", -1, -1, None), Among("\u{0BBF}", -1, -1, None), ]; static A_25: &'static [Among<Context>; 6] = &[ Among("\u{0B95}\u{0BBF}\u{0BA9}\u{0BCD}\u{0BB1}\u{0BCD}", -1, -1, None), Among("\u{0BBE}\u{0BA8}\u{0BBF}\u{0BA9}\u{0BCD}\u{0BB1}\u{0BCD}", -1, -1, None), Among("\u{0B95}\u{0BBF}\u{0BB1}\u{0BCD}", -1, -1, None), Among("\u{0B95}\u{0BBF}\u{0BA9}\u{0BCD}\u{0BB1}", -1, -1, None), Among("\u{0BBE}\u{0BA8}\u{0BBF}\u{0BA9}\u{0BCD}\u{0BB1}", -1, -1, None), Among("\u{0B95}\u{0BBF}\u{0BB1}", -1, -1, None), ]; #[derive(Clone)] struct Context { i_length: usize, b_found_wrong_ending: bool, b_found_vetrumai_urupu: bool, b_found_a_match: bool, } fn r_has_min_length(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 104 context.i_length = env.current.chars().count(); if !(context.i_length > 4){ return false; } return true; } fn r_fix_va_start(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 109 // or, line 110 'lab0: loop { let v_1 = env.cursor; 'lab1: loop { // (, line 110 // and, line 110 let v_2 = env.cursor; // try, line 110 let v_3 = env.cursor; 'lab2: loop { // literal, line 110 if !env.eq_s(&"\u{0BB5}\u{0BCB}") { env.cursor = v_3; break 'lab2; } break 'lab2; } env.cursor = v_2; // [, line 110 env.bra = env.cursor; // literal, line 110 if !env.eq_s(&"\u{0BB5}\u{0BCB}") { break 'lab1; } // ], line 110 env.ket = env.cursor; // <-, line 110 if !env.slice_from("\u{0B93}") { return false; } break 'lab0; } env.cursor = v_1; 'lab3: loop { // (, line 111 // and, line 111 let v_4 = env.cursor; // try, line 111 let v_5 = env.cursor; 'lab4: loop { // literal, line 111 if !env.eq_s(&"\u{0BB5}\u{0BCA}") { env.cursor = v_5; break 'lab4; } break 'lab4; } env.cursor = v_4; // [, line 111 env.bra = env.cursor; // literal, line 111 if !env.eq_s(&"\u{0BB5}\u{0BCA}") { break 'lab3; } // ], line 111 env.ket = env.cursor; // <-, line 111 if !env.slice_from("\u{0B92}") { return false; } break 'lab0; } env.cursor = v_1; 'lab5: loop { // (, line 112 // and, line 112 let v_6 = env.cursor; // try, line 112 let v_7 = env.cursor; 'lab6: loop { // literal, line 112 if !env.eq_s(&"\u{0BB5}\u{0BC1}") { env.cursor = v_7; break 'lab6; } break 'lab6; } env.cursor = v_6; // [, line 112 env.bra = env.cursor; // literal, line 112 if !env.eq_s(&"\u{0BB5}\u{0BC1}") { break 'lab5; } // ], line 112 env.ket = env.cursor; // <-, line 112 if !env.slice_from("\u{0B89}") { return false; } break 'lab0; } env.cursor = v_1; // (, line 113 // and, line 113 let v_8 = env.cursor; // try, line 113 let v_9 = env.cursor; 'lab7: loop { // literal, line 113 if !env.eq_s(&"\u{0BB5}\u{0BC2}") { env.cursor = v_9; break 'lab7; } break 'lab7; } env.cursor = v_8; // [, line 113 env.bra = env.cursor; // literal, line 113 if !env.eq_s(&"\u{0BB5}\u{0BC2}") { return false; } // ], line 113 env.ket = env.cursor; // <-, line 113 if !env.slice_from("\u{0B8A}") { return false; } break 'lab0; } return true; } fn r_fix_endings(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 116 // set found_wrong_ending, line 117 context.b_found_wrong_ending = true; // repeat, line 118 'replab0: loop{ let v_1 = env.cursor; 'lab1: for _ in 0..1 { // (, line 118 // Boolean test found_wrong_ending, line 118 if !context.b_found_wrong_ending { break 'lab1; } // (, line 118 // do, line 118 let v_2 = env.cursor; 'lab2: loop { // call fix_ending, line 118 if !r_fix_ending(env, context) { break 'lab2; } break 'lab2; } env.cursor = v_2; continue 'replab0; } env.cursor = v_1; break 'replab0; } return true; } fn r_remove_question_prefixes(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 121 // [, line 122 env.bra = env.cursor; // (, line 122 // literal, line 122 if !env.eq_s(&"\u{0B8E}") { return false; } // among, line 122 if env.find_among(A_0, context) == 0 { return false; } // literal, line 122 if !env.eq_s(&"\u{0BCD}") { return false; } // ], line 122 env.ket = env.cursor; // delete, line 122 if !env.slice_del() { return false; } // do, line 123 let v_1 = env.cursor; 'lab0: loop { // call fix_va_start, line 123 if !r_fix_va_start(env, context) { break 'lab0; } break 'lab0; } env.cursor = v_1; return true; } fn r_fix_ending(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 126 // unset found_wrong_ending, line 127 context.b_found_wrong_ending = false; context.i_length = env.current.chars().count(); if !(context.i_length > 3){ return false; } // backwards, line 130 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 130 // or, line 132 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 131 // [, line 131 env.ket = env.cursor; // among, line 131 if env.find_among_b(A_1, context) == 0 { break 'lab1; } // ], line 131 env.bra = env.cursor; // delete, line 131 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab2: loop { // (, line 133 // [, line 133 env.ket = env.cursor; // literal, line 133 if !env.eq_s_b(&"\u{0BAF}\u{0BCD}") { break 'lab2; } // test, line 133 let v_2 = env.limit - env.cursor; // among, line 133 if env.find_among_b(A_2, context) == 0 { break 'lab2; } env.cursor = env.limit - v_2; // ], line 133 env.bra = env.cursor; // delete, line 133 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab3: loop { // (, line 135 // [, line 135 env.ket = env.cursor; // or, line 135 'lab4: loop { let v_3 = env.limit - env.cursor; 'lab5: loop { // literal, line 135 if !env.eq_s_b(&"\u{0B9F}\u{0BCD}\u{0BAA}\u{0BCD}") { break 'lab5; } break 'lab4; } env.cursor = env.limit - v_3; // literal, line 135 if !env.eq_s_b(&"\u{0B9F}\u{0BCD}\u{0B95}\u{0BCD}") { break 'lab3; } break 'lab4; } // ], line 135 env.bra = env.cursor; // <-, line 135 if !env.slice_from("\u{0BB3}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab6: loop { // (, line 137 // [, line 137 env.ket = env.cursor; // literal, line 137 if !env.eq_s_b(&"\u{0BA9}\u{0BCD}\u{0BB1}\u{0BCD}") { break 'lab6; } // ], line 137 env.bra = env.cursor; // <-, line 137 if !env.slice_from("\u{0BB2}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab7: loop { // (, line 140 // [, line 140 env.ket = env.cursor; // literal, line 140 if !env.eq_s_b(&"\u{0BB1}\u{0BCD}\u{0B95}\u{0BCD}") { break 'lab7; } // ], line 140 env.bra = env.cursor; // <-, line 140 if !env.slice_from("\u{0BB2}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab8: loop { // (, line 142 // [, line 142 env.ket = env.cursor; // literal, line 142 if !env.eq_s_b(&"\u{0B9F}\u{0BCD}\u{0B9F}\u{0BCD}") { break 'lab8; } // ], line 142 env.bra = env.cursor; // <-, line 142 if !env.slice_from("\u{0B9F}\u{0BC1}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab9: loop { // (, line 144 // Boolean test found_vetrumai_urupu, line 144 if !context.b_found_vetrumai_urupu { break 'lab9; } // [, line 144 env.ket = env.cursor; // literal, line 144 if !env.eq_s_b(&"\u{0BA4}\u{0BCD}\u{0BA4}\u{0BCD}") { break 'lab9; } // (, line 144 // test, line 144 let v_4 = env.limit - env.cursor; // not, line 144 let v_5 = env.limit - env.cursor; 'lab10: loop { // literal, line 144 if !env.eq_s_b(&"\u{0BC8}") { break 'lab10; } break 'lab9; } env.cursor = env.limit - v_5; env.cursor = env.limit - v_4; // ], line 144 env.bra = env.cursor; // <-, line 144 if !env.slice_from("\u{0BAE}\u{0BCD}") { return false; } // ], line 144 env.bra = env.cursor; break 'lab0; } env.cursor = env.limit - v_1; 'lab11: loop { // (, line 146 // [, line 146 env.ket = env.cursor; // or, line 146 'lab12: loop { let v_6 = env.limit - env.cursor; 'lab13: loop { // literal, line 146 if !env.eq_s_b(&"\u{0BC1}\u{0B95}\u{0BCD}") { break 'lab13; } break 'lab12; } env.cursor = env.limit - v_6; // literal, line 146 if !env.eq_s_b(&"\u{0BC1}\u{0B95}\u{0BCD}\u{0B95}\u{0BCD}") { break 'lab11; } break 'lab12; } // ], line 146 env.bra = env.cursor; // <-, line 146 if !env.slice_from("\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab14: loop { // (, line 148 // [, line 148 env.ket = env.cursor; // literal, line 148 if !env.eq_s_b(&"\u{0BCD}") { break 'lab14; } // among, line 148 if env.find_among_b(A_3, context) == 0 { break 'lab14; } // literal, line 148 if !env.eq_s_b(&"\u{0BCD}") { break 'lab14; } // among, line 148 if env.find_among_b(A_4, context) == 0 { break 'lab14; } // ], line 148 env.bra = env.cursor; // delete, line 148 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab15: loop { // (, line 150 // [, line 150 env.ket = env.cursor; // literal, line 150 if !env.eq_s_b(&"\u{0BC1}\u{0B95}\u{0BCD}") { break 'lab15; } // ], line 150 env.bra = env.cursor; // <-, line 150 if !env.slice_from("\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab16: loop { // (, line 152 // [, line 152 env.ket = env.cursor; // literal, line 152 if !env.eq_s_b(&"\u{0BCD}") { break 'lab16; } // among, line 152 if env.find_among_b(A_5, context) == 0 { break 'lab16; } // ], line 152 env.bra = env.cursor; // delete, line 152 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab17: loop { // (, line 154 // [, line 154 env.ket = env.cursor; // literal, line 154 if !env.eq_s_b(&"\u{0BCD}") { break 'lab17; } // (, line 154 // or, line 154 'lab18: loop { let v_7 = env.limit - env.cursor; 'lab19: loop { // among, line 154 if env.find_among_b(A_6, context) == 0 { break 'lab19; } break 'lab18; } env.cursor = env.limit - v_7; // among, line 154 if env.find_among_b(A_7, context) == 0 { break 'lab17; } break 'lab18; } // literal, line 154 if !env.eq_s_b(&"\u{0BCD}") { break 'lab17; } // ], line 154 env.bra = env.cursor; // <-, line 154 if !env.slice_from("\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab20: loop { // (, line 156 // [, line 156 env.ket = env.cursor; // among, line 156 if env.find_among_b(A_8, context) == 0 { break 'lab20; } // ], line 156 env.bra = env.cursor; // delete, line 156 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab21: loop { // (, line 158 // [, line 158 env.ket = env.cursor; // literal, line 158 if !env.eq_s_b(&"\u{0BA9}\u{0BC1}") { break 'lab21; } // (, line 158 // test, line 158 let v_8 = env.limit - env.cursor; // not, line 158 let v_9 = env.limit - env.cursor; 'lab22: loop { // among, line 158 if env.find_among_b(A_9, context) == 0 { break 'lab22; } break 'lab21; } env.cursor = env.limit - v_9; env.cursor = env.limit - v_8; // ], line 158 env.bra = env.cursor; // delete, line 158 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab23: loop { // (, line 160 // [, line 160 env.ket = env.cursor; // literal, line 160 if !env.eq_s_b(&"\u{0B99}\u{0BCD}") { break 'lab23; } // (, line 160 // test, line 160 let v_10 = env.limit - env.cursor; // not, line 160 let v_11 = env.limit - env.cursor; 'lab24: loop { // literal, line 160 if !env.eq_s_b(&"\u{0BC8}") { break 'lab24; } break 'lab23; } env.cursor = env.limit - v_11; env.cursor = env.limit - v_10; // ], line 160 env.bra = env.cursor; // <-, line 160 if !env.slice_from("\u{0BAE}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab25: loop { // (, line 162 // [, line 162 env.ket = env.cursor; // literal, line 162 if !env.eq_s_b(&"\u{0B99}\u{0BCD}") { break 'lab25; } // ], line 162 env.bra = env.cursor; // delete, line 162 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit - v_1; // (, line 164 // [, line 164 env.ket = env.cursor; // literal, line 164 if !env.eq_s_b(&"\u{0BCD}") { return false; } // (, line 164 // test, line 164 let v_12 = env.limit - env.cursor; // (, line 164 // or, line 164 'lab26: loop { let v_13 = env.limit - env.cursor; 'lab27: loop { // among, line 164 if env.find_among_b(A_10, context) == 0 { break 'lab27; } break 'lab26; } env.cursor = env.limit - v_13; // literal, line 164 if !env.eq_s_b(&"\u{0BCD}") { return false; } break 'lab26; } env.cursor = env.limit - v_12; // ], line 164 env.bra = env.cursor; // delete, line 164 if !env.slice_del() { return false; } break 'lab0; } env.cursor = env.limit_backward; // set found_wrong_ending, line 167 context.b_found_wrong_ending = true; return true; } fn r_remove_pronoun_prefixes(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 170 // unset found_a_match, line 171 context.b_found_a_match = false; // [, line 172 env.bra = env.cursor; // among, line 172 if env.find_among(A_11, context) == 0 { return false; } // among, line 172 if env.find_among(A_12, context) == 0 { return false; } // literal, line 172 if !env.eq_s(&"\u{0BCD}") { return false; } // ], line 172 env.ket = env.cursor; // delete, line 172 if !env.slice_del() { return false; } // (, line 173 // set found_a_match, line 173 context.b_found_a_match = true; // do, line 174 let v_1 = env.cursor; 'lab0: loop { // call fix_va_start, line 174 if !r_fix_va_start(env, context) { break 'lab0; } break 'lab0; } env.cursor = v_1; return true; } fn r_remove_plural_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 177 // unset found_a_match, line 178 context.b_found_a_match = false; // backwards, line 179 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 179 // or, line 180 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 180 // [, line 180 env.ket = env.cursor; // literal, line 180 if !env.eq_s_b(&"\u{0BC1}\u{0B99}\u{0BCD}\u{0B95}\u{0BB3}\u{0BCD}") { break 'lab1; } // (, line 180 // test, line 180 let v_2 = env.limit - env.cursor; // not, line 180 let v_3 = env.limit - env.cursor; 'lab2: loop { // among, line 180 if env.find_among_b(A_13, context) == 0 { break 'lab2; } break 'lab1; } env.cursor = env.limit - v_3; env.cursor = env.limit - v_2; // ], line 180 env.bra = env.cursor; // <-, line 180 if !env.slice_from("\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab3: loop { // (, line 181 // [, line 181 env.ket = env.cursor; // literal, line 181 if !env.eq_s_b(&"\u{0BB1}\u{0BCD}\u{0B95}\u{0BB3}\u{0BCD}") { break 'lab3; } // ], line 181 env.bra = env.cursor; // <-, line 181 if !env.slice_from("\u{0BB2}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; 'lab4: loop { // (, line 182 // [, line 182 env.ket = env.cursor; // literal, line 182 if !env.eq_s_b(&"\u{0B9F}\u{0BCD}\u{0B95}\u{0BB3}\u{0BCD}") { break 'lab4; } // ], line 182 env.bra = env.cursor; // <-, line 182 if !env.slice_from("\u{0BB3}\u{0BCD}") { return false; } break 'lab0; } env.cursor = env.limit - v_1; // (, line 183 // [, line 183 env.ket = env.cursor; // literal, line 183 if !env.eq_s_b(&"\u{0B95}\u{0BB3}\u{0BCD}") { return false; } // ], line 183 env.bra = env.cursor; // delete, line 183 if !env.slice_del() { return false; } break 'lab0; } // (, line 184 // set found_a_match, line 184 context.b_found_a_match = true; env.cursor = env.limit_backward; return true; } fn r_remove_question_suffixes(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 188 // call has_min_length, line 189 if !r_has_min_length(env, context) { return false; } // unset found_a_match, line 190 context.b_found_a_match = false; // backwards, line 191 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 191 // do, line 192 let v_1 = env.limit - env.cursor; 'lab0: loop { // (, line 192 // [, line 193 env.ket = env.cursor; // among, line 193 if env.find_among_b(A_14, context) == 0 { break 'lab0; } // ], line 193 env.bra = env.cursor; // <-, line 193 if !env.slice_from("\u{0BCD}") { return false; } // (, line 194 // set found_a_match, line 194 context.b_found_a_match = true; break 'lab0; } env.cursor = env.limit - v_1; env.cursor = env.limit_backward; // do, line 197 let v_2 = env.cursor; 'lab1: loop { // call fix_endings, line 197 if !r_fix_endings(env, context) { break 'lab1; } break 'lab1; } env.cursor = v_2; return true; }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
true
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/norwegian.rs
src/snowball/algorithms/norwegian.rs
//! This file was generated automatically by the Snowball to Rust compiler //! Snowball 2.0.0 - https://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 29] = &[ Among("a", -1, 1, None), Among("e", -1, 1, None), Among("ede", 1, 1, None), Among("ande", 1, 1, None), Among("ende", 1, 1, None), Among("ane", 1, 1, None), Among("ene", 1, 1, None), Among("hetene", 6, 1, None), Among("erte", 1, 3, None), Among("en", -1, 1, None), Among("heten", 9, 1, None), Among("ar", -1, 1, None), Among("er", -1, 1, None), Among("heter", 12, 1, None), Among("s", -1, 2, None), Among("as", 14, 1, None), Among("es", 14, 1, None), Among("edes", 16, 1, None), Among("endes", 16, 1, None), Among("enes", 16, 1, None), Among("hetenes", 19, 1, None), Among("ens", 14, 1, None), Among("hetens", 21, 1, None), Among("ers", 14, 1, None), Among("ets", 14, 1, None), Among("et", -1, 1, None), Among("het", 25, 1, None), Among("ert", -1, 3, None), Among("ast", -1, 1, None), ]; static A_1: &'static [Among<Context>; 2] = &[ Among("dt", -1, -1, None), Among("vt", -1, -1, None), ]; static A_2: &'static [Among<Context>; 11] = &[ Among("leg", -1, 1, None), Among("eleg", 0, 1, None), Among("ig", -1, 1, None), Among("eig", 2, 1, None), Among("lig", 2, 1, None), Among("elig", 4, 1, None), Among("els", -1, 1, None), Among("lov", -1, 1, None), Among("elov", 7, 1, None), Among("slov", 7, 1, None), Among("hetslov", 9, 1, None), ]; static G_v: &'static [u8; 19] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 48, 0, 128]; static G_s_ending: &'static [u8; 4] = &[119, 125, 149, 1]; #[derive(Clone)] struct Context { i_x: usize, i_p1: usize, } fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool { context.i_p1 = env.limit; let v_1 = env.cursor; let c = env.byte_index_for_hop(3); if 0 as i32 > c || c > env.limit as i32 { return false; } env.cursor = c as usize; context.i_x = env.cursor; env.cursor = v_1; 'golab0: loop { let v_2 = env.cursor; 'lab1: loop { if !env.in_grouping(G_v, 97, 248) { break 'lab1; } env.cursor = v_2; break 'golab0; } env.cursor = v_2; if env.cursor >= env.limit { return false; } env.next_char(); } 'golab2: loop { 'lab3: loop { if !env.out_grouping(G_v, 97, 248) { break 'lab3; } break 'golab2; } if env.cursor >= env.limit { return false; } env.next_char(); } context.i_p1 = env.cursor; 'lab4: loop { if !(context.i_p1 < context.i_x){ break 'lab4; } context.i_p1 = context.i_x; break 'lab4; } return true; } fn r_main_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; if env.cursor < context.i_p1 { return false; } let v_2 = env.limit_backward; env.limit_backward = context.i_p1; env.ket = env.cursor; among_var = env.find_among_b(A_0, context); if among_var == 0 { env.limit_backward = v_2; return false; } env.bra = env.cursor; env.limit_backward = v_2; if among_var == 1 { if !env.slice_del() { return false; } } else if among_var == 2 { 'lab0: loop { let v_3 = env.limit - env.cursor; 'lab1: loop { if !env.in_grouping_b(G_s_ending, 98, 122) { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_3; if !env.eq_s_b(&"k") { return false; } if !env.out_grouping_b(G_v, 97, 248) { return false; } break 'lab0; } if !env.slice_del() { return false; } } else if among_var == 3 { if !env.slice_from("er") { return false; } } return true; } fn r_consonant_pair(env: &mut SnowballEnv, context: &mut Context) -> bool { let v_1 = env.limit - env.cursor; if env.cursor < context.i_p1 { return false; } let v_3 = env.limit_backward; env.limit_backward = context.i_p1; env.ket = env.cursor; if env.find_among_b(A_1, context) == 0 { env.limit_backward = v_3; return false; } env.bra = env.cursor; env.limit_backward = v_3; env.cursor = env.limit - v_1; if env.cursor <= env.limit_backward { return false; } env.previous_char(); env.bra = env.cursor; if !env.slice_del() { return false; } return true; } fn r_other_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { if env.cursor < context.i_p1 { return false; } let v_2 = env.limit_backward; env.limit_backward = context.i_p1; env.ket = env.cursor; if env.find_among_b(A_2, context) == 0 { env.limit_backward = v_2; return false; } env.bra = env.cursor; env.limit_backward = v_2; if !env.slice_del() { return false; } return true; } pub fn stem(env: &mut SnowballEnv) -> bool { let mut context = &mut Context { i_x: 0, i_p1: 0, }; let v_1 = env.cursor; r_mark_regions(env, context); env.cursor = v_1; env.limit_backward = env.cursor; env.cursor = env.limit; let v_2 = env.limit - env.cursor; r_main_suffix(env, context); env.cursor = env.limit - v_2; let v_3 = env.limit - env.cursor; r_consonant_pair(env, context); env.cursor = env.limit - v_3; let v_4 = env.limit - env.cursor; r_other_suffix(env, context); env.cursor = env.limit - v_4; env.cursor = env.limit_backward; return true; }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
false
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/dutch.rs
src/snowball/algorithms/dutch.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 11] = &[ Among("", -1, 6, None), Among("\u{00E1}", 0, 1, None), Among("\u{00E4}", 0, 1, None), Among("\u{00E9}", 0, 2, None), Among("\u{00EB}", 0, 2, None), Among("\u{00ED}", 0, 3, None), Among("\u{00EF}", 0, 3, None), Among("\u{00F3}", 0, 4, None), Among("\u{00F6}", 0, 4, None), Among("\u{00FA}", 0, 5, None), Among("\u{00FC}", 0, 5, None), ]; static A_1: &'static [Among<Context>; 3] = &[ Among("", -1, 3, None), Among("I", 0, 2, None), Among("Y", 0, 1, None), ]; static A_2: &'static [Among<Context>; 3] = &[ Among("dd", -1, -1, None), Among("kk", -1, -1, None), Among("tt", -1, -1, None), ]; static A_3: &'static [Among<Context>; 5] = &[ Among("ene", -1, 2, None), Among("se", -1, 3, None), Among("en", -1, 2, None), Among("heden", 2, 1, None), Among("s", -1, 3, None), ]; static A_4: &'static [Among<Context>; 6] = &[ Among("end", -1, 1, None), Among("ig", -1, 2, None), Among("ing", -1, 1, None), Among("lijk", -1, 3, None), Among("baar", -1, 4, None), Among("bar", -1, 5, None), ]; static A_5: &'static [Among<Context>; 4] = &[ Among("aa", -1, -1, None), Among("ee", -1, -1, None), Among("oo", -1, -1, None), Among("uu", -1, -1, None), ]; static G_v: &'static [u8; 17] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]; static G_v_I: &'static [u8; 20] = &[1, 0, 0, 17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]; static G_v_j: &'static [u8; 17] = &[17, 67, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]; #[derive(Clone)] struct Context { i_p2: usize, i_p1: usize, b_e_found: bool, } fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 41 // test, line 42 let v_1 = env.cursor; // repeat, line 42 'replab0: loop{ let v_2 = env.cursor; 'lab1: for _ in 0..1 { // (, line 42 // [, line 43 env.bra = env.cursor; // substring, line 43 among_var = env.find_among(A_0, context); if among_var == 0 { break 'lab1; } // ], line 43 env.ket = env.cursor; if among_var == 0 { break 'lab1; } else if among_var == 1 { // (, line 45 // <-, line 45 if !env.slice_from("a") { return false; } } else if among_var == 2 { // (, line 47 // <-, line 47 if !env.slice_from("e") { return false; } } else if among_var == 3 { // (, line 49 // <-, line 49 if !env.slice_from("i") { return false; } } else if among_var == 4 { // (, line 51 // <-, line 51 if !env.slice_from("o") { return false; } } else if among_var == 5 { // (, line 53 // <-, line 53 if !env.slice_from("u") { return false; } } else if among_var == 6 { // (, line 54 // next, line 54 if env.cursor >= env.limit { break 'lab1; } env.next_char(); } continue 'replab0; } env.cursor = v_2; break 'replab0; } env.cursor = v_1; // try, line 57 let v_3 = env.cursor; 'lab2: loop { // (, line 57 // [, line 57 env.bra = env.cursor; // literal, line 57 if !env.eq_s(&"y") { env.cursor = v_3; break 'lab2; } // ], line 57 env.ket = env.cursor; // <-, line 57 if !env.slice_from("Y") { return false; } break 'lab2; } // repeat, line 58 'replab3: loop{ let v_4 = env.cursor; 'lab4: for _ in 0..1 { // goto, line 58 'golab5: loop { let v_5 = env.cursor; 'lab6: loop { // (, line 58 if !env.in_grouping(G_v, 97, 232) { break 'lab6; } // [, line 59 env.bra = env.cursor; // or, line 59 'lab7: loop { let v_6 = env.cursor; 'lab8: loop { // (, line 59 // literal, line 59 if !env.eq_s(&"i") { break 'lab8; } // ], line 59 env.ket = env.cursor; if !env.in_grouping(G_v, 97, 232) { break 'lab8; } // <-, line 59 if !env.slice_from("I") { return false; } break 'lab7; } env.cursor = v_6; // (, line 60 // literal, line 60 if !env.eq_s(&"y") { break 'lab6; } // ], line 60 env.ket = env.cursor; // <-, line 60 if !env.slice_from("Y") { return false; } break 'lab7; } env.cursor = v_5; break 'golab5; } env.cursor = v_5; if env.cursor >= env.limit { break 'lab4; } env.next_char(); } continue 'replab3; } env.cursor = v_4; break 'replab3; } return true; } fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 64 context.i_p1 = env.limit; context.i_p2 = env.limit; // gopast, line 69 'golab0: loop { 'lab1: loop { if !env.in_grouping(G_v, 97, 232) { break 'lab1; } break 'golab0; } if env.cursor >= env.limit { return false; } env.next_char(); } // gopast, line 69 'golab2: loop { 'lab3: loop { if !env.out_grouping(G_v, 97, 232) { break 'lab3; } break 'golab2; } if env.cursor >= env.limit { return false; } env.next_char(); } // setmark p1, line 69 context.i_p1 = env.cursor; // try, line 70 'lab4: loop { // (, line 70 if !(context.i_p1 < 3){ break 'lab4; } context.i_p1 = 3; break 'lab4; } // gopast, line 71 'golab5: loop { 'lab6: loop { if !env.in_grouping(G_v, 97, 232) { break 'lab6; } break 'golab5; } if env.cursor >= env.limit { return false; } env.next_char(); } // gopast, line 71 'golab7: loop { 'lab8: loop { if !env.out_grouping(G_v, 97, 232) { break 'lab8; } break 'golab7; } if env.cursor >= env.limit { return false; } env.next_char(); } // setmark p2, line 71 context.i_p2 = env.cursor; return true; } fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // repeat, line 75 'replab0: loop{ let v_1 = env.cursor; 'lab1: for _ in 0..1 { // (, line 75 // [, line 77 env.bra = env.cursor; // substring, line 77 among_var = env.find_among(A_1, context); if among_var == 0 { break 'lab1; } // ], line 77 env.ket = env.cursor; if among_var == 0 { break 'lab1; } else if among_var == 1 { // (, line 78 // <-, line 78 if !env.slice_from("y") { return false; } } else if among_var == 2 { // (, line 79 // <-, line 79 if !env.slice_from("i") { return false; } } else if among_var == 3 { // (, line 80 // next, line 80 if env.cursor >= env.limit { break 'lab1; } env.next_char(); } continue 'replab0; } env.cursor = v_1; break 'replab0; } return true; } fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p1 <= env.cursor){ return false; } return true; } fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p2 <= env.cursor){ return false; } return true; } fn r_undouble(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 90 // test, line 91 let v_1 = env.limit - env.cursor; // among, line 91 if env.find_among_b(A_2, context) == 0 { return false; } env.cursor = env.limit - v_1; // [, line 91 env.ket = env.cursor; // next, line 91 if env.cursor <= env.limit_backward { return false; } env.previous_char(); // ], line 91 env.bra = env.cursor; // delete, line 91 if !env.slice_del() { return false; } return true; } fn r_e_ending(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 94 // unset e_found, line 95 context.b_e_found = false; // [, line 96 env.ket = env.cursor; // literal, line 96 if !env.eq_s_b(&"e") { return false; } // ], line 96 env.bra = env.cursor; // call R1, line 96 if !r_R1(env, context) { return false; } // test, line 96 let v_1 = env.limit - env.cursor; if !env.out_grouping_b(G_v, 97, 232) { return false; } env.cursor = env.limit - v_1; // delete, line 96 if !env.slice_del() { return false; } // set e_found, line 97 context.b_e_found = true; // call undouble, line 98 if !r_undouble(env, context) { return false; } return true; } fn r_en_ending(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 101 // call R1, line 102 if !r_R1(env, context) { return false; } // and, line 102 let v_1 = env.limit - env.cursor; if !env.out_grouping_b(G_v, 97, 232) { return false; } env.cursor = env.limit - v_1; // not, line 102 let v_2 = env.limit - env.cursor; 'lab0: loop { // literal, line 102 if !env.eq_s_b(&"gem") { break 'lab0; } return false; } env.cursor = env.limit - v_2; // delete, line 102 if !env.slice_del() { return false; } // call undouble, line 103 if !r_undouble(env, context) { return false; } return true; } fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 106 // do, line 107 let v_1 = env.limit - env.cursor; 'lab0: loop { // (, line 107 // [, line 108 env.ket = env.cursor; // substring, line 108 among_var = env.find_among_b(A_3, context); if among_var == 0 { break 'lab0; } // ], line 108 env.bra = env.cursor; if among_var == 0 { break 'lab0; } else if among_var == 1 { // (, line 110 // call R1, line 110 if !r_R1(env, context) { break 'lab0; } // <-, line 110 if !env.slice_from("heid") { return false; } } else if among_var == 2 { // (, line 113 // call en_ending, line 113 if !r_en_ending(env, context) { break 'lab0; } } else if among_var == 3 { // (, line 116 // call R1, line 116 if !r_R1(env, context) { break 'lab0; } if !env.out_grouping_b(G_v_j, 97, 232) { break 'lab0; } // delete, line 116 if !env.slice_del() { return false; } } break 'lab0; } env.cursor = env.limit - v_1; // do, line 120 let v_2 = env.limit - env.cursor; 'lab1: loop { // call e_ending, line 120 if !r_e_ending(env, context) { break 'lab1; } break 'lab1; } env.cursor = env.limit - v_2; // do, line 122 let v_3 = env.limit - env.cursor; 'lab2: loop { // (, line 122 // [, line 122 env.ket = env.cursor; // literal, line 122 if !env.eq_s_b(&"heid") { break 'lab2; } // ], line 122 env.bra = env.cursor; // call R2, line 122 if !r_R2(env, context) { break 'lab2; } // not, line 122 let v_4 = env.limit - env.cursor; 'lab3: loop { // literal, line 122 if !env.eq_s_b(&"c") { break 'lab3; } break 'lab2; } env.cursor = env.limit - v_4; // delete, line 122 if !env.slice_del() { return false; } // [, line 123 env.ket = env.cursor; // literal, line 123 if !env.eq_s_b(&"en") { break 'lab2; } // ], line 123 env.bra = env.cursor; // call en_ending, line 123 if !r_en_ending(env, context) { break 'lab2; } break 'lab2; } env.cursor = env.limit - v_3; // do, line 126 let v_5 = env.limit - env.cursor; 'lab4: loop { // (, line 126 // [, line 127 env.ket = env.cursor; // substring, line 127 among_var = env.find_among_b(A_4, context); if among_var == 0 { break 'lab4; } // ], line 127 env.bra = env.cursor; if among_var == 0 { break 'lab4; } else if among_var == 1 { // (, line 129 // call R2, line 129 if !r_R2(env, context) { break 'lab4; } // delete, line 129 if !env.slice_del() { return false; } // or, line 130 'lab5: loop { let v_6 = env.limit - env.cursor; 'lab6: loop { // (, line 130 // [, line 130 env.ket = env.cursor; // literal, line 130 if !env.eq_s_b(&"ig") { break 'lab6; } // ], line 130 env.bra = env.cursor; // call R2, line 130 if !r_R2(env, context) { break 'lab6; } // not, line 130 let v_7 = env.limit - env.cursor; 'lab7: loop { // literal, line 130 if !env.eq_s_b(&"e") { break 'lab7; } break 'lab6; } env.cursor = env.limit - v_7; // delete, line 130 if !env.slice_del() { return false; } break 'lab5; } env.cursor = env.limit - v_6; // call undouble, line 130 if !r_undouble(env, context) { break 'lab4; } break 'lab5; } } else if among_var == 2 { // (, line 133 // call R2, line 133 if !r_R2(env, context) { break 'lab4; } // not, line 133 let v_8 = env.limit - env.cursor; 'lab8: loop { // literal, line 133 if !env.eq_s_b(&"e") { break 'lab8; } break 'lab4; } env.cursor = env.limit - v_8; // delete, line 133 if !env.slice_del() { return false; } } else if among_var == 3 { // (, line 136 // call R2, line 136 if !r_R2(env, context) { break 'lab4; } // delete, line 136 if !env.slice_del() { return false; } // call e_ending, line 136 if !r_e_ending(env, context) { break 'lab4; } } else if among_var == 4 { // (, line 139 // call R2, line 139 if !r_R2(env, context) { break 'lab4; } // delete, line 139 if !env.slice_del() { return false; } } else if among_var == 5 { // (, line 142 // call R2, line 142 if !r_R2(env, context) { break 'lab4; } // Boolean test e_found, line 142 if !context.b_e_found { break 'lab4; } // delete, line 142 if !env.slice_del() { return false; } } break 'lab4; } env.cursor = env.limit - v_5; // do, line 146 let v_9 = env.limit - env.cursor; 'lab9: loop { // (, line 146 if !env.out_grouping_b(G_v_I, 73, 232) { break 'lab9; } // test, line 148 let v_10 = env.limit - env.cursor; // (, line 148 // among, line 149 if env.find_among_b(A_5, context) == 0 { break 'lab9; } if !env.out_grouping_b(G_v, 97, 232) { break 'lab9; } env.cursor = env.limit - v_10; // [, line 152 env.ket = env.cursor; // next, line 152 if env.cursor <= env.limit_backward { break 'lab9; } env.previous_char(); // ], line 152 env.bra = env.cursor; // delete, line 152 if !env.slice_del() { return false; } break 'lab9; } env.cursor = env.limit - v_9; return true; } pub fn stem(env: &mut SnowballEnv) -> bool { let mut context = &mut Context { i_p2: 0, i_p1: 0, b_e_found: false, }; // (, line 157 // do, line 159 let v_1 = env.cursor; 'lab0: loop { // call prelude, line 159 if !r_prelude(env, context) { break 'lab0; } break 'lab0; } env.cursor = v_1; // do, line 160 let v_2 = env.cursor; 'lab1: loop { // call mark_regions, line 160 if !r_mark_regions(env, context) { break 'lab1; } break 'lab1; } env.cursor = v_2; // backwards, line 161 env.limit_backward = env.cursor; env.cursor = env.limit; // do, line 162 let v_3 = env.limit - env.cursor; 'lab2: loop { // call standard_suffix, line 162 if !r_standard_suffix(env, context) { break 'lab2; } break 'lab2; } env.cursor = env.limit - v_3; env.cursor = env.limit_backward; // do, line 163 let v_4 = env.cursor; 'lab3: loop { // call postlude, line 163 if !r_postlude(env, context) { break 'lab3; } break 'lab3; } env.cursor = v_4; return true; }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
false
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/english.rs
src/snowball/algorithms/english.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 3] = &[ Among("arsen", -1, -1, None), Among("commun", -1, -1, None), Among("gener", -1, -1, None), ]; static A_1: &'static [Among<Context>; 3] = &[ Among("'", -1, 1, None), Among("'s'", 0, 1, None), Among("'s", -1, 1, None), ]; static A_2: &'static [Among<Context>; 6] = &[ Among("ied", -1, 2, None), Among("s", -1, 3, None), Among("ies", 1, 2, None), Among("sses", 1, 1, None), Among("ss", 1, -1, None), Among("us", 1, -1, None), ]; static A_3: &'static [Among<Context>; 13] = &[ Among("", -1, 3, None), Among("bb", 0, 2, None), Among("dd", 0, 2, None), Among("ff", 0, 2, None), Among("gg", 0, 2, None), Among("bl", 0, 1, None), Among("mm", 0, 2, None), Among("nn", 0, 2, None), Among("pp", 0, 2, None), Among("rr", 0, 2, None), Among("at", 0, 1, None), Among("tt", 0, 2, None), Among("iz", 0, 1, None), ]; static A_4: &'static [Among<Context>; 6] = &[ Among("ed", -1, 2, None), Among("eed", 0, 1, None), Among("ing", -1, 2, None), Among("edly", -1, 2, None), Among("eedly", 3, 1, None), Among("ingly", -1, 2, None), ]; static A_5: &'static [Among<Context>; 24] = &[ Among("anci", -1, 3, None), Among("enci", -1, 2, None), Among("ogi", -1, 13, None), Among("li", -1, 16, None), Among("bli", 3, 12, None), Among("abli", 4, 4, None), Among("alli", 3, 8, None), Among("fulli", 3, 14, None), Among("lessli", 3, 15, None), Among("ousli", 3, 10, None), Among("entli", 3, 5, None), Among("aliti", -1, 8, None), Among("biliti", -1, 12, None), Among("iviti", -1, 11, None), Among("tional", -1, 1, None), Among("ational", 14, 7, None), Among("alism", -1, 8, None), Among("ation", -1, 7, None), Among("ization", 17, 6, None), Among("izer", -1, 6, None), Among("ator", -1, 7, None), Among("iveness", -1, 11, None), Among("fulness", -1, 9, None), Among("ousness", -1, 10, None), ]; static A_6: &'static [Among<Context>; 9] = &[ Among("icate", -1, 4, None), Among("ative", -1, 6, None), Among("alize", -1, 3, None), Among("iciti", -1, 4, None), Among("ical", -1, 4, None), Among("tional", -1, 1, None), Among("ational", 5, 2, None), Among("ful", -1, 5, None), Among("ness", -1, 5, None), ]; static A_7: &'static [Among<Context>; 18] = &[ Among("ic", -1, 1, None), Among("ance", -1, 1, None), Among("ence", -1, 1, None), Among("able", -1, 1, None), Among("ible", -1, 1, None), Among("ate", -1, 1, None), Among("ive", -1, 1, None), Among("ize", -1, 1, None), Among("iti", -1, 1, None), Among("al", -1, 1, None), Among("ism", -1, 1, None), Among("ion", -1, 2, None), Among("er", -1, 1, None), Among("ous", -1, 1, None), Among("ant", -1, 1, None), Among("ent", -1, 1, None), Among("ment", 15, 1, None), Among("ement", 16, 1, None), ]; static A_8: &'static [Among<Context>; 2] = &[ Among("e", -1, 1, None), Among("l", -1, 2, None), ]; static A_9: &'static [Among<Context>; 8] = &[ Among("succeed", -1, -1, None), Among("proceed", -1, -1, None), Among("exceed", -1, -1, None), Among("canning", -1, -1, None), Among("inning", -1, -1, None), Among("earring", -1, -1, None), Among("herring", -1, -1, None), Among("outing", -1, -1, None), ]; static A_10: &'static [Among<Context>; 18] = &[ Among("andes", -1, -1, None), Among("atlas", -1, -1, None), Among("bias", -1, -1, None), Among("cosmos", -1, -1, None), Among("dying", -1, 3, None), Among("early", -1, 9, None), Among("gently", -1, 7, None), Among("howe", -1, -1, None), Among("idly", -1, 6, None), Among("lying", -1, 4, None), Among("news", -1, -1, None), Among("only", -1, 10, None), Among("singly", -1, 11, None), Among("skies", -1, 2, None), Among("skis", -1, 1, None), Among("sky", -1, -1, None), Among("tying", -1, 5, None), Among("ugly", -1, 8, None), ]; static G_v: &'static [u8; 4] = &[17, 65, 16, 1]; static G_v_WXY: &'static [u8; 5] = &[1, 17, 65, 208, 1]; static G_valid_LI: &'static [u8; 3] = &[55, 141, 2]; #[derive(Clone)] struct Context { b_Y_found: bool, i_p2: usize, i_p1: usize, } fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 25 // unset Y_found, line 26 context.b_Y_found = false; // do, line 27 let v_1 = env.cursor; 'lab0: loop { // (, line 27 // [, line 27 env.bra = env.cursor; // literal, line 27 if !env.eq_s(&"'") { break 'lab0; } // ], line 27 env.ket = env.cursor; // delete, line 27 if !env.slice_del() { return false; } break 'lab0; } env.cursor = v_1; // do, line 28 let v_2 = env.cursor; 'lab1: loop { // (, line 28 // [, line 28 env.bra = env.cursor; // literal, line 28 if !env.eq_s(&"y") { break 'lab1; } // ], line 28 env.ket = env.cursor; // <-, line 28 if !env.slice_from("Y") { return false; } // set Y_found, line 28 context.b_Y_found = true; break 'lab1; } env.cursor = v_2; // do, line 29 let v_3 = env.cursor; 'lab2: loop { // repeat, line 29 'replab3: loop{ let v_4 = env.cursor; 'lab4: for _ in 0..1 { // (, line 29 // goto, line 29 'golab5: loop { let v_5 = env.cursor; 'lab6: loop { // (, line 29 if !env.in_grouping(G_v, 97, 121) { break 'lab6; } // [, line 29 env.bra = env.cursor; // literal, line 29 if !env.eq_s(&"y") { break 'lab6; } // ], line 29 env.ket = env.cursor; env.cursor = v_5; break 'golab5; } env.cursor = v_5; if env.cursor >= env.limit { break 'lab4; } env.next_char(); } // <-, line 29 if !env.slice_from("Y") { return false; } // set Y_found, line 29 context.b_Y_found = true; continue 'replab3; } env.cursor = v_4; break 'replab3; } break 'lab2; } env.cursor = v_3; return true; } fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 32 context.i_p1 = env.limit; context.i_p2 = env.limit; // do, line 35 let v_1 = env.cursor; 'lab0: loop { // (, line 35 // or, line 41 'lab1: loop { let v_2 = env.cursor; 'lab2: loop { // among, line 36 if env.find_among(A_0, context) == 0 { break 'lab2; } break 'lab1; } env.cursor = v_2; // (, line 41 // gopast, line 41 'golab3: loop { 'lab4: loop { if !env.in_grouping(G_v, 97, 121) { break 'lab4; } break 'golab3; } if env.cursor >= env.limit { break 'lab0; } env.next_char(); } // gopast, line 41 'golab5: loop { 'lab6: loop { if !env.out_grouping(G_v, 97, 121) { break 'lab6; } break 'golab5; } if env.cursor >= env.limit { break 'lab0; } env.next_char(); } break 'lab1; } // setmark p1, line 42 context.i_p1 = env.cursor; // gopast, line 43 'golab7: loop { 'lab8: loop { if !env.in_grouping(G_v, 97, 121) { break 'lab8; } break 'golab7; } if env.cursor >= env.limit { break 'lab0; } env.next_char(); } // gopast, line 43 'golab9: loop { 'lab10: loop { if !env.out_grouping(G_v, 97, 121) { break 'lab10; } break 'golab9; } if env.cursor >= env.limit { break 'lab0; } env.next_char(); } // setmark p2, line 43 context.i_p2 = env.cursor; break 'lab0; } env.cursor = v_1; return true; } fn r_shortv(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 49 // or, line 51 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 50 if !env.out_grouping_b(G_v_WXY, 89, 121) { break 'lab1; } if !env.in_grouping_b(G_v, 97, 121) { break 'lab1; } if !env.out_grouping_b(G_v, 97, 121) { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_1; // (, line 52 if !env.out_grouping_b(G_v, 97, 121) { return false; } if !env.in_grouping_b(G_v, 97, 121) { return false; } // atlimit, line 52 if env.cursor > env.limit_backward { return false; } break 'lab0; } return true; } fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p1 <= env.cursor){ return false; } return true; } fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p2 <= env.cursor){ return false; } return true; } fn r_Step_1a(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 58 // try, line 59 let v_1 = env.limit - env.cursor; 'lab0: loop { // (, line 59 // [, line 60 env.ket = env.cursor; // substring, line 60 among_var = env.find_among_b(A_1, context); if among_var == 0 { env.cursor = env.limit - v_1; break 'lab0; } // ], line 60 env.bra = env.cursor; if among_var == 0 { env.cursor = env.limit - v_1; break 'lab0; } else if among_var == 1 { // (, line 62 // delete, line 62 if !env.slice_del() { return false; } } break 'lab0; } // [, line 65 env.ket = env.cursor; // substring, line 65 among_var = env.find_among_b(A_2, context); if among_var == 0 { return false; } // ], line 65 env.bra = env.cursor; if among_var == 0 { return false; } else if among_var == 1 { // (, line 66 // <-, line 66 if !env.slice_from("ss") { return false; } } else if among_var == 2 { // (, line 68 // or, line 68 'lab1: loop { let v_2 = env.limit - env.cursor; 'lab2: loop { // (, line 68 // hop, line 68 let c = env.byte_index_for_hop(-2); if env.limit_backward as i32 > c || c > env.limit as i32 { break 'lab2; } env.cursor = c as usize; // <-, line 68 if !env.slice_from("i") { return false; } break 'lab1; } env.cursor = env.limit - v_2; // <-, line 68 if !env.slice_from("ie") { return false; } break 'lab1; } } else if among_var == 3 { // (, line 69 // next, line 69 if env.cursor <= env.limit_backward { return false; } env.previous_char(); // gopast, line 69 'golab3: loop { 'lab4: loop { if !env.in_grouping_b(G_v, 97, 121) { break 'lab4; } break 'golab3; } if env.cursor <= env.limit_backward { return false; } env.previous_char(); } // delete, line 69 if !env.slice_del() { return false; } } return true; } fn r_Step_1b(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 74 // [, line 75 env.ket = env.cursor; // substring, line 75 among_var = env.find_among_b(A_4, context); if among_var == 0 { return false; } // ], line 75 env.bra = env.cursor; if among_var == 0 { return false; } else if among_var == 1 { // (, line 77 // call R1, line 77 if !r_R1(env, context) { return false; } // <-, line 77 if !env.slice_from("ee") { return false; } } else if among_var == 2 { // (, line 79 // test, line 80 let v_1 = env.limit - env.cursor; // gopast, line 80 'golab0: loop { 'lab1: loop { if !env.in_grouping_b(G_v, 97, 121) { break 'lab1; } break 'golab0; } if env.cursor <= env.limit_backward { return false; } env.previous_char(); } env.cursor = env.limit - v_1; // delete, line 80 if !env.slice_del() { return false; } // test, line 81 let v_3 = env.limit - env.cursor; // substring, line 81 among_var = env.find_among_b(A_3, context); if among_var == 0 { return false; } env.cursor = env.limit - v_3; if among_var == 0 { return false; } else if among_var == 1 { // (, line 83 // <+, line 83 let c = env.cursor; let (bra, ket) = (env.cursor, env.cursor); env.insert(bra, ket, "e"); env.cursor = c; } else if among_var == 2 { // (, line 86 // [, line 86 env.ket = env.cursor; // next, line 86 if env.cursor <= env.limit_backward { return false; } env.previous_char(); // ], line 86 env.bra = env.cursor; // delete, line 86 if !env.slice_del() { return false; } } else if among_var == 3 { // (, line 87 // atmark, line 87 if env.cursor != context.i_p1 { return false; } // test, line 87 let v_4 = env.limit - env.cursor; // call shortv, line 87 if !r_shortv(env, context) { return false; } env.cursor = env.limit - v_4; // <+, line 87 let c = env.cursor; let (bra, ket) = (env.cursor, env.cursor); env.insert(bra, ket, "e"); env.cursor = c; } } return true; } fn r_Step_1c(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 93 // [, line 94 env.ket = env.cursor; // or, line 94 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // literal, line 94 if !env.eq_s_b(&"y") { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_1; // literal, line 94 if !env.eq_s_b(&"Y") { return false; } break 'lab0; } // ], line 94 env.bra = env.cursor; if !env.out_grouping_b(G_v, 97, 121) { return false; } // not, line 95 let v_2 = env.limit - env.cursor; 'lab2: loop { // atlimit, line 95 if env.cursor > env.limit_backward { break 'lab2; } return false; } env.cursor = env.limit - v_2; // <-, line 96 if !env.slice_from("i") { return false; } return true; } fn r_Step_2(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 99 // [, line 100 env.ket = env.cursor; // substring, line 100 among_var = env.find_among_b(A_5, context); if among_var == 0 { return false; } // ], line 100 env.bra = env.cursor; // call R1, line 100 if !r_R1(env, context) { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 101 // <-, line 101 if !env.slice_from("tion") { return false; } } else if among_var == 2 { // (, line 102 // <-, line 102 if !env.slice_from("ence") { return false; } } else if among_var == 3 { // (, line 103 // <-, line 103 if !env.slice_from("ance") { return false; } } else if among_var == 4 { // (, line 104 // <-, line 104 if !env.slice_from("able") { return false; } } else if among_var == 5 { // (, line 105 // <-, line 105 if !env.slice_from("ent") { return false; } } else if among_var == 6 { // (, line 107 // <-, line 107 if !env.slice_from("ize") { return false; } } else if among_var == 7 { // (, line 109 // <-, line 109 if !env.slice_from("ate") { return false; } } else if among_var == 8 { // (, line 111 // <-, line 111 if !env.slice_from("al") { return false; } } else if among_var == 9 { // (, line 112 // <-, line 112 if !env.slice_from("ful") { return false; } } else if among_var == 10 { // (, line 114 // <-, line 114 if !env.slice_from("ous") { return false; } } else if among_var == 11 { // (, line 116 // <-, line 116 if !env.slice_from("ive") { return false; } } else if among_var == 12 { // (, line 118 // <-, line 118 if !env.slice_from("ble") { return false; } } else if among_var == 13 { // (, line 119 // literal, line 119 if !env.eq_s_b(&"l") { return false; } // <-, line 119 if !env.slice_from("og") { return false; } } else if among_var == 14 { // (, line 120 // <-, line 120 if !env.slice_from("ful") { return false; } } else if among_var == 15 { // (, line 121 // <-, line 121 if !env.slice_from("less") { return false; } } else if among_var == 16 { // (, line 122 if !env.in_grouping_b(G_valid_LI, 99, 116) { return false; } // delete, line 122 if !env.slice_del() { return false; } } return true; } fn r_Step_3(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 126 // [, line 127 env.ket = env.cursor; // substring, line 127 among_var = env.find_among_b(A_6, context); if among_var == 0 { return false; } // ], line 127 env.bra = env.cursor; // call R1, line 127 if !r_R1(env, context) { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 128 // <-, line 128 if !env.slice_from("tion") { return false; } } else if among_var == 2 { // (, line 129 // <-, line 129 if !env.slice_from("ate") { return false; } } else if among_var == 3 { // (, line 130 // <-, line 130 if !env.slice_from("al") { return false; } } else if among_var == 4 { // (, line 132 // <-, line 132 if !env.slice_from("ic") { return false; } } else if among_var == 5 { // (, line 134 // delete, line 134 if !env.slice_del() { return false; } } else if among_var == 6 { // (, line 136 // call R2, line 136 if !r_R2(env, context) { return false; } // delete, line 136 if !env.slice_del() { return false; } } return true; } fn r_Step_4(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 140 // [, line 141 env.ket = env.cursor; // substring, line 141 among_var = env.find_among_b(A_7, context); if among_var == 0 { return false; } // ], line 141 env.bra = env.cursor; // call R2, line 141 if !r_R2(env, context) { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 144 // delete, line 144 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 145 // or, line 145 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // literal, line 145 if !env.eq_s_b(&"s") { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_1; // literal, line 145 if !env.eq_s_b(&"t") { return false; } break 'lab0; } // delete, line 145 if !env.slice_del() { return false; } } return true; } fn r_Step_5(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 149 // [, line 150 env.ket = env.cursor; // substring, line 150 among_var = env.find_among_b(A_8, context); if among_var == 0 { return false; } // ], line 150 env.bra = env.cursor; if among_var == 0 { return false; } else if among_var == 1 { // (, line 151 // or, line 151 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // call R2, line 151 if !r_R2(env, context) { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_1; // (, line 151 // call R1, line 151 if !r_R1(env, context) { return false; } // not, line 151 let v_2 = env.limit - env.cursor; 'lab2: loop { // call shortv, line 151 if !r_shortv(env, context) { break 'lab2; } return false; } env.cursor = env.limit - v_2; break 'lab0; } // delete, line 151 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 152 // call R2, line 152 if !r_R2(env, context) { return false; } // literal, line 152 if !env.eq_s_b(&"l") { return false; } // delete, line 152 if !env.slice_del() { return false; } } return true; } fn r_exception2(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 156 // [, line 158 env.ket = env.cursor; // substring, line 158 if env.find_among_b(A_9, context) == 0 { return false; } // ], line 158 env.bra = env.cursor; // atlimit, line 158 if env.cursor > env.limit_backward { return false; } return true; } fn r_exception1(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 168 // [, line 170 env.bra = env.cursor; // substring, line 170 among_var = env.find_among(A_10, context); if among_var == 0 { return false; } // ], line 170 env.ket = env.cursor; // atlimit, line 170 if env.cursor < env.limit { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 174 // <-, line 174 if !env.slice_from("ski") { return false; } } else if among_var == 2 { // (, line 175 // <-, line 175 if !env.slice_from("sky") { return false; } } else if among_var == 3 { // (, line 176 // <-, line 176 if !env.slice_from("die") { return false; } } else if among_var == 4 { // (, line 177 // <-, line 177 if !env.slice_from("lie") { return false; } } else if among_var == 5 { // (, line 178 // <-, line 178 if !env.slice_from("tie") { return false; } } else if among_var == 6 { // (, line 182 // <-, line 182 if !env.slice_from("idl") { return false; } } else if among_var == 7 { // (, line 183 // <-, line 183 if !env.slice_from("gentl") { return false; } } else if among_var == 8 { // (, line 184 // <-, line 184 if !env.slice_from("ugli") { return false; } } else if among_var == 9 { // (, line 185 // <-, line 185 if !env.slice_from("earli") { return false; } } else if among_var == 10 { // (, line 186 // <-, line 186 if !env.slice_from("onli") { return false; } } else if among_var == 11 { // (, line 187 // <-, line 187 if !env.slice_from("singl") { return false; } } return true; } fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 203 // Boolean test Y_found, line 203 if !context.b_Y_found { return false; } // repeat, line 203 'replab0: loop{ let v_1 = env.cursor; 'lab1: for _ in 0..1 { // (, line 203 // goto, line 203 'golab2: loop { let v_2 = env.cursor; 'lab3: loop { // (, line 203 // [, line 203 env.bra = env.cursor; // literal, line 203 if !env.eq_s(&"Y") { break 'lab3; } // ], line 203 env.ket = env.cursor; env.cursor = v_2; break 'golab2; } env.cursor = v_2; if env.cursor >= env.limit { break 'lab1; } env.next_char(); } // <-, line 203 if !env.slice_from("y") { return false; } continue 'replab0; } env.cursor = v_1; break 'replab0; } return true; } pub fn stem(env: &mut SnowballEnv) -> bool { let mut context = &mut Context { b_Y_found: false, i_p2: 0, i_p1: 0, }; // (, line 205 // or, line 207 'lab0: loop { let v_1 = env.cursor; 'lab1: loop { // call exception1, line 207 if !r_exception1(env, context) { break 'lab1; } break 'lab0; } env.cursor = v_1; 'lab2: loop { // not, line 208 let v_2 = env.cursor; 'lab3: loop { // hop, line 208 let c = env.byte_index_for_hop(3); if 0 as i32 > c || c > env.limit as i32 { break 'lab3; } env.cursor = c as usize; break 'lab2; } env.cursor = v_2; break 'lab0; } env.cursor = v_1; // (, line 208 // do, line 209 let v_3 = env.cursor; 'lab4: loop { // call prelude, line 209 if !r_prelude(env, context) { break 'lab4; } break 'lab4; } env.cursor = v_3; // do, line 210 let v_4 = env.cursor; 'lab5: loop { // call mark_regions, line 210 if !r_mark_regions(env, context) { break 'lab5; } break 'lab5; } env.cursor = v_4; // backwards, line 211 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 211 // do, line 213 let v_5 = env.limit - env.cursor; 'lab6: loop { // call Step_1a, line 213 if !r_Step_1a(env, context) { break 'lab6; } break 'lab6; } env.cursor = env.limit - v_5; // or, line 215 'lab7: loop { let v_6 = env.limit - env.cursor; 'lab8: loop { // call exception2, line 215 if !r_exception2(env, context) { break 'lab8; } break 'lab7; } env.cursor = env.limit - v_6; // (, line 215 // do, line 217 let v_7 = env.limit - env.cursor; 'lab9: loop { // call Step_1b, line 217 if !r_Step_1b(env, context) { break 'lab9; } break 'lab9; } env.cursor = env.limit - v_7; // do, line 218 let v_8 = env.limit - env.cursor; 'lab10: loop { // call Step_1c, line 218 if !r_Step_1c(env, context) { break 'lab10; } break 'lab10; } env.cursor = env.limit - v_8; // do, line 220 let v_9 = env.limit - env.cursor; 'lab11: loop { // call Step_2, line 220 if !r_Step_2(env, context) { break 'lab11; } break 'lab11; } env.cursor = env.limit - v_9; // do, line 221 let v_10 = env.limit - env.cursor; 'lab12: loop { // call Step_3, line 221 if !r_Step_3(env, context) { break 'lab12; } break 'lab12; } env.cursor = env.limit - v_10; // do, line 222 let v_11 = env.limit - env.cursor; 'lab13: loop { // call Step_4, line 222 if !r_Step_4(env, context) { break 'lab13; } break 'lab13; } env.cursor = env.limit - v_11; // do, line 224 let v_12 = env.limit - env.cursor; 'lab14: loop { // call Step_5, line 224 if !r_Step_5(env, context) { break 'lab14; } break 'lab14;
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
true
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/romanian.rs
src/snowball/algorithms/romanian.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 3] = &[ Among("", -1, 3, None), Among("I", 0, 1, None), Among("U", 0, 2, None), ]; static A_1: &'static [Among<Context>; 16] = &[ Among("ea", -1, 3, None), Among("a\u{0163}ia", -1, 7, None), Among("aua", -1, 2, None), Among("iua", -1, 4, None), Among("a\u{0163}ie", -1, 7, None), Among("ele", -1, 3, None), Among("ile", -1, 5, None), Among("iile", 6, 4, None), Among("iei", -1, 4, None), Among("atei", -1, 6, None), Among("ii", -1, 4, None), Among("ului", -1, 1, None), Among("ul", -1, 1, None), Among("elor", -1, 3, None), Among("ilor", -1, 4, None), Among("iilor", 14, 4, None), ]; static A_2: &'static [Among<Context>; 46] = &[ Among("icala", -1, 4, None), Among("iciva", -1, 4, None), Among("ativa", -1, 5, None), Among("itiva", -1, 6, None), Among("icale", -1, 4, None), Among("a\u{0163}iune", -1, 5, None), Among("i\u{0163}iune", -1, 6, None), Among("atoare", -1, 5, None), Among("itoare", -1, 6, None), Among("\u{0103}toare", -1, 5, None), Among("icitate", -1, 4, None), Among("abilitate", -1, 1, None), Among("ibilitate", -1, 2, None), Among("ivitate", -1, 3, None), Among("icive", -1, 4, None), Among("ative", -1, 5, None), Among("itive", -1, 6, None), Among("icali", -1, 4, None), Among("atori", -1, 5, None), Among("icatori", 18, 4, None), Among("itori", -1, 6, None), Among("\u{0103}tori", -1, 5, None), Among("icitati", -1, 4, None), Among("abilitati", -1, 1, None), Among("ivitati", -1, 3, None), Among("icivi", -1, 4, None), Among("ativi", -1, 5, None), Among("itivi", -1, 6, None), Among("icit\u{0103}i", -1, 4, None), Among("abilit\u{0103}i", -1, 1, None), Among("ivit\u{0103}i", -1, 3, None), Among("icit\u{0103}\u{0163}i", -1, 4, None), Among("abilit\u{0103}\u{0163}i", -1, 1, None), Among("ivit\u{0103}\u{0163}i", -1, 3, None), Among("ical", -1, 4, None), Among("ator", -1, 5, None), Among("icator", 35, 4, None), Among("itor", -1, 6, None), Among("\u{0103}tor", -1, 5, None), Among("iciv", -1, 4, None), Among("ativ", -1, 5, None), Among("itiv", -1, 6, None), Among("ical\u{0103}", -1, 4, None), Among("iciv\u{0103}", -1, 4, None), Among("ativ\u{0103}", -1, 5, None), Among("itiv\u{0103}", -1, 6, None), ]; static A_3: &'static [Among<Context>; 62] = &[ Among("ica", -1, 1, None), Among("abila", -1, 1, None), Among("ibila", -1, 1, None), Among("oasa", -1, 1, None), Among("ata", -1, 1, None), Among("ita", -1, 1, None), Among("anta", -1, 1, None), Among("ista", -1, 3, None), Among("uta", -1, 1, None), Among("iva", -1, 1, None), Among("ic", -1, 1, None), Among("ice", -1, 1, None), Among("abile", -1, 1, None), Among("ibile", -1, 1, None), Among("isme", -1, 3, None), Among("iune", -1, 2, None), Among("oase", -1, 1, None), Among("ate", -1, 1, None), Among("itate", 17, 1, None), Among("ite", -1, 1, None), Among("ante", -1, 1, None), Among("iste", -1, 3, None), Among("ute", -1, 1, None), Among("ive", -1, 1, None), Among("ici", -1, 1, None), Among("abili", -1, 1, None), Among("ibili", -1, 1, None), Among("iuni", -1, 2, None), Among("atori", -1, 1, None), Among("osi", -1, 1, None), Among("ati", -1, 1, None), Among("itati", 30, 1, None), Among("iti", -1, 1, None), Among("anti", -1, 1, None), Among("isti", -1, 3, None), Among("uti", -1, 1, None), Among("i\u{015F}ti", -1, 3, None), Among("ivi", -1, 1, None), Among("it\u{0103}i", -1, 1, None), Among("o\u{015F}i", -1, 1, None), Among("it\u{0103}\u{0163}i", -1, 1, None), Among("abil", -1, 1, None), Among("ibil", -1, 1, None), Among("ism", -1, 3, None), Among("ator", -1, 1, None), Among("os", -1, 1, None), Among("at", -1, 1, None), Among("it", -1, 1, None), Among("ant", -1, 1, None), Among("ist", -1, 3, None), Among("ut", -1, 1, None), Among("iv", -1, 1, None), Among("ic\u{0103}", -1, 1, None), Among("abil\u{0103}", -1, 1, None), Among("ibil\u{0103}", -1, 1, None), Among("oas\u{0103}", -1, 1, None), Among("at\u{0103}", -1, 1, None), Among("it\u{0103}", -1, 1, None), Among("ant\u{0103}", -1, 1, None), Among("ist\u{0103}", -1, 3, None), Among("ut\u{0103}", -1, 1, None), Among("iv\u{0103}", -1, 1, None), ]; static A_4: &'static [Among<Context>; 94] = &[ Among("ea", -1, 1, None), Among("ia", -1, 1, None), Among("esc", -1, 1, None), Among("\u{0103}sc", -1, 1, None), Among("ind", -1, 1, None), Among("\u{00E2}nd", -1, 1, None), Among("are", -1, 1, None), Among("ere", -1, 1, None), Among("ire", -1, 1, None), Among("\u{00E2}re", -1, 1, None), Among("se", -1, 2, None), Among("ase", 10, 1, None), Among("sese", 10, 2, None), Among("ise", 10, 1, None), Among("use", 10, 1, None), Among("\u{00E2}se", 10, 1, None), Among("e\u{015F}te", -1, 1, None), Among("\u{0103}\u{015F}te", -1, 1, None), Among("eze", -1, 1, None), Among("ai", -1, 1, None), Among("eai", 19, 1, None), Among("iai", 19, 1, None), Among("sei", -1, 2, None), Among("e\u{015F}ti", -1, 1, None), Among("\u{0103}\u{015F}ti", -1, 1, None), Among("ui", -1, 1, None), Among("ezi", -1, 1, None), Among("a\u{015F}i", -1, 1, None), Among("se\u{015F}i", -1, 2, None), Among("ase\u{015F}i", 28, 1, None), Among("sese\u{015F}i", 28, 2, None), Among("ise\u{015F}i", 28, 1, None), Among("use\u{015F}i", 28, 1, None), Among("\u{00E2}se\u{015F}i", 28, 1, None), Among("i\u{015F}i", -1, 1, None), Among("u\u{015F}i", -1, 1, None), Among("\u{00E2}\u{015F}i", -1, 1, None), Among("\u{00E2}i", -1, 1, None), Among("a\u{0163}i", -1, 2, None), Among("ea\u{0163}i", 38, 1, None), Among("ia\u{0163}i", 38, 1, None), Among("e\u{0163}i", -1, 2, None), Among("i\u{0163}i", -1, 2, None), Among("ar\u{0103}\u{0163}i", -1, 1, None), Among("ser\u{0103}\u{0163}i", -1, 2, None), Among("aser\u{0103}\u{0163}i", 44, 1, None), Among("seser\u{0103}\u{0163}i", 44, 2, None), Among("iser\u{0103}\u{0163}i", 44, 1, None), Among("user\u{0103}\u{0163}i", 44, 1, None), Among("\u{00E2}ser\u{0103}\u{0163}i", 44, 1, None), Among("ir\u{0103}\u{0163}i", -1, 1, None), Among("ur\u{0103}\u{0163}i", -1, 1, None), Among("\u{00E2}r\u{0103}\u{0163}i", -1, 1, None), Among("\u{00E2}\u{0163}i", -1, 2, None), Among("am", -1, 1, None), Among("eam", 54, 1, None), Among("iam", 54, 1, None), Among("em", -1, 2, None), Among("asem", 57, 1, None), Among("sesem", 57, 2, None), Among("isem", 57, 1, None), Among("usem", 57, 1, None), Among("\u{00E2}sem", 57, 1, None), Among("im", -1, 2, None), Among("\u{0103}m", -1, 2, None), Among("ar\u{0103}m", 64, 1, None), Among("ser\u{0103}m", 64, 2, None), Among("aser\u{0103}m", 66, 1, None), Among("seser\u{0103}m", 66, 2, None), Among("iser\u{0103}m", 66, 1, None), Among("user\u{0103}m", 66, 1, None), Among("\u{00E2}ser\u{0103}m", 66, 1, None), Among("ir\u{0103}m", 64, 1, None), Among("ur\u{0103}m", 64, 1, None), Among("\u{00E2}r\u{0103}m", 64, 1, None), Among("\u{00E2}m", -1, 2, None), Among("au", -1, 1, None), Among("eau", 76, 1, None), Among("iau", 76, 1, None), Among("indu", -1, 1, None), Among("\u{00E2}ndu", -1, 1, None), Among("ez", -1, 1, None), Among("easc\u{0103}", -1, 1, None), Among("ar\u{0103}", -1, 1, None), Among("ser\u{0103}", -1, 2, None), Among("aser\u{0103}", 84, 1, None), Among("seser\u{0103}", 84, 2, None), Among("iser\u{0103}", 84, 1, None), Among("user\u{0103}", 84, 1, None), Among("\u{00E2}ser\u{0103}", 84, 1, None), Among("ir\u{0103}", -1, 1, None), Among("ur\u{0103}", -1, 1, None), Among("\u{00E2}r\u{0103}", -1, 1, None), Among("eaz\u{0103}", -1, 1, None), ]; static A_5: &'static [Among<Context>; 5] = &[ Among("a", -1, 1, None), Among("e", -1, 1, None), Among("ie", 1, 1, None), Among("i", -1, 1, None), Among("\u{0103}", -1, 1, None), ]; static G_v: &'static [u8; 21] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 32, 0, 0, 4]; #[derive(Clone)] struct Context { b_standard_suffix_removed: bool, i_p2: usize, i_p1: usize, i_pV: usize, } fn r_prelude(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 30 // repeat, line 31 'replab0: loop{ let v_1 = env.cursor; 'lab1: for _ in 0..1 { // goto, line 31 'golab2: loop { let v_2 = env.cursor; 'lab3: loop { // (, line 31 if !env.in_grouping(G_v, 97, 259) { break 'lab3; } // [, line 32 env.bra = env.cursor; // or, line 32 'lab4: loop { let v_3 = env.cursor; 'lab5: loop { // (, line 32 // literal, line 32 if !env.eq_s(&"u") { break 'lab5; } // ], line 32 env.ket = env.cursor; if !env.in_grouping(G_v, 97, 259) { break 'lab5; } // <-, line 32 if !env.slice_from("U") { return false; } break 'lab4; } env.cursor = v_3; // (, line 33 // literal, line 33 if !env.eq_s(&"i") { break 'lab3; } // ], line 33 env.ket = env.cursor; if !env.in_grouping(G_v, 97, 259) { break 'lab3; } // <-, line 33 if !env.slice_from("I") { return false; } break 'lab4; } env.cursor = v_2; break 'golab2; } env.cursor = v_2; if env.cursor >= env.limit { break 'lab1; } env.next_char(); } continue 'replab0; } env.cursor = v_1; break 'replab0; } return true; } fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 37 context.i_pV = env.limit; context.i_p1 = env.limit; context.i_p2 = env.limit; // do, line 43 let v_1 = env.cursor; 'lab0: loop { // (, line 43 // or, line 45 'lab1: loop { let v_2 = env.cursor; 'lab2: loop { // (, line 44 if !env.in_grouping(G_v, 97, 259) { break 'lab2; } // or, line 44 'lab3: loop { let v_3 = env.cursor; 'lab4: loop { // (, line 44 if !env.out_grouping(G_v, 97, 259) { break 'lab4; } // gopast, line 44 'golab5: loop { 'lab6: loop { if !env.in_grouping(G_v, 97, 259) { break 'lab6; } break 'golab5; } if env.cursor >= env.limit { break 'lab4; } env.next_char(); } break 'lab3; } env.cursor = v_3; // (, line 44 if !env.in_grouping(G_v, 97, 259) { break 'lab2; } // gopast, line 44 'golab7: loop { 'lab8: loop { if !env.out_grouping(G_v, 97, 259) { break 'lab8; } break 'golab7; } if env.cursor >= env.limit { break 'lab2; } env.next_char(); } break 'lab3; } break 'lab1; } env.cursor = v_2; // (, line 46 if !env.out_grouping(G_v, 97, 259) { break 'lab0; } // or, line 46 'lab9: loop { let v_6 = env.cursor; 'lab10: loop { // (, line 46 if !env.out_grouping(G_v, 97, 259) { break 'lab10; } // gopast, line 46 'golab11: loop { 'lab12: loop { if !env.in_grouping(G_v, 97, 259) { break 'lab12; } break 'golab11; } if env.cursor >= env.limit { break 'lab10; } env.next_char(); } break 'lab9; } env.cursor = v_6; // (, line 46 if !env.in_grouping(G_v, 97, 259) { break 'lab0; } // next, line 46 if env.cursor >= env.limit { break 'lab0; } env.next_char(); break 'lab9; } break 'lab1; } // setmark pV, line 47 context.i_pV = env.cursor; break 'lab0; } env.cursor = v_1; // do, line 49 let v_8 = env.cursor; 'lab13: loop { // (, line 49 // gopast, line 50 'golab14: loop { 'lab15: loop { if !env.in_grouping(G_v, 97, 259) { break 'lab15; } break 'golab14; } if env.cursor >= env.limit { break 'lab13; } env.next_char(); } // gopast, line 50 'golab16: loop { 'lab17: loop { if !env.out_grouping(G_v, 97, 259) { break 'lab17; } break 'golab16; } if env.cursor >= env.limit { break 'lab13; } env.next_char(); } // setmark p1, line 50 context.i_p1 = env.cursor; // gopast, line 51 'golab18: loop { 'lab19: loop { if !env.in_grouping(G_v, 97, 259) { break 'lab19; } break 'golab18; } if env.cursor >= env.limit { break 'lab13; } env.next_char(); } // gopast, line 51 'golab20: loop { 'lab21: loop { if !env.out_grouping(G_v, 97, 259) { break 'lab21; } break 'golab20; } if env.cursor >= env.limit { break 'lab13; } env.next_char(); } // setmark p2, line 51 context.i_p2 = env.cursor; break 'lab13; } env.cursor = v_8; return true; } fn r_postlude(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // repeat, line 55 'replab0: loop{ let v_1 = env.cursor; 'lab1: for _ in 0..1 { // (, line 55 // [, line 57 env.bra = env.cursor; // substring, line 57 among_var = env.find_among(A_0, context); if among_var == 0 { break 'lab1; } // ], line 57 env.ket = env.cursor; if among_var == 0 { break 'lab1; } else if among_var == 1 { // (, line 58 // <-, line 58 if !env.slice_from("i") { return false; } } else if among_var == 2 { // (, line 59 // <-, line 59 if !env.slice_from("u") { return false; } } else if among_var == 3 { // (, line 60 // next, line 60 if env.cursor >= env.limit { break 'lab1; } env.next_char(); } continue 'replab0; } env.cursor = v_1; break 'replab0; } return true; } fn r_RV(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_pV <= env.cursor){ return false; } return true; } fn r_R1(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p1 <= env.cursor){ return false; } return true; } fn r_R2(env: &mut SnowballEnv, context: &mut Context) -> bool { if !(context.i_p2 <= env.cursor){ return false; } return true; } fn r_step_0(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 71 // [, line 72 env.ket = env.cursor; // substring, line 72 among_var = env.find_among_b(A_1, context); if among_var == 0 { return false; } // ], line 72 env.bra = env.cursor; // call R1, line 72 if !r_R1(env, context) { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 74 // delete, line 74 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 76 // <-, line 76 if !env.slice_from("a") { return false; } } else if among_var == 3 { // (, line 78 // <-, line 78 if !env.slice_from("e") { return false; } } else if among_var == 4 { // (, line 80 // <-, line 80 if !env.slice_from("i") { return false; } } else if among_var == 5 { // (, line 82 // not, line 82 let v_1 = env.limit - env.cursor; 'lab0: loop { // literal, line 82 if !env.eq_s_b(&"ab") { break 'lab0; } return false; } env.cursor = env.limit - v_1; // <-, line 82 if !env.slice_from("i") { return false; } } else if among_var == 6 { // (, line 84 // <-, line 84 if !env.slice_from("at") { return false; } } else if among_var == 7 { // (, line 86 // <-, line 86 if !env.slice_from("a\u{0163}i") { return false; } } return true; } fn r_combo_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // test, line 90 let v_1 = env.limit - env.cursor; // (, line 90 // [, line 91 env.ket = env.cursor; // substring, line 91 among_var = env.find_among_b(A_2, context); if among_var == 0 { return false; } // ], line 91 env.bra = env.cursor; // call R1, line 91 if !r_R1(env, context) { return false; } // (, line 91 if among_var == 0 { return false; } else if among_var == 1 { // (, line 99 // <-, line 100 if !env.slice_from("abil") { return false; } } else if among_var == 2 { // (, line 102 // <-, line 103 if !env.slice_from("ibil") { return false; } } else if among_var == 3 { // (, line 105 // <-, line 106 if !env.slice_from("iv") { return false; } } else if among_var == 4 { // (, line 111 // <-, line 112 if !env.slice_from("ic") { return false; } } else if among_var == 5 { // (, line 116 // <-, line 117 if !env.slice_from("at") { return false; } } else if among_var == 6 { // (, line 120 // <-, line 121 if !env.slice_from("it") { return false; } } // set standard_suffix_removed, line 124 context.b_standard_suffix_removed = true; env.cursor = env.limit - v_1; return true; } fn r_standard_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 128 // unset standard_suffix_removed, line 129 context.b_standard_suffix_removed = false; // repeat, line 130 'replab0: loop{ let v_1 = env.limit - env.cursor; 'lab1: for _ in 0..1 { // call combo_suffix, line 130 if !r_combo_suffix(env, context) { break 'lab1; } continue 'replab0; } env.cursor = env.limit - v_1; break 'replab0; } // [, line 131 env.ket = env.cursor; // substring, line 131 among_var = env.find_among_b(A_3, context); if among_var == 0 { return false; } // ], line 131 env.bra = env.cursor; // call R2, line 131 if !r_R2(env, context) { return false; } // (, line 131 if among_var == 0 { return false; } else if among_var == 1 { // (, line 147 // delete, line 148 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 150 // literal, line 151 if !env.eq_s_b(&"\u{0163}") { return false; } // ], line 151 env.bra = env.cursor; // <-, line 151 if !env.slice_from("t") { return false; } } else if among_var == 3 { // (, line 154 // <-, line 155 if !env.slice_from("ist") { return false; } } // set standard_suffix_removed, line 159 context.b_standard_suffix_removed = true; return true; } fn r_verb_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // setlimit, line 163 let v_1 = env.limit - env.cursor; // tomark, line 163 if env.cursor < context.i_pV { return false; } env.cursor = context.i_pV; let v_2 = env.limit_backward; env.limit_backward = env.cursor; env.cursor = env.limit - v_1; // (, line 163 // [, line 164 env.ket = env.cursor; // substring, line 164 among_var = env.find_among_b(A_4, context); if among_var == 0 { env.limit_backward = v_2; return false; } // ], line 164 env.bra = env.cursor; if among_var == 0 { env.limit_backward = v_2; return false; } else if among_var == 1 { // (, line 199 // or, line 199 'lab0: loop { let v_3 = env.limit - env.cursor; 'lab1: loop { if !env.out_grouping_b(G_v, 97, 259) { break 'lab1; } break 'lab0; } env.cursor = env.limit - v_3; // literal, line 199 if !env.eq_s_b(&"u") { env.limit_backward = v_2; return false; } break 'lab0; } // delete, line 199 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 213 // delete, line 213 if !env.slice_del() { return false; } } env.limit_backward = v_2; return true; } fn r_vowel_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 217 // [, line 218 env.ket = env.cursor; // substring, line 218 among_var = env.find_among_b(A_5, context); if among_var == 0 { return false; } // ], line 218 env.bra = env.cursor; // call RV, line 218 if !r_RV(env, context) { return false; } if among_var == 0 { return false; } else if among_var == 1 { // (, line 219 // delete, line 219 if !env.slice_del() { return false; } } return true; } pub fn stem(env: &mut SnowballEnv) -> bool { let mut context = &mut Context { b_standard_suffix_removed: false, i_p2: 0, i_p1: 0, i_pV: 0, }; // (, line 224 // do, line 225 let v_1 = env.cursor; 'lab0: loop { // call prelude, line 225 if !r_prelude(env, context) { break 'lab0; } break 'lab0; } env.cursor = v_1; // do, line 226 let v_2 = env.cursor; 'lab1: loop { // call mark_regions, line 226 if !r_mark_regions(env, context) { break 'lab1; } break 'lab1; } env.cursor = v_2; // backwards, line 227 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 227 // do, line 228 let v_3 = env.limit - env.cursor; 'lab2: loop { // call step_0, line 228 if !r_step_0(env, context) { break 'lab2; } break 'lab2; } env.cursor = env.limit - v_3; // do, line 229 let v_4 = env.limit - env.cursor; 'lab3: loop { // call standard_suffix, line 229 if !r_standard_suffix(env, context) { break 'lab3; } break 'lab3; } env.cursor = env.limit - v_4; // do, line 230 let v_5 = env.limit - env.cursor; 'lab4: loop { // (, line 230 // or, line 230 'lab5: loop { let v_6 = env.limit - env.cursor; 'lab6: loop { // Boolean test standard_suffix_removed, line 230 if !context.b_standard_suffix_removed { break 'lab6; } break 'lab5; } env.cursor = env.limit - v_6; // call verb_suffix, line 230 if !r_verb_suffix(env, context) { break 'lab4; } break 'lab5; } break 'lab4; } env.cursor = env.limit - v_5; // do, line 231 let v_7 = env.limit - env.cursor; 'lab7: loop { // call vowel_suffix, line 231 if !r_vowel_suffix(env, context) { break 'lab7; } break 'lab7; } env.cursor = env.limit - v_7; env.cursor = env.limit_backward; // do, line 233 let v_8 = env.cursor; 'lab8: loop { // call postlude, line 233 if !r_postlude(env, context) { break 'lab8; } break 'lab8; } env.cursor = v_8; return true; }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
false
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/swedish.rs
src/snowball/algorithms/swedish.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 37] = &[ Among("a", -1, 1, None), Among("arna", 0, 1, None), Among("erna", 0, 1, None), Among("heterna", 2, 1, None), Among("orna", 0, 1, None), Among("ad", -1, 1, None), Among("e", -1, 1, None), Among("ade", 6, 1, None), Among("ande", 6, 1, None), Among("arne", 6, 1, None), Among("are", 6, 1, None), Among("aste", 6, 1, None), Among("en", -1, 1, None), Among("anden", 12, 1, None), Among("aren", 12, 1, None), Among("heten", 12, 1, None), Among("ern", -1, 1, None), Among("ar", -1, 1, None), Among("er", -1, 1, None), Among("heter", 18, 1, None), Among("or", -1, 1, None), Among("s", -1, 2, None), Among("as", 21, 1, None), Among("arnas", 22, 1, None), Among("ernas", 22, 1, None), Among("ornas", 22, 1, None), Among("es", 21, 1, None), Among("ades", 26, 1, None), Among("andes", 26, 1, None), Among("ens", 21, 1, None), Among("arens", 29, 1, None), Among("hetens", 29, 1, None), Among("erns", 21, 1, None), Among("at", -1, 1, None), Among("andet", -1, 1, None), Among("het", -1, 1, None), Among("ast", -1, 1, None), ]; static A_1: &'static [Among<Context>; 7] = &[ Among("dd", -1, -1, None), Among("gd", -1, -1, None), Among("nn", -1, -1, None), Among("dt", -1, -1, None), Among("gt", -1, -1, None), Among("kt", -1, -1, None), Among("tt", -1, -1, None), ]; static A_2: &'static [Among<Context>; 5] = &[ Among("ig", -1, 1, None), Among("lig", 0, 1, None), Among("els", -1, 1, None), Among("fullt", -1, 3, None), Among("l\u{00F6}st", -1, 2, None), ]; static G_v: &'static [u8; 19] = &[17, 65, 16, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 32]; static G_s_ending: &'static [u8; 3] = &[119, 127, 149]; #[derive(Clone)] struct Context { i_x: usize, i_p1: usize, } fn r_mark_regions(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 26 context.i_p1 = env.limit; // test, line 29 let v_1 = env.cursor; // (, line 29 // hop, line 29 let c = env.byte_index_for_hop(3); if 0 as i32 > c || c > env.limit as i32 { return false; } env.cursor = c as usize; // setmark x, line 29 context.i_x = env.cursor; env.cursor = v_1; // goto, line 30 'golab0: loop { let v_2 = env.cursor; 'lab1: loop { if !env.in_grouping(G_v, 97, 246) { break 'lab1; } env.cursor = v_2; break 'golab0; } env.cursor = v_2; if env.cursor >= env.limit { return false; } env.next_char(); } // gopast, line 30 'golab2: loop { 'lab3: loop { if !env.out_grouping(G_v, 97, 246) { break 'lab3; } break 'golab2; } if env.cursor >= env.limit { return false; } env.next_char(); } // setmark p1, line 30 context.i_p1 = env.cursor; // try, line 31 'lab4: loop { // (, line 31 if !(context.i_p1 < context.i_x){ break 'lab4; } context.i_p1 = context.i_x; break 'lab4; } return true; } fn r_main_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // (, line 36 // setlimit, line 37 let v_1 = env.limit - env.cursor; // tomark, line 37 if env.cursor < context.i_p1 { return false; } env.cursor = context.i_p1; let v_2 = env.limit_backward; env.limit_backward = env.cursor; env.cursor = env.limit - v_1; // (, line 37 // [, line 37 env.ket = env.cursor; // substring, line 37 among_var = env.find_among_b(A_0, context); if among_var == 0 { env.limit_backward = v_2; return false; } // ], line 37 env.bra = env.cursor; env.limit_backward = v_2; if among_var == 0 { return false; } else if among_var == 1 { // (, line 44 // delete, line 44 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 46 if !env.in_grouping_b(G_s_ending, 98, 121) { return false; } // delete, line 46 if !env.slice_del() { return false; } } return true; } fn r_consonant_pair(env: &mut SnowballEnv, context: &mut Context) -> bool { // setlimit, line 50 let v_1 = env.limit - env.cursor; // tomark, line 50 if env.cursor < context.i_p1 { return false; } env.cursor = context.i_p1; let v_2 = env.limit_backward; env.limit_backward = env.cursor; env.cursor = env.limit - v_1; // (, line 50 // and, line 52 let v_3 = env.limit - env.cursor; // among, line 51 if env.find_among_b(A_1, context) == 0 { env.limit_backward = v_2; return false; } env.cursor = env.limit - v_3; // (, line 52 // [, line 52 env.ket = env.cursor; // next, line 52 if env.cursor <= env.limit_backward { env.limit_backward = v_2; return false; } env.previous_char(); // ], line 52 env.bra = env.cursor; // delete, line 52 if !env.slice_del() { return false; } env.limit_backward = v_2; return true; } fn r_other_suffix(env: &mut SnowballEnv, context: &mut Context) -> bool { let mut among_var; // setlimit, line 55 let v_1 = env.limit - env.cursor; // tomark, line 55 if env.cursor < context.i_p1 { return false; } env.cursor = context.i_p1; let v_2 = env.limit_backward; env.limit_backward = env.cursor; env.cursor = env.limit - v_1; // (, line 55 // [, line 56 env.ket = env.cursor; // substring, line 56 among_var = env.find_among_b(A_2, context); if among_var == 0 { env.limit_backward = v_2; return false; } // ], line 56 env.bra = env.cursor; if among_var == 0 { env.limit_backward = v_2; return false; } else if among_var == 1 { // (, line 57 // delete, line 57 if !env.slice_del() { return false; } } else if among_var == 2 { // (, line 58 // <-, line 58 if !env.slice_from("l\u{00F6}s") { return false; } } else if among_var == 3 { // (, line 59 // <-, line 59 if !env.slice_from("full") { return false; } } env.limit_backward = v_2; return true; } pub fn stem(env: &mut SnowballEnv) -> bool { let mut context = &mut Context { i_x: 0, i_p1: 0, }; // (, line 64 // do, line 66 let v_1 = env.cursor; 'lab0: loop { // call mark_regions, line 66 if !r_mark_regions(env, context) { break 'lab0; } break 'lab0; } env.cursor = v_1; // backwards, line 67 env.limit_backward = env.cursor; env.cursor = env.limit; // (, line 67 // do, line 68 let v_2 = env.limit - env.cursor; 'lab1: loop { // call main_suffix, line 68 if !r_main_suffix(env, context) { break 'lab1; } break 'lab1; } env.cursor = env.limit - v_2; // do, line 69 let v_3 = env.limit - env.cursor; 'lab2: loop { // call consonant_pair, line 69 if !r_consonant_pair(env, context) { break 'lab2; } break 'lab2; } env.cursor = env.limit - v_3; // do, line 70 let v_4 = env.limit - env.cursor; 'lab3: loop { // call other_suffix, line 70 if !r_other_suffix(env, context) { break 'lab3; } break 'lab3; } env.cursor = env.limit - v_4; env.cursor = env.limit_backward; return true; }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
false
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/src/snowball/algorithms/turkish.rs
src/snowball/algorithms/turkish.rs
//! This file was generated automatically by the Snowball to Rust compiler //! http://snowballstem.org/ #![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(unused_variables)] #![allow(unused_mut)] use snowball::SnowballEnv; use snowball::Among; static A_0: &'static [Among<Context>; 10] = &[ Among("m", -1, -1, None), Among("n", -1, -1, None), Among("miz", -1, -1, None), Among("niz", -1, -1, None), Among("muz", -1, -1, None), Among("nuz", -1, -1, None), Among("m\u{0131}z", -1, -1, None), Among("n\u{0131}z", -1, -1, None), Among("m\u{00FC}z", -1, -1, None), Among("n\u{00FC}z", -1, -1, None), ]; static A_1: &'static [Among<Context>; 2] = &[ Among("leri", -1, -1, None), Among("lar\u{0131}", -1, -1, None), ]; static A_2: &'static [Among<Context>; 4] = &[ Among("ni", -1, -1, None), Among("nu", -1, -1, None), Among("n\u{0131}", -1, -1, None), Among("n\u{00FC}", -1, -1, None), ]; static A_3: &'static [Among<Context>; 4] = &[ Among("in", -1, -1, None), Among("un", -1, -1, None), Among("\u{0131}n", -1, -1, None), Among("\u{00FC}n", -1, -1, None), ]; static A_4: &'static [Among<Context>; 2] = &[ Among("a", -1, -1, None), Among("e", -1, -1, None), ]; static A_5: &'static [Among<Context>; 2] = &[ Among("na", -1, -1, None), Among("ne", -1, -1, None), ]; static A_6: &'static [Among<Context>; 4] = &[ Among("da", -1, -1, None), Among("ta", -1, -1, None), Among("de", -1, -1, None), Among("te", -1, -1, None), ]; static A_7: &'static [Among<Context>; 2] = &[ Among("nda", -1, -1, None), Among("nde", -1, -1, None), ]; static A_8: &'static [Among<Context>; 4] = &[ Among("dan", -1, -1, None), Among("tan", -1, -1, None), Among("den", -1, -1, None), Among("ten", -1, -1, None), ]; static A_9: &'static [Among<Context>; 2] = &[ Among("ndan", -1, -1, None), Among("nden", -1, -1, None), ]; static A_10: &'static [Among<Context>; 2] = &[ Among("la", -1, -1, None), Among("le", -1, -1, None), ]; static A_11: &'static [Among<Context>; 2] = &[ Among("ca", -1, -1, None), Among("ce", -1, -1, None), ]; static A_12: &'static [Among<Context>; 4] = &[ Among("im", -1, -1, None), Among("um", -1, -1, None), Among("\u{0131}m", -1, -1, None), Among("\u{00FC}m", -1, -1, None), ]; static A_13: &'static [Among<Context>; 4] = &[ Among("sin", -1, -1, None), Among("sun", -1, -1, None), Among("s\u{0131}n", -1, -1, None), Among("s\u{00FC}n", -1, -1, None), ]; static A_14: &'static [Among<Context>; 4] = &[ Among("iz", -1, -1, None), Among("uz", -1, -1, None), Among("\u{0131}z", -1, -1, None), Among("\u{00FC}z", -1, -1, None), ]; static A_15: &'static [Among<Context>; 4] = &[ Among("siniz", -1, -1, None), Among("sunuz", -1, -1, None), Among("s\u{0131}n\u{0131}z", -1, -1, None), Among("s\u{00FC}n\u{00FC}z", -1, -1, None), ]; static A_16: &'static [Among<Context>; 2] = &[ Among("lar", -1, -1, None), Among("ler", -1, -1, None), ]; static A_17: &'static [Among<Context>; 4] = &[ Among("niz", -1, -1, None), Among("nuz", -1, -1, None), Among("n\u{0131}z", -1, -1, None), Among("n\u{00FC}z", -1, -1, None), ]; static A_18: &'static [Among<Context>; 8] = &[ Among("dir", -1, -1, None), Among("tir", -1, -1, None), Among("dur", -1, -1, None), Among("tur", -1, -1, None), Among("d\u{0131}r", -1, -1, None), Among("t\u{0131}r", -1, -1, None), Among("d\u{00FC}r", -1, -1, None), Among("t\u{00FC}r", -1, -1, None), ]; static A_19: &'static [Among<Context>; 2] = &[ Among("cas\u{0131}na", -1, -1, None), Among("cesine", -1, -1, None), ]; static A_20: &'static [Among<Context>; 32] = &[ Among("di", -1, -1, None), Among("ti", -1, -1, None), Among("dik", -1, -1, None), Among("tik", -1, -1, None), Among("duk", -1, -1, None), Among("tuk", -1, -1, None), Among("d\u{0131}k", -1, -1, None), Among("t\u{0131}k", -1, -1, None), Among("d\u{00FC}k", -1, -1, None), Among("t\u{00FC}k", -1, -1, None), Among("dim", -1, -1, None), Among("tim", -1, -1, None), Among("dum", -1, -1, None), Among("tum", -1, -1, None), Among("d\u{0131}m", -1, -1, None), Among("t\u{0131}m", -1, -1, None), Among("d\u{00FC}m", -1, -1, None), Among("t\u{00FC}m", -1, -1, None), Among("din", -1, -1, None), Among("tin", -1, -1, None), Among("dun", -1, -1, None), Among("tun", -1, -1, None), Among("d\u{0131}n", -1, -1, None), Among("t\u{0131}n", -1, -1, None), Among("d\u{00FC}n", -1, -1, None), Among("t\u{00FC}n", -1, -1, None), Among("du", -1, -1, None), Among("tu", -1, -1, None), Among("d\u{0131}", -1, -1, None), Among("t\u{0131}", -1, -1, None), Among("d\u{00FC}", -1, -1, None), Among("t\u{00FC}", -1, -1, None), ]; static A_21: &'static [Among<Context>; 8] = &[ Among("sa", -1, -1, None), Among("se", -1, -1, None), Among("sak", -1, -1, None), Among("sek", -1, -1, None), Among("sam", -1, -1, None), Among("sem", -1, -1, None), Among("san", -1, -1, None), Among("sen", -1, -1, None), ]; static A_22: &'static [Among<Context>; 4] = &[ Among("mi\u{015F}", -1, -1, None), Among("mu\u{015F}", -1, -1, None), Among("m\u{0131}\u{015F}", -1, -1, None), Among("m\u{00FC}\u{015F}", -1, -1, None), ]; static A_23: &'static [Among<Context>; 4] = &[ Among("b", -1, 1, None), Among("c", -1, 2, None), Among("d", -1, 3, None), Among("\u{011F}", -1, 4, None), ]; static G_vowel: &'static [u8; 27] = &[17, 65, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 8, 0, 0, 0, 0, 0, 0, 1]; static G_U: &'static [u8; 26] = &[1, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 1]; static G_vowel1: &'static [u8; 27] = &[1, 64, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; static G_vowel2: &'static [u8; 19] = &[17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 130]; static G_vowel3: &'static [u8; 27] = &[1, 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]; static G_vowel4: &'static [u8; 1] = &[17]; static G_vowel5: &'static [u8; 1] = &[65]; static G_vowel6: &'static [u8; 1] = &[65]; #[derive(Clone)] struct Context { b_continue_stemming_noun_suffixes: bool, i_strlen: usize, } fn r_check_vowel_harmony(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 111 // test, line 112 let v_1 = env.limit - env.cursor; // (, line 113 // (, line 114 // goto, line 114 'golab0: loop { let v_2 = env.limit - env.cursor; 'lab1: loop { if !env.in_grouping_b(G_vowel, 97, 305) { break 'lab1; } env.cursor = env.limit - v_2; break 'golab0; } env.cursor = env.limit - v_2; if env.cursor <= env.limit_backward { return false; } env.previous_char(); } // (, line 115 // or, line 116 'lab2: loop { let v_3 = env.limit - env.cursor; 'lab3: loop { // (, line 116 // literal, line 116 if !env.eq_s_b(&"a") { break 'lab3; } // goto, line 116 'golab4: loop { let v_4 = env.limit - env.cursor; 'lab5: loop { if !env.in_grouping_b(G_vowel1, 97, 305) { break 'lab5; } env.cursor = env.limit - v_4; break 'golab4; } env.cursor = env.limit - v_4; if env.cursor <= env.limit_backward { break 'lab3; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab6: loop { // (, line 117 // literal, line 117 if !env.eq_s_b(&"e") { break 'lab6; } // goto, line 117 'golab7: loop { let v_5 = env.limit - env.cursor; 'lab8: loop { if !env.in_grouping_b(G_vowel2, 101, 252) { break 'lab8; } env.cursor = env.limit - v_5; break 'golab7; } env.cursor = env.limit - v_5; if env.cursor <= env.limit_backward { break 'lab6; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab9: loop { // (, line 118 // literal, line 118 if !env.eq_s_b(&"\u{0131}") { break 'lab9; } // goto, line 118 'golab10: loop { let v_6 = env.limit - env.cursor; 'lab11: loop { if !env.in_grouping_b(G_vowel3, 97, 305) { break 'lab11; } env.cursor = env.limit - v_6; break 'golab10; } env.cursor = env.limit - v_6; if env.cursor <= env.limit_backward { break 'lab9; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab12: loop { // (, line 119 // literal, line 119 if !env.eq_s_b(&"i") { break 'lab12; } // goto, line 119 'golab13: loop { let v_7 = env.limit - env.cursor; 'lab14: loop { if !env.in_grouping_b(G_vowel4, 101, 105) { break 'lab14; } env.cursor = env.limit - v_7; break 'golab13; } env.cursor = env.limit - v_7; if env.cursor <= env.limit_backward { break 'lab12; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab15: loop { // (, line 120 // literal, line 120 if !env.eq_s_b(&"o") { break 'lab15; } // goto, line 120 'golab16: loop { let v_8 = env.limit - env.cursor; 'lab17: loop { if !env.in_grouping_b(G_vowel5, 111, 117) { break 'lab17; } env.cursor = env.limit - v_8; break 'golab16; } env.cursor = env.limit - v_8; if env.cursor <= env.limit_backward { break 'lab15; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab18: loop { // (, line 121 // literal, line 121 if !env.eq_s_b(&"\u{00F6}") { break 'lab18; } // goto, line 121 'golab19: loop { let v_9 = env.limit - env.cursor; 'lab20: loop { if !env.in_grouping_b(G_vowel6, 246, 252) { break 'lab20; } env.cursor = env.limit - v_9; break 'golab19; } env.cursor = env.limit - v_9; if env.cursor <= env.limit_backward { break 'lab18; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; 'lab21: loop { // (, line 122 // literal, line 122 if !env.eq_s_b(&"u") { break 'lab21; } // goto, line 122 'golab22: loop { let v_10 = env.limit - env.cursor; 'lab23: loop { if !env.in_grouping_b(G_vowel5, 111, 117) { break 'lab23; } env.cursor = env.limit - v_10; break 'golab22; } env.cursor = env.limit - v_10; if env.cursor <= env.limit_backward { break 'lab21; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_3; // (, line 123 // literal, line 123 if !env.eq_s_b(&"\u{00FC}") { return false; } // goto, line 123 'golab24: loop { let v_11 = env.limit - env.cursor; 'lab25: loop { if !env.in_grouping_b(G_vowel6, 246, 252) { break 'lab25; } env.cursor = env.limit - v_11; break 'golab24; } env.cursor = env.limit - v_11; if env.cursor <= env.limit_backward { return false; } env.previous_char(); } break 'lab2; } env.cursor = env.limit - v_1; return true; } fn r_mark_suffix_with_optional_n_consonant(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 132 // or, line 134 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 133 // literal, line 133 if !env.eq_s_b(&"n") { break 'lab1; } // (, line 133 // test, line 133 let v_2 = env.limit - env.cursor; if !env.in_grouping_b(G_vowel, 97, 305) { break 'lab1; } env.cursor = env.limit - v_2; break 'lab0; } env.cursor = env.limit - v_1; // (, line 135 // (, line 135 // not, line 135 let v_3 = env.limit - env.cursor; 'lab2: loop { // (, line 135 // test, line 135 let v_4 = env.limit - env.cursor; // literal, line 135 if !env.eq_s_b(&"n") { break 'lab2; } env.cursor = env.limit - v_4; return false; } env.cursor = env.limit - v_3; // test, line 135 let v_5 = env.limit - env.cursor; // (, line 135 // next, line 135 if env.cursor <= env.limit_backward { return false; } env.previous_char(); if !env.in_grouping_b(G_vowel, 97, 305) { return false; } env.cursor = env.limit - v_5; break 'lab0; } return true; } fn r_mark_suffix_with_optional_s_consonant(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 143 // or, line 145 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 144 // literal, line 144 if !env.eq_s_b(&"s") { break 'lab1; } // (, line 144 // test, line 144 let v_2 = env.limit - env.cursor; if !env.in_grouping_b(G_vowel, 97, 305) { break 'lab1; } env.cursor = env.limit - v_2; break 'lab0; } env.cursor = env.limit - v_1; // (, line 146 // (, line 146 // not, line 146 let v_3 = env.limit - env.cursor; 'lab2: loop { // (, line 146 // test, line 146 let v_4 = env.limit - env.cursor; // literal, line 146 if !env.eq_s_b(&"s") { break 'lab2; } env.cursor = env.limit - v_4; return false; } env.cursor = env.limit - v_3; // test, line 146 let v_5 = env.limit - env.cursor; // (, line 146 // next, line 146 if env.cursor <= env.limit_backward { return false; } env.previous_char(); if !env.in_grouping_b(G_vowel, 97, 305) { return false; } env.cursor = env.limit - v_5; break 'lab0; } return true; } fn r_mark_suffix_with_optional_y_consonant(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 153 // or, line 155 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 154 // literal, line 154 if !env.eq_s_b(&"y") { break 'lab1; } // (, line 154 // test, line 154 let v_2 = env.limit - env.cursor; if !env.in_grouping_b(G_vowel, 97, 305) { break 'lab1; } env.cursor = env.limit - v_2; break 'lab0; } env.cursor = env.limit - v_1; // (, line 156 // (, line 156 // not, line 156 let v_3 = env.limit - env.cursor; 'lab2: loop { // (, line 156 // test, line 156 let v_4 = env.limit - env.cursor; // literal, line 156 if !env.eq_s_b(&"y") { break 'lab2; } env.cursor = env.limit - v_4; return false; } env.cursor = env.limit - v_3; // test, line 156 let v_5 = env.limit - env.cursor; // (, line 156 // next, line 156 if env.cursor <= env.limit_backward { return false; } env.previous_char(); if !env.in_grouping_b(G_vowel, 97, 305) { return false; } env.cursor = env.limit - v_5; break 'lab0; } return true; } fn r_mark_suffix_with_optional_U_vowel(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 159 // or, line 161 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 160 if !env.in_grouping_b(G_U, 105, 305) { break 'lab1; } // (, line 160 // test, line 160 let v_2 = env.limit - env.cursor; if !env.out_grouping_b(G_vowel, 97, 305) { break 'lab1; } env.cursor = env.limit - v_2; break 'lab0; } env.cursor = env.limit - v_1; // (, line 162 // (, line 162 // not, line 162 let v_3 = env.limit - env.cursor; 'lab2: loop { // (, line 162 // test, line 162 let v_4 = env.limit - env.cursor; if !env.in_grouping_b(G_U, 105, 305) { break 'lab2; } env.cursor = env.limit - v_4; return false; } env.cursor = env.limit - v_3; // test, line 162 let v_5 = env.limit - env.cursor; // (, line 162 // next, line 162 if env.cursor <= env.limit_backward { return false; } env.previous_char(); if !env.out_grouping_b(G_vowel, 97, 305) { return false; } env.cursor = env.limit - v_5; break 'lab0; } return true; } fn r_mark_possessives(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 166 // among, line 167 if env.find_among_b(A_0, context) == 0 { return false; } // (, line 169 // call mark_suffix_with_optional_U_vowel, line 169 if !r_mark_suffix_with_optional_U_vowel(env, context) { return false; } return true; } fn r_mark_sU(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 172 // call check_vowel_harmony, line 173 if !r_check_vowel_harmony(env, context) { return false; } if !env.in_grouping_b(G_U, 105, 305) { return false; } // (, line 175 // call mark_suffix_with_optional_s_consonant, line 175 if !r_mark_suffix_with_optional_s_consonant(env, context) { return false; } return true; } fn r_mark_lArI(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 178 // among, line 179 if env.find_among_b(A_1, context) == 0 { return false; } return true; } fn r_mark_yU(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 182 // call check_vowel_harmony, line 183 if !r_check_vowel_harmony(env, context) { return false; } if !env.in_grouping_b(G_U, 105, 305) { return false; } // (, line 185 // call mark_suffix_with_optional_y_consonant, line 185 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_nU(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 188 // call check_vowel_harmony, line 189 if !r_check_vowel_harmony(env, context) { return false; } // among, line 190 if env.find_among_b(A_2, context) == 0 { return false; } return true; } fn r_mark_nUn(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 193 // call check_vowel_harmony, line 194 if !r_check_vowel_harmony(env, context) { return false; } // among, line 195 if env.find_among_b(A_3, context) == 0 { return false; } // (, line 196 // call mark_suffix_with_optional_n_consonant, line 196 if !r_mark_suffix_with_optional_n_consonant(env, context) { return false; } return true; } fn r_mark_yA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 199 // call check_vowel_harmony, line 200 if !r_check_vowel_harmony(env, context) { return false; } // among, line 201 if env.find_among_b(A_4, context) == 0 { return false; } // (, line 202 // call mark_suffix_with_optional_y_consonant, line 202 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_nA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 205 // call check_vowel_harmony, line 206 if !r_check_vowel_harmony(env, context) { return false; } // among, line 207 if env.find_among_b(A_5, context) == 0 { return false; } return true; } fn r_mark_DA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 210 // call check_vowel_harmony, line 211 if !r_check_vowel_harmony(env, context) { return false; } // among, line 212 if env.find_among_b(A_6, context) == 0 { return false; } return true; } fn r_mark_ndA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 215 // call check_vowel_harmony, line 216 if !r_check_vowel_harmony(env, context) { return false; } // among, line 217 if env.find_among_b(A_7, context) == 0 { return false; } return true; } fn r_mark_DAn(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 220 // call check_vowel_harmony, line 221 if !r_check_vowel_harmony(env, context) { return false; } // among, line 222 if env.find_among_b(A_8, context) == 0 { return false; } return true; } fn r_mark_ndAn(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 225 // call check_vowel_harmony, line 226 if !r_check_vowel_harmony(env, context) { return false; } // among, line 227 if env.find_among_b(A_9, context) == 0 { return false; } return true; } fn r_mark_ylA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 230 // call check_vowel_harmony, line 231 if !r_check_vowel_harmony(env, context) { return false; } // among, line 232 if env.find_among_b(A_10, context) == 0 { return false; } // (, line 233 // call mark_suffix_with_optional_y_consonant, line 233 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_ki(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 236 // literal, line 237 if !env.eq_s_b(&"ki") { return false; } return true; } fn r_mark_ncA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 240 // call check_vowel_harmony, line 241 if !r_check_vowel_harmony(env, context) { return false; } // among, line 242 if env.find_among_b(A_11, context) == 0 { return false; } // (, line 243 // call mark_suffix_with_optional_n_consonant, line 243 if !r_mark_suffix_with_optional_n_consonant(env, context) { return false; } return true; } fn r_mark_yUm(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 246 // call check_vowel_harmony, line 247 if !r_check_vowel_harmony(env, context) { return false; } // among, line 248 if env.find_among_b(A_12, context) == 0 { return false; } // (, line 249 // call mark_suffix_with_optional_y_consonant, line 249 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_sUn(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 252 // call check_vowel_harmony, line 253 if !r_check_vowel_harmony(env, context) { return false; } // among, line 254 if env.find_among_b(A_13, context) == 0 { return false; } return true; } fn r_mark_yUz(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 257 // call check_vowel_harmony, line 258 if !r_check_vowel_harmony(env, context) { return false; } // among, line 259 if env.find_among_b(A_14, context) == 0 { return false; } // (, line 260 // call mark_suffix_with_optional_y_consonant, line 260 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_sUnUz(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 263 // among, line 264 if env.find_among_b(A_15, context) == 0 { return false; } return true; } fn r_mark_lAr(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 267 // call check_vowel_harmony, line 268 if !r_check_vowel_harmony(env, context) { return false; } // among, line 269 if env.find_among_b(A_16, context) == 0 { return false; } return true; } fn r_mark_nUz(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 272 // call check_vowel_harmony, line 273 if !r_check_vowel_harmony(env, context) { return false; } // among, line 274 if env.find_among_b(A_17, context) == 0 { return false; } return true; } fn r_mark_DUr(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 277 // call check_vowel_harmony, line 278 if !r_check_vowel_harmony(env, context) { return false; } // among, line 279 if env.find_among_b(A_18, context) == 0 { return false; } return true; } fn r_mark_cAsInA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 282 // among, line 283 if env.find_among_b(A_19, context) == 0 { return false; } return true; } fn r_mark_yDU(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 286 // call check_vowel_harmony, line 287 if !r_check_vowel_harmony(env, context) { return false; } // among, line 288 if env.find_among_b(A_20, context) == 0 { return false; } // (, line 292 // call mark_suffix_with_optional_y_consonant, line 292 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_ysA(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 296 // among, line 297 if env.find_among_b(A_21, context) == 0 { return false; } // (, line 298 // call mark_suffix_with_optional_y_consonant, line 298 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_ymUs_(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 301 // call check_vowel_harmony, line 302 if !r_check_vowel_harmony(env, context) { return false; } // among, line 303 if env.find_among_b(A_22, context) == 0 { return false; } // (, line 304 // call mark_suffix_with_optional_y_consonant, line 304 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_mark_yken(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 307 // literal, line 308 if !env.eq_s_b(&"ken") { return false; } // (, line 308 // call mark_suffix_with_optional_y_consonant, line 308 if !r_mark_suffix_with_optional_y_consonant(env, context) { return false; } return true; } fn r_stem_nominal_verb_suffixes(env: &mut SnowballEnv, context: &mut Context) -> bool { // (, line 311 // [, line 312 env.ket = env.cursor; // set continue_stemming_noun_suffixes, line 313 context.b_continue_stemming_noun_suffixes = true; // or, line 315 'lab0: loop { let v_1 = env.limit - env.cursor; 'lab1: loop { // (, line 314 // or, line 314 'lab2: loop { let v_2 = env.limit - env.cursor; 'lab3: loop { // call mark_ymUs_, line 314 if !r_mark_ymUs_(env, context) { break 'lab3; } break 'lab2; } env.cursor = env.limit - v_2; 'lab4: loop { // call mark_yDU, line 314 if !r_mark_yDU(env, context) { break 'lab4; } break 'lab2; } env.cursor = env.limit - v_2; 'lab5: loop { // call mark_ysA, line 314 if !r_mark_ysA(env, context) { break 'lab5; } break 'lab2; } env.cursor = env.limit - v_2; // call mark_yken, line 314 if !r_mark_yken(env, context) { break 'lab1; } break 'lab2; } break 'lab0; } env.cursor = env.limit - v_1; 'lab6: loop { // (, line 316 // call mark_cAsInA, line 316 if !r_mark_cAsInA(env, context) { break 'lab6; } // (, line 316 // or, line 316 'lab7: loop { let v_3 = env.limit - env.cursor; 'lab8: loop { // call mark_sUnUz, line 316 if !r_mark_sUnUz(env, context) { break 'lab8; } break 'lab7; } env.cursor = env.limit - v_3; 'lab9: loop { // call mark_lAr, line 316 if !r_mark_lAr(env, context) { break 'lab9; } break 'lab7; } env.cursor = env.limit - v_3; 'lab10: loop { // call mark_yUm, line 316 if !r_mark_yUm(env, context) { break 'lab10; } break 'lab7; } env.cursor = env.limit - v_3; 'lab11: loop { // call mark_sUn, line 316 if !r_mark_sUn(env, context) { break 'lab11; } break 'lab7; } env.cursor = env.limit - v_3; 'lab12: loop {
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
true
CurrySoftware/rust-stemmers
https://github.com/CurrySoftware/rust-stemmers/blob/1fde09dfa08fb0fb07fbd6570aba8ecc98174edb/examples/stem-file/main.rs
examples/stem-file/main.rs
extern crate rust_stemmers; use rust_stemmers::{Algorithm, Stemmer}; fn main() { let en_stemmer = Stemmer::create(Algorithm::English); assert_eq!(en_stemmer.stem("fruitlessly"), "fruitless"); }
rust
MIT
1fde09dfa08fb0fb07fbd6570aba8ecc98174edb
2026-01-04T20:25:20.053159Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/rustyvctl/old.build.rs
rustyvctl/old.build.rs
use std::env; fn main() { let os = env::var("CARGO_CFG_TARGET_OS"); if os == Ok("uefi".to_string()) { println!("cargo:rustc-flags='-Clink-args= /subsystem:EFI_APPLICATION"); } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/rustyvctl/src/main.rs
rustyvctl/src/main.rs
//! A UEFI executable for communicating with the //! [hypervisor](../hypervisor/index.html). //! Invoke via the UEFI shell like so: //! ```text //! UEFI Interactive Shell v2.2 //! EDK II //! UEFI v2.70 (EDK II, 0x00010000) //! Mapping table //! FS0: Alias(s):F0a:;BLK0: //! PciRoot(0x0)/Pci(0x1,0x1)/Ata(0x0) //! Press ESC in 1 seconds to skip startup.nsh or any other key to continue. //! Shell> fs0: //! FS0:\> dir //! Directory of: FS0:\ //! 06/03/2021 23:33 342,016 rustyvctl.efi //! 06/03/2021 23:42 10,383 NvVars //! 2 File(s) 433,807 bytes //! 0 Dir(s) //! FS0:\> .\rustyvctl.efi //! FS0:\> //! ``` #![no_std] #![no_main] #![feature(abi_efiapi)] #![warn(missing_docs)] // Used for ud2 intrinsic. #![feature(stdsimd)] extern crate hypervisor_abi; extern crate uefi; //extern crate uefi_services; extern crate log; use core::fmt::Write; use uefi::prelude::*; /// The entrypoint of the UEFI application. #[no_mangle] pub extern "efiapi" fn efi_main( _image_handle: uefi::Handle, system_table: SystemTable<Boot>, ) -> Status { let results = hypervisor_abi::invoke_hypercall(hypervisor_abi::HYPERCALL_REASON_VERSION); let io_result = write!( system_table.stdout(), "Hypervisor version {}.{}.{}\r\n", results.results[0], results.results[1], results.results[2] ); match io_result { Ok(()) => Status::SUCCESS, Err(_) => Status::WARN_WRITE_FAILURE, } } /// Handle Rust panics. #[panic_handler] pub extern "C" fn panic_fmt(_info: &core::panic::PanicInfo) -> ! { unsafe { core::arch::x86_64::ud2() } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor_abi/src/lib.rs
hypervisor_abi/src/lib.rs
//! Hypercall ABI //! The hypervisor will handle hypercalls via the CPUID instruction. //! Hypercalls must have a magic number HYPERCALL_MAGIC in RAX and a valid //! hypercall reason in RBX. //! Values will be returned in RAX, RBX, RCX, and RDX according to the //! hypercall reason. #![no_std] use core::arch::x86_64::__cpuid_count; /// Magic number which must be in RAX if this is a hypercall. pub const HYPERCALL_MAGIC: u32 = 0x72737479; /// Hypercall reasons must be in RBX. If RBX=1, the reason is version. /// The major, minor, and patch version numbers from this crate's Cargo.toml /// will be returned in rax, rbx, and rcx respectively. Rdx is reserved zero. pub const HYPERCALL_REASON_VERSION: u32 = 0x1; #[derive(Debug, Default, Clone, Copy)] pub struct HyperCallResults { // The hypercall "reason" or discriminant. Similar to a syscall number. pub reason: u32, // Return values of the hypercall. pub results: [u32; 4], } pub fn invoke_hypercall(reason: u32) -> HyperCallResults { let results = unsafe { __cpuid_count(HYPERCALL_MAGIC, reason) }; HyperCallResults { reason, results: [results.eax, results.ebx, results.ecx, results.edx], } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/linux/src/lib.rs
linux/src/lib.rs
//! A shim layer between the C code making up the Linux kernel module and the //! [hypervisor](../hypervisor/index.html) module. //! This code gets compiled into a static library which is linked into the //! kernel module #![no_std] #![warn(missing_docs)] extern crate hypervisor; use core::convert::TryFrom; /// The size of a small page in bytes. const PAGE_SIZE: usize = 0x1000; extern "C" { /// A function implemented in C which converts a kernel virtual address to a physical address. fn rustyvisor_linux_virt_to_phys(x: *mut u8) -> u64; /// A function implemented in C for allocating memory. The memory will be zeroed. fn rustyvisor_linux_kmalloc(size: usize) -> *mut u8; } use hypervisor::segmentation::{GdtEntry, GdtEntry64}; use hypervisor::segmentation::Tss; /// Allocate and initialize a VCpu. fn rustyvisor_linux_create_vcpu() -> Result<&'static mut hypervisor::VCpu, ()> { unsafe { let vcpu = rustyvisor_linux_kmalloc(core::mem::size_of::<hypervisor::VCpu>()) as *mut hypervisor::VCpu; if vcpu.is_null() { return Err(()); } let tss = rustyvisor_linux_kmalloc(core::mem::size_of::<hypervisor::segmentation::Tss>()); if tss.is_null() { return Err(()); } let virtual_local_interrupt_controller = rustyvisor_linux_kmalloc(core::mem::size_of::< hypervisor::interrupt_controller::VirtualLocalInterruptController, >()) as *mut hypervisor::interrupt_controller::VirtualLocalInterruptController; if virtual_local_interrupt_controller.is_null() { return Err(()); } let vmxon_region = rustyvisor_linux_kmalloc(PAGE_SIZE) as *mut u32; if vmxon_region.is_null() { return Err(()); } let vmx_on_region_phys = rustyvisor_linux_virt_to_phys(vmxon_region as *mut u8); let vmcs = rustyvisor_linux_kmalloc(PAGE_SIZE) as *mut u32; if vmcs.is_null() { return Err(()); } let vmcs_phys = rustyvisor_linux_virt_to_phys(vmcs as *mut u8); let stack_pages = 1; let stack = rustyvisor_linux_kmalloc(stack_pages * PAGE_SIZE); if stack.is_null() { return Err(()); } let msr_bitmap = rustyvisor_linux_kmalloc(PAGE_SIZE); if msr_bitmap.is_null() { return Err(()); } let msr_bitmap_phys = rustyvisor_linux_virt_to_phys(msr_bitmap); let gdt = hypervisor::segmentation::get_current_gdt(); let original_gdt_size = gdt.len() * core::mem::size_of::<GdtEntry>(); let host_gdt_size = core::mem::size_of_val(&gdt) + core::mem::size_of::<GdtEntry64>(); let host_tr_index = gdt.len(); let host_gdt = rustyvisor_linux_kmalloc(host_gdt_size); if host_gdt.is_null() { return Err(()); } (*vcpu).this_vcpu = vcpu; (*vcpu).loaded_successfully = false; (*vcpu).vmcs_phys = vmcs_phys; (*vcpu).vmcs_size = PAGE_SIZE; (*vcpu).vmcs = vmcs; (*vcpu).virtual_local_interrupt_controller = virtual_local_interrupt_controller; (*vcpu).vmxon_region_phys = vmx_on_region_phys; (*vcpu).vmxon_region_size = PAGE_SIZE; (*vcpu).vmxon_region = vmxon_region; (*vcpu).msr_bitmap = msr_bitmap_phys; (*vcpu).stack_base = stack; (*vcpu).stack_size = stack_pages * PAGE_SIZE; // Page size (*vcpu).stack_top = (*vcpu).stack_base.add((*vcpu).stack_size); (*vcpu).host_gdt_base = host_gdt as *mut u64; (*vcpu).host_gdt_limit = host_gdt_size as u64 - 1; let tss_base = tss as u64; (*vcpu).tr_base = tss_base; (*vcpu).tr_selector = u16::try_from(host_tr_index * core::mem::size_of::<GdtEntry>()).unwrap(); let tss_gdt_entry = host_gdt.add(original_gdt_size) as *mut GdtEntry64; (*tss_gdt_entry).access = 0xe9; (*tss_gdt_entry).granularity = 0; (*tss_gdt_entry).limit_low = u16::try_from(core::mem::size_of::<Tss>() - 1).unwrap(); (*tss_gdt_entry).base_low = tss_base as u16; (*tss_gdt_entry).base_middle = (tss_base >> 16) as u8; (*tss_gdt_entry).base_high = (tss_base >> 24) as u8; (*tss_gdt_entry).base_highest = (tss_base >> 32) as u32; (*tss_gdt_entry).reserved0 = 0; Ok(&mut *vcpu) } } /// Load the hypervisor on the current core. #[no_mangle] pub extern "C" fn rustyvisor_linux_core_load(_ptr: usize) -> i32 { let vcpu = match rustyvisor_linux_create_vcpu() { Ok(vcpu) => vcpu, Err(_) => return -1, }; hypervisor::rustyvisor_core_load(vcpu) }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmcs_fields.rs
hypervisor/src/vmcs_fields.rs
//! Defines the fields of the vmcs and their contents. #![allow(non_upper_case_globals)] #![allow(unused)] #[repr(u64)] pub enum VmcsField { VirtualProcessorID = 0x0000_0000, PostedIntrNV = 0x0000_0002, GuestEsSelector = 0x0000_0800, GuestCsSelector = 0x0000_0802, GuestSsSelector = 0x0000_0804, GuestDsSelector = 0x0000_0806, GuestFsSelector = 0x0000_0808, GuestGsSelector = 0x0000_080a, GuestLdtrSelector = 0x0000_080c, GuestTrSelector = 0x0000_080e, GuestIntrStatus = 0x0000_0810, GuestPmlIndex = 0x0000_0812, HostEsSelector = 0x0000_0c00, HostCsSelector = 0x0000_0c02, HostSsSelector = 0x0000_0c04, HostDsSelector = 0x0000_0c06, HostFsSelector = 0x0000_0c08, HostGsSelector = 0x0000_0c0a, HostTrSelector = 0x0000_0c0c, IoBitmapA = 0x0000_2000, IoBitmapAHigh = 0x0000_2001, IoBitmapB = 0x0000_2002, IoBitmapBHigh = 0x0000_2003, MsrBitmap = 0x0000_2004, MsrBitmapHigh = 0x0000_2005, VmExitMsrStoreAddr = 0x0000_2006, VmExitMsrStoreAddrHigh = 0x0000_2007, VmExitMsrLoadAddr = 0x0000_2008, VmExitMsrLoadAddrHigh = 0x0000_2009, VmEntryMsrLoadAddr = 0x0000_200a, VmEntryMsrLoadAddrHigh = 0x0000_200b, PMLAddress = 0x0000_200e, PMLAddressHigh = 0x0000_200f, TscOffset = 0x0000_2010, TscOffsetHigh = 0x0000_2011, VirtualApicPageAddr = 0x0000_2012, VirtualApicPageAddrHigh = 0x0000_2013, APICAccessAddr = 0x0000_2014, APICAccessAddrHigh = 0x0000_2015, PostedIntrDescAddr = 0x0000_2016, PostedIntrDescAddrHigh = 0x0000_2017, EPTPointer = 0x0000_201a, EPTPointerHigh = 0x0000_201b, EoiExitBitmap0 = 0x0000_201c, EoiExitBitmap0High = 0x0000_201d, EoiExitBitmap1 = 0x0000_201e, EoiExitBitmap1High = 0x0000_201f, EoiExitBitmap2 = 0x0000_2020, EoiExitBitmap2High = 0x0000_2021, EoiExitBitmap3 = 0x0000_2022, EoiExitBitmap3High = 0x0000_2023, VmReadBitmap = 0x0000_2026, VmWriteBitmap = 0x0000_2028, XssExitBitmap = 0x0000_202c, XssExitBitmapHigh = 0x0000_202d, TsxMultiplier = 0x0000_2032, TsxMultiplierHigh = 0x0000_2033, GuestPhysicalAddress = 0x0000_2400, GuestPhysicalAddressHigh = 0x0000_2401, VmcsLinkPointer = 0x0000_2800, VmcsLinkPointerHigh = 0x0000_2801, GuestIA32Debugctl = 0x0000_2802, GuestIA32DebugctlHigh = 0x0000_2803, GuestIA32Pat = 0x0000_2804, GuestIA32PatHigh = 0x0000_2805, GuestIA32Efer = 0x0000_2806, GuestIA32EferHigh = 0x0000_2807, GuestIA32PerfGlobalCtrl = 0x0000_2808, GuestIA32PerfGlobalCtrlHigh = 0x0000_2809, GuestPDPtr0 = 0x0000_280a, GuestPDPtr0High = 0x0000_280b, GuestPDPtr1 = 0x0000_280c, GuestPDPtr1High = 0x0000_280d, GuestPDPtr2 = 0x0000_280e, GuestPDPtr2High = 0x0000_280f, GuestPDPtr3 = 0x0000_2810, GuestPDPtr3High = 0x0000_2811, GuestBndcfgs = 0x0000_2812, GuestBndcfgsHigh = 0x0000_2813, HostIA32Pat = 0x0000_2c00, HostIA32PatHigh = 0x0000_2c01, HostIA32Efer = 0x0000_2c02, HostIA32EferHigh = 0x0000_2c03, HostIA32PerfGlobalCtrl = 0x0000_2c04, HostIA32PerfGlobalCtrlHigh = 0x0000_2c05, PinBasedVmExecControl = 0x0000_4000, CpuBasedVmExecControl = 0x0000_4002, ExceptIonBitmap = 0x0000_4004, PageFaultErrorCodeMask = 0x0000_4006, PageFaultErrorCodeMatch = 0x0000_4008, Cr3TargetCount = 0x0000_400a, VmExitControls = 0x0000_400c, VmExitMsrStoreCount = 0x0000_400e, VmExitMsrLoadCount = 0x0000_4010, VmEntryControls = 0x0000_4012, VmEntryMsrLoadCount = 0x0000_4014, VmEntryIntrInfoField = 0x0000_4016, VmEntryExceptIonErrorCode = 0x0000_4018, VmEntryInstructionLen = 0x0000_401a, TPRThreshold = 0x0000_401c, SecondaryVmExecControl = 0x0000_401e, PLEGap = 0x0000_4020, PLEWindow = 0x0000_4022, VmInstructionError = 0x0000_4400, VmExitReason = 0x0000_4402, VmExitIntrInfo = 0x0000_4404, VmExitIntrErrorCode = 0x0000_4406, IdtVectoringInfoField = 0x0000_4408, IdtVectoringErrorCode = 0x0000_440a, VmExitInstructionLen = 0x0000_440c, VmxInstructionInfo = 0x0000_440e, GuestEsLimit = 0x0000_4800, GuestCsLimit = 0x0000_4802, GuestSsLimit = 0x0000_4804, GuestDsLimit = 0x0000_4806, GuestFsLimit = 0x0000_4808, GuestGsLimit = 0x0000_480a, GuestLdtrLimit = 0x0000_480c, GuestTrLimit = 0x0000_480e, GuestGdtrLimit = 0x0000_4810, GuestIdtrLimit = 0x0000_4812, GuestEsArBytes = 0x0000_4814, GuestCsArBytes = 0x0000_4816, GuestSsArBytes = 0x0000_4818, GuestDsArBytes = 0x0000_481a, GuestFsArBytes = 0x0000_481c, GuestGsArBytes = 0x0000_481e, GuestLdtrArBytes = 0x0000_4820, GuestTrArBytes = 0x0000_4822, GuestInterruptibilityInfo = 0x0000_4824, GuestActivityState = 0x0000_4826, GuestSysenterCs = 0x0000_482a, VmxPreemptionTimerValue = 0x0000_482e, HostIA32SysenterCs = 0x0000_4c00, Cr0GuestHostMask = 0x0000_6000, Cr4GuestHostMask = 0x0000_6002, Cr0ReadShadow = 0x0000_6004, Cr4ReadShadow = 0x0000_6006, Cr3TargetValue0 = 0x0000_6008, Cr3TargetValue1 = 0x0000_600a, Cr3TargetValue2 = 0x0000_600c, Cr3TargetValue3 = 0x0000_600e, ExitQualificatIon = 0x0000_6400, GuestLinearAddress = 0x0000_640a, GuestCr0 = 0x0000_6800, GuestCr3 = 0x0000_6802, GuestCr4 = 0x0000_6804, GuestEsBase = 0x0000_6806, GuestCsBase = 0x0000_6808, GuestSsBase = 0x0000_680a, GuestDsBase = 0x0000_680c, GuestFsBase = 0x0000_680e, GuestGsBase = 0x0000_6810, GuestLdtrBase = 0x0000_6812, GuestTrBase = 0x0000_6814, GuestGdtrBase = 0x0000_6816, GuestIdtrBase = 0x0000_6818, GuestDr7 = 0x0000_681a, GuestRsp = 0x0000_681c, GuestRip = 0x0000_681e, GuestRFlags = 0x0000_6820, GuestPendingDbgExceptions = 0x0000_6822, GuestSysenterEsp = 0x0000_6824, GuestSysenterEip = 0x0000_6826, HostCr0 = 0x0000_6c00, HostCr3 = 0x0000_6c02, HostCr4 = 0x0000_6c04, HostFsBase = 0x0000_6c06, HostGsBase = 0x0000_6c08, HostTrBase = 0x0000_6c0a, HostGdtrBase = 0x0000_6c0c, HostIdtrBase = 0x0000_6c0e, HostIA32SysenterEsp = 0x0000_6c10, HostIA32SysenterEip = 0x0000_6c12, HostRsp = 0x0000_6c14, HostRip = 0x0000_6c16, } pub const PinBasedControlsExternalInterruptExiting: u64 = 1 << 0; pub const PinBasedControlsNmiExiting: u64 = 1 << 3; pub const PinBasedControlsVirtualNmi: u64 = 1 << 5; pub const PinBasedControlsVmxPreemption: u64 = 1 << 6; pub const PinBasedControlsPostedInterrupts: u64 = 1 << 7; pub const CpuBasedControlsInterruptWindowExiting: u64 = 1 << 2; pub const CpuBasedControlsTscOffsetting: u64 = 1 << 3; pub const CpuBasedControlsHltExiting: u64 = 1 << 7; pub const CpuBasedControlsInvlpgExiting: u64 = 1 << 9; pub const CpuBasedControlsMwaitExiting: u64 = 1 << 10; pub const CpuBasedControlsRdpmcExiting: u64 = 1 << 11; pub const CpuBasedControlsRdtscExiting: u64 = 1 << 12; pub const CpuBasedControlsCr3LdExiting: u64 = 1 << 15; pub const CpuBasedControlsCr3StExiting: u64 = 1 << 16; pub const CpuBasedControlsCr8LdExiting: u64 = 1 << 19; pub const CpuBasedControlsCr8StExiting: u64 = 1 << 20; pub const CpuBasedControlsTprShadow: u64 = 1 << 21; pub const CpuBasedControlsNmiWindowExiting: u64 = 1 << 22; pub const CpuBasedControlsMovDrExiting: u64 = 1 << 23; pub const CpuBasedControlsIoExiting: u64 = 1 << 24; pub const CpuBasedControlsIoBitmaps: u64 = 1 << 25; pub const CpuBasedControlsMonitorTrapFlagEnable: u64 = 1 << 27; pub const CpuBasedControlsMsrBitmaps: u64 = 1 << 28; pub const CpuBasedControlsMonitorExiting: u64 = 1 << 29; pub const CpuBasedControlsPauseExiting: u64 = 1 << 30; pub const CpuBasedControlsSecondaryEnable: u64 = 1 << 31; pub const SecondaryCpuBasedControlsVirtualApic: u64 = 1 << 0; pub const SecondaryCpuBasedControlsEptEnable: u64 = 1 << 1; pub const SecondaryCpuBasedControlsDtExiting: u64 = 1 << 2; pub const SecondaryCpuBasedControlsRdtscpEnable: u64 = 1 << 3; pub const SecondaryCpuBasedControlsX2ApicEnable: u64 = 1 << 4; pub const SecondaryCpuBasedControlsVpidEnable: u64 = 1 << 5; pub const SecondaryCpuBasedControlsWbinvdExiting: u64 = 1 << 6; pub const SecondaryCpuBasedControlsUnrestrictedGuest: u64 = 1 << 7; pub const SecondaryCpuBasedControlsVirtualApicRegister: u64 = 1 << 8; pub const SecondaryCpuBasedControlsVirtualInterruptEnable: u64 = 1 << 9; pub const SecondaryCpuBasedControlsPauseLoopExiting: u64 = 1 << 10; pub const SecondaryCpuBasedControlsRdrandExiting: u64 = 1 << 11; pub const SecondaryCpuBasedControlsInvpcidEnable: u64 = 1 << 12; pub const SecondaryCpuBasedControlsVmfuncEnable: u64 = 1 << 13; pub const SecondaryCpuBasedControlsVmcsShadow: u64 = 1 << 14; pub const SecondaryCpuBasedControlsEnclsExiting: u64 = 1 << 15; pub const SecondaryCpuBasedControlsRdseedExiting: u64 = 1 << 16; pub const SecondaryCpuBasedControlsPmlEnable: u64 = 1 << 17; pub const SecondaryCpuBasedControlsEptVeEnable: u64 = 1 << 18; pub const SecondaryCpuBasedControlsPtConcealVmx: u64 = 1 << 19; pub const SecondaryCpuBasedControlsXSavesEnable: u64 = 1 << 20; pub const SecondaryCpuBasedControlsEptExecuteControl: u64 = 1 << 22; pub const SecondaryCpuBasedControlsTscScalingEnable: u64 = 1 << 25; // Table 24-11 sectIon 24.7.1 vol3c pub const VmExitIa32eMode: u64 = 1 << 9; pub const VmExitAcknowledgeInterruptOnExit: u64 = 1 << 15; pub const VmExitConcealVmxFromPt: u64 = 1 << 24; // Table 24-13 sectIon 24.8.1 vol3c pub const VmEntryIa32eMode: u64 = 1 << 9;
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/register_state.rs
hypervisor/src/register_state.rs
//! Defines structures for working with the register state during a VM exit or //! interrupt. /// Stores the state of the general purpose registers. /// The order must be the same as the order of the pushes and pops in the assembly functions _host_entrypoint and _service_interrupt. /// This structure does not include rsp since rsp is saved by iret in an interrupt and in the vmcs field GuestRsp by a vmexit. #[derive(Debug)] #[repr(C)] pub struct GeneralPurposeRegisterState { pub r15: u64, pub r14: u64, pub r13: u64, pub r12: u64, pub r11: u64, pub r10: u64, pub r9: u64, pub r8: u64, pub rdi: u64, pub rsi: u64, pub rbp: u64, pub rdx: u64, pub rcx: u64, pub rbx: u64, pub rax: u64, } impl GeneralPurposeRegisterState { /// Returns a mutable reference to a register in the GeneralPurposeRegisterState or None if that register is not in the state. /// Note that rsp is note in GeneralPurposeRegisterState. /// /// This order is related to the encoding of the mod rm byte and is widely used throughout various vmcs fields. /// For more information about the mod rm byte, see Vol 2. Section 2.1.3 particularly Table 2-2. "32-Bit Addressing Forms with the ModR/M Byte". /// See also Vol 3. Table 27-3. "Exit Qualification for Control-Register Accesses" and Vol 3. Tables 27-9 through 27-14. and probably other places. pub fn by_mod_rm_index(&mut self, index: u64) -> Option<&mut u64> { match index { 0x0 => Some(&mut self.rax), 0x1 => Some(&mut self.rcx), 0x2 => Some(&mut self.rdx), 0x3 => Some(&mut self.rbx), 0x4 => None, // For an interrupt rsp is pushed by the iret. For a vmexit, it's stored in the vmcs field GuestRsp. 0x5 => Some(&mut self.rbp), 0x6 => Some(&mut self.rsi), 0x7 => Some(&mut self.rdi), 0x8 => Some(&mut self.r8), 0x9 => Some(&mut self.r9), 0xa => Some(&mut self.r10), 0xb => Some(&mut self.r11), 0xc => Some(&mut self.r12), 0xd => Some(&mut self.r13), 0xe => Some(&mut self.r14), 0xf => Some(&mut self.r15), _ => panic!("Illegal value"), } } } /// The register state when an interrupt is taken. /// This order must be the same as the order of the pushes and pops in the assembly function _service_interrupt. /// The order of the general purpose registers and gs, fs, es, and ds is arbitrary. The registers rip, cs, rflags, ss, and rsp are pushed by the interrupt, and their order is fixed by hardware. #[derive(Debug)] #[repr(C)] pub struct InterruptRegisterState { gs: u64, fs: u64, es: u64, ds: u64, registers: GeneralPurposeRegisterState, interrupt_number: u64, error_code: u64, rip: u64, cs: u64, rflags: u64, rsp: u64, ss: u64, }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/isr.rs
hypervisor/src/isr.rs
//! This module defines various interrupt service routines, or ISRs. //! An interrupt service routine is called via the hardware when an interrupt //! occurs. //! These ISRs must be installed into the Interrupt Descriptor Table. //! This module mostly names functions defined elsewhere in assembly. /// The type of an Interrupt Service Routine assembly stub. /// They are modeled as a no-return extern "C" function. /// However, they have an unusual calling convention determined by the /// hardware, and are not meant to be called directly by rust code. /// Instead, generate the appropriate interrupt. pub type InterruptServiceRoutine = unsafe extern "C" fn() -> !; extern "C" { /// ISR 0, division by 0. fn _isr0() -> !; /// ISR 1, debug exception. fn _isr1() -> !; /// ISR 2, Non-maskabile interrupt. fn _isr2() -> !; /// ISR 3, breakpoint. fn _isr3() -> !; /// ISR 4, overflow. fn _isr4() -> !; /// ISR 5, bound range exceeded. fn _isr5() -> !; /// ISR 6, invalid opcode. fn _isr6() -> !; /// ISR 7, device unavailable. fn _isr7() -> !; /// ISR 8, double fault. fn _isr8() -> !; /// ISR 9, coprocessor segment overrun (deprecated). fn _isr9() -> !; /// ISR 10, invalid TSS. fn _isr10() -> !; /// ISR 11, segment not present. fn _isr11() -> !; /// ISR 12, stack segment fault. fn _isr12() -> !; /// ISR 13, general protection fault. fn _isr13() -> !; /// ISR 14, page fault. fn _isr14() -> !; /// ISR 15, reserved. fn _isr15() -> !; /// ISR 16, x87 floating point exception. fn _isr16() -> !; /// ISR 17, alignment check. fn _isr17() -> !; /// ISR 18, machine check. fn _isr18() -> !; /// ISR 19, simd floating point exception. fn _isr19() -> !; /// ISR 20, virtualization exception. fn _isr20() -> !; /// ISR 21, reserved. fn _isr21() -> !; /// ISR 22, reserved. fn _isr22() -> !; /// ISR 23, reserved. fn _isr23() -> !; /// ISR 24, reserved. fn _isr24() -> !; /// ISR 25, reserved. fn _isr25() -> !; /// ISR 26, reserved. fn _isr26() -> !; /// ISR 27, reserved. fn _isr27() -> !; /// ISR 28, reserved. fn _isr28() -> !; /// ISR 29, reserved. fn _isr29() -> !; /// ISR 30, security exception. fn _isr30() -> !; /// ISR 31, reserved. fn _isr31() -> !; fn _isr32() -> !; fn _isr33() -> !; fn _isr34() -> !; fn _isr35() -> !; fn _isr36() -> !; fn _isr37() -> !; fn _isr38() -> !; fn _isr39() -> !; fn _isr40() -> !; fn _isr41() -> !; fn _isr42() -> !; fn _isr43() -> !; fn _isr44() -> !; fn _isr45() -> !; fn _isr46() -> !; fn _isr47() -> !; fn _isr48() -> !; fn _isr49() -> !; fn _isr50() -> !; fn _isr51() -> !; fn _isr52() -> !; fn _isr53() -> !; fn _isr54() -> !; fn _isr55() -> !; fn _isr56() -> !; fn _isr57() -> !; fn _isr58() -> !; fn _isr59() -> !; fn _isr60() -> !; fn _isr61() -> !; fn _isr62() -> !; fn _isr63() -> !; fn _isr64() -> !; fn _isr65() -> !; fn _isr66() -> !; fn _isr67() -> !; fn _isr68() -> !; fn _isr69() -> !; fn _isr70() -> !; fn _isr71() -> !; fn _isr72() -> !; fn _isr73() -> !; fn _isr74() -> !; fn _isr75() -> !; fn _isr76() -> !; fn _isr77() -> !; fn _isr78() -> !; fn _isr79() -> !; fn _isr80() -> !; fn _isr81() -> !; fn _isr82() -> !; fn _isr83() -> !; fn _isr84() -> !; fn _isr85() -> !; fn _isr86() -> !; fn _isr87() -> !; fn _isr88() -> !; fn _isr89() -> !; fn _isr90() -> !; fn _isr91() -> !; fn _isr92() -> !; fn _isr93() -> !; fn _isr94() -> !; fn _isr95() -> !; fn _isr96() -> !; fn _isr97() -> !; fn _isr98() -> !; fn _isr99() -> !; fn _isr100() -> !; fn _isr101() -> !; fn _isr102() -> !; fn _isr103() -> !; fn _isr104() -> !; fn _isr105() -> !; fn _isr106() -> !; fn _isr107() -> !; fn _isr108() -> !; fn _isr109() -> !; fn _isr110() -> !; fn _isr111() -> !; fn _isr112() -> !; fn _isr113() -> !; fn _isr114() -> !; fn _isr115() -> !; fn _isr116() -> !; fn _isr117() -> !; fn _isr118() -> !; fn _isr119() -> !; fn _isr120() -> !; fn _isr121() -> !; fn _isr122() -> !; fn _isr123() -> !; fn _isr124() -> !; fn _isr125() -> !; fn _isr126() -> !; fn _isr127() -> !; fn _isr128() -> !; fn _isr129() -> !; fn _isr130() -> !; fn _isr131() -> !; fn _isr132() -> !; fn _isr133() -> !; fn _isr134() -> !; fn _isr135() -> !; fn _isr136() -> !; fn _isr137() -> !; fn _isr138() -> !; fn _isr139() -> !; fn _isr140() -> !; fn _isr141() -> !; fn _isr142() -> !; fn _isr143() -> !; fn _isr144() -> !; fn _isr145() -> !; fn _isr146() -> !; fn _isr147() -> !; fn _isr148() -> !; fn _isr149() -> !; fn _isr150() -> !; fn _isr151() -> !; fn _isr152() -> !; fn _isr153() -> !; fn _isr154() -> !; fn _isr155() -> !; fn _isr156() -> !; fn _isr157() -> !; fn _isr158() -> !; fn _isr159() -> !; fn _isr160() -> !; fn _isr161() -> !; fn _isr162() -> !; fn _isr163() -> !; fn _isr164() -> !; fn _isr165() -> !; fn _isr166() -> !; fn _isr167() -> !; fn _isr168() -> !; fn _isr169() -> !; fn _isr170() -> !; fn _isr171() -> !; fn _isr172() -> !; fn _isr173() -> !; fn _isr174() -> !; fn _isr175() -> !; fn _isr176() -> !; fn _isr177() -> !; fn _isr178() -> !; fn _isr179() -> !; fn _isr180() -> !; fn _isr181() -> !; fn _isr182() -> !; fn _isr183() -> !; fn _isr184() -> !; fn _isr185() -> !; fn _isr186() -> !; fn _isr187() -> !; fn _isr188() -> !; fn _isr189() -> !; fn _isr190() -> !; fn _isr191() -> !; fn _isr192() -> !; fn _isr193() -> !; fn _isr194() -> !; fn _isr195() -> !; fn _isr196() -> !; fn _isr197() -> !; fn _isr198() -> !; fn _isr199() -> !; fn _isr200() -> !; fn _isr201() -> !; fn _isr202() -> !; fn _isr203() -> !; fn _isr204() -> !; fn _isr205() -> !; fn _isr206() -> !; fn _isr207() -> !; fn _isr208() -> !; fn _isr209() -> !; fn _isr210() -> !; fn _isr211() -> !; fn _isr212() -> !; fn _isr213() -> !; fn _isr214() -> !; fn _isr215() -> !; fn _isr216() -> !; fn _isr217() -> !; fn _isr218() -> !; fn _isr219() -> !; fn _isr220() -> !; fn _isr221() -> !; fn _isr222() -> !; fn _isr223() -> !; fn _isr224() -> !; fn _isr225() -> !; fn _isr226() -> !; fn _isr227() -> !; fn _isr228() -> !; fn _isr229() -> !; fn _isr230() -> !; fn _isr231() -> !; fn _isr232() -> !; fn _isr233() -> !; fn _isr234() -> !; fn _isr235() -> !; fn _isr236() -> !; fn _isr237() -> !; fn _isr238() -> !; fn _isr239() -> !; fn _isr240() -> !; fn _isr241() -> !; fn _isr242() -> !; fn _isr243() -> !; fn _isr244() -> !; fn _isr245() -> !; fn _isr246() -> !; fn _isr247() -> !; fn _isr248() -> !; fn _isr249() -> !; fn _isr250() -> !; fn _isr251() -> !; fn _isr252() -> !; fn _isr253() -> !; fn _isr254() -> !; fn _isr255() -> !; } /// This table is used to iterate over the assocated ISRs when installing the Interrupt Descriptor Table. pub const ISR: [InterruptServiceRoutine; 256] = [ _isr0, _isr1, _isr2, _isr3, _isr4, _isr5, _isr6, _isr7, _isr8, _isr9, _isr10, _isr11, _isr12, _isr13, _isr14, _isr15, _isr16, _isr17, _isr18, _isr19, _isr20, _isr21, _isr22, _isr23, _isr24, _isr25, _isr26, _isr27, _isr28, _isr29, _isr30, _isr31, _isr32, _isr33, _isr34, _isr35, _isr36, _isr37, _isr38, _isr39, _isr40, _isr41, _isr42, _isr43, _isr44, _isr45, _isr46, _isr47, _isr48, _isr49, _isr50, _isr51, _isr52, _isr53, _isr54, _isr55, _isr56, _isr57, _isr58, _isr59, _isr60, _isr61, _isr62, _isr63, _isr64, _isr65, _isr66, _isr67, _isr68, _isr69, _isr70, _isr71, _isr72, _isr73, _isr74, _isr75, _isr76, _isr77, _isr78, _isr79, _isr80, _isr81, _isr82, _isr83, _isr84, _isr85, _isr86, _isr87, _isr88, _isr89, _isr90, _isr91, _isr92, _isr93, _isr94, _isr95, _isr96, _isr97, _isr98, _isr99, _isr100, _isr101, _isr102, _isr103, _isr104, _isr105, _isr106, _isr107, _isr108, _isr109, _isr110, _isr111, _isr112, _isr113, _isr114, _isr115, _isr116, _isr117, _isr118, _isr119, _isr120, _isr121, _isr122, _isr123, _isr124, _isr125, _isr126, _isr127, _isr128, _isr129, _isr130, _isr131, _isr132, _isr133, _isr134, _isr135, _isr136, _isr137, _isr138, _isr139, _isr140, _isr141, _isr142, _isr143, _isr144, _isr145, _isr146, _isr147, _isr148, _isr149, _isr150, _isr151, _isr152, _isr153, _isr154, _isr155, _isr156, _isr157, _isr158, _isr159, _isr160, _isr161, _isr162, _isr163, _isr164, _isr165, _isr166, _isr167, _isr168, _isr169, _isr170, _isr171, _isr172, _isr173, _isr174, _isr175, _isr176, _isr177, _isr178, _isr179, _isr180, _isr181, _isr182, _isr183, _isr184, _isr185, _isr186, _isr187, _isr188, _isr189, _isr190, _isr191, _isr192, _isr193, _isr194, _isr195, _isr196, _isr197, _isr198, _isr199, _isr200, _isr201, _isr202, _isr203, _isr204, _isr205, _isr206, _isr207, _isr208, _isr209, _isr210, _isr211, _isr212, _isr213, _isr214, _isr215, _isr216, _isr217, _isr218, _isr219, _isr220, _isr221, _isr222, _isr223, _isr224, _isr225, _isr226, _isr227, _isr228, _isr229, _isr230, _isr231, _isr232, _isr233, _isr234, _isr235, _isr236, _isr237, _isr238, _isr239, _isr240, _isr241, _isr242, _isr243, _isr244, _isr245, _isr246, _isr247, _isr248, _isr249, _isr250, _isr251, _isr252, _isr253, _isr254, _isr255, ];
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/interrupts.rs
hypervisor/src/interrupts.rs
//! This module defines various structurs used by the hypervisor to set up the //! host Interrupt Descriptor Table and handle interrupts and exceptions received //! by the host. use crate::isr; use spin::Mutex; use crate::register_state::InterruptRegisterState; #[allow(unused)] #[derive(Copy, Clone, Default)] #[repr(packed)] struct IdtEntry { base_low: u16, selector: u16, always0: u8, flags: u8, base_high: u16, base_highest: u32, _reserved: u32, } #[derive(Default)] pub struct Idt([IdtEntry; 20]); impl IdtEntry { const fn new() -> Self { IdtEntry { base_high: 0, base_highest: 0, base_low: 0, always0: 0, flags: 0, selector: 0, _reserved: 0, } } } const IDT_ENTRY_FLAGS_RING_0: u8 = 0x00; const IDT_ENTRY_FLAGS_PRESENT: u8 = 0x80; const IDT_ENTRY_FLAGS_INTERRUPT_GATE: u8 = 0x0e; impl Idt { const fn new() -> Self { Idt([IdtEntry::new(); 20]) } fn set_entry(&mut self, num: usize, base: u64, selector: u16, flags: u8) { self.0[num].base_low = (base & 0xffff) as u16; self.0[num].base_high = ((base >> 16) & 0xffff) as u16; self.0[num].base_highest = (base >> 32) as u32; self.0[num].always0 = 0; self.0[num].selector = selector; self.0[num].flags = flags; } } static IDT: Mutex<Idt> = Mutex::new(Idt::new()); pub fn host_idt_base() -> u64 { let idt = &*IDT.lock() as *const Idt; idt as u64 } #[no_mangle] pub extern "C" fn interrupt_dispatcher(state: &mut InterruptRegisterState) { panic!("Unhandled interrupt {:x?}", state); } pub fn init_interrupt_handlers(cs: u16) { let mut idt = IDT.lock(); for i in 0..20 { idt.set_entry( i, isr::ISR[i as usize] as usize as u64, cs, IDT_ENTRY_FLAGS_RING_0 | IDT_ENTRY_FLAGS_PRESENT | IDT_ENTRY_FLAGS_INTERRUPT_GATE, ); } } #[derive(Default)] #[repr(packed)] pub struct IdtDescriptor { pub limit: u16, pub base: u64, }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/segmentation.rs
hypervisor/src/segmentation.rs
//! Defines structures and code for working with x86 segments. use log::trace; use x86; const GDT_ENTRY_ACCESS_PRESENT: u8 = 1 << 7; // See Intel manual Table 24-2 ch 24-4 vol 3c const VMX_INFO_SEGMENT_UNUSABLE: u32 = 1 << 16; /// GDT entries are packed in a complicated way meant to be backwards /// compatible since the days of the i286. This represents the component parts ///of a GDT entry unpacked into a format we can feed into various host and /// guest VMCS entries. #[derive(Default, Debug)] pub struct UnpackedGdtEntry { /// The base of the segment. pub base: u64, /// The limit of the segment. pub limit: u64, /// The access rights of the segment. pub access_rights: u32, /// The segment selector. pub selector: u16, } impl UnpackedGdtEntry { /// Checks to see if the GDT entry is usable. /// If the UEFI guest TR is unusable, a new one must be created since we /// need a host TSS to launch a VM. pub fn is_usable(&self) -> bool { self.access_rights != VMX_INFO_SEGMENT_UNUSABLE } } /// Given a global descriptor table, and a selector which indexes into the /// table, unpack the corresponding GDT entry into an UnpackedGdtEntry. pub fn unpack_gdt_entry(gdt: &[GdtEntry], selector: u16) -> UnpackedGdtEntry { let mut unpacked: UnpackedGdtEntry = Default::default(); let index: usize = usize::from(selector) / core::mem::size_of::<GdtEntry>(); if index == 0 { unpacked.access_rights |= VMX_INFO_SEGMENT_UNUSABLE; trace!("Unpacked {:x?}", unpacked); return unpacked; } unpacked.selector = selector; unpacked.limit = u64::from(gdt[index].limit_low) | ((u64::from(gdt[index].granularity) & 0x0f) << 16); unpacked.base = u64::from(gdt[index].base_low); unpacked.base = (u64::from(gdt[index].base_high) << 24) | (u64::from(gdt[index].base_middle) << 16) | u64::from(gdt[index].base_low); unpacked.access_rights = u32::from(gdt[index].access); unpacked.access_rights |= u32::from((gdt[index].granularity) & 0xf0) << 8; unpacked.access_rights &= 0xf0ff; if (gdt[index].access & GDT_ENTRY_ACCESS_PRESENT) == 0 { unpacked.access_rights |= VMX_INFO_SEGMENT_UNUSABLE; } trace!("Gdt entry {:x?}", gdt[index]); trace!("Gdt entry unpacked {:x?}", unpacked); unpacked } /// 32 bit GDT entry. /// The layout of this structure is determined by hardware. /// For more information see the Intel manual, Volume 3, Chapter 5 /// ("Protection"), Section 5.2 "Fields and Flags Used for Segment-Level and /// Page-Level Protection". /// See also the OS Dev wiki page on the [GDT](https://wiki.osdev.org/GDT) and /// the accompanying [tutorial](https://wiki.osdev.org/GDT_Tutorial). #[derive(Debug, Clone, Copy)] #[allow(unused)] #[repr(packed)] pub struct GdtEntry { /// Low 16 bits of the segment limit. pub limit_low: u16, /// Low 16 bits of the segment base. pub base_low: u16, /// Middle 8 bits of the segment base. pub base_middle: u8, /// Various flags used to set segment type and access rights. pub access: u8, /// The low 4 bits are part of the limit. The high 4 bits are the /// granularity of the segment and the size. pub granularity: u8, /// High 8 bits of the segment base. pub base_high: u8, } /// 64 bit GDT entry. /// The layout of this structure is determined by hardware. /// For more information see the Intel manual, Volume 3, Chapter 3 /// ("Protected-Mode Memory Management"), "Section 3.5.2 Segment Descriptor /// Tables in IA-32e Mode". /// See also Volume 3, Chapter 7 ("Task Mangement"), Section 7.2.3 "TSS /// Descriptor in 64-bit mode". /// See also the OS Dev wiki page on the [GDT](https://wiki.osdev.org/GDT) and /// the accompanying [tutorial](https://wiki.osdev.org/GDT_Tutorial). #[allow(unused)] #[repr(packed)] pub struct GdtEntry64 { /// Low 16 bits of the segment limit. pub limit_low: u16, /// Low 16 bits of the segment base. pub base_low: u16, /// Middle 8 bits of the segment base. pub base_middle: u8, /// Various flags used to set segment type and access rights. pub access: u8, /// The low 4 bits are part of the limit. The high 4 bits are the /// granularity of the segment and the size. pub granularity: u8, /// Higher 8 bits of the segment base. pub base_high: u8, /// Highest 32 bits of the segment base. pub base_highest: u32, /// Reserved 0. pub reserved0: u32, } /// Get a reference to the processor's current GDT. /// Note that we can't pub fn get_current_gdt() -> &'static [GdtEntry] { let mut gdtr: x86::dtables::DescriptorTablePointer<u64> = Default::default(); unsafe { x86::dtables::sgdt(&mut gdtr); } trace!("Gdtr is {:x?}", gdtr); let bytes = usize::from(gdtr.limit) + 1; unsafe { core::slice::from_raw_parts( gdtr.base as *const GdtEntry, bytes / core::mem::size_of::<GdtEntry>(), ) } } /// Global Descriptor Table Register. /// Describes the size and base of the GDT. /// For more information see the Intel manual, Volume 3, Chapter 2 ("System /// Architecture Overview"), Section 2.4.1 "Global Descriptor Table Register /// GDTR)", and the accompanying figure. /// See also the OS Dev wiki page on the [GDT](https://wiki.osdev.org/GDT) and /// the accompanying [tutorial](https://wiki.osdev.org/GDT_Tutorial). #[derive(Default)] #[repr(packed)] pub struct GdtDescriptor { /// The limit of the Global Descriptor Table. /// That is the size of the GDT minus one. pub limit: u16, /// The base virtual address of the GDT. pub base: u64, } /// The Task Struct Segment. /// This is used for hardware task switching on 32 bit x86 and for holding /// interrupt stack bases on 64 bit x86. /// For more information see the Intel manual, Volume 3, Chapter 7 ("Task /// Management"), Figure 7-11 "64-Bit TSS Format". /// and the OS Dev wiki page on the /// [TSS](https://wiki.osdev.org/Task_State_Segment). #[allow(unused)] #[repr(packed)] pub struct Tss { reserved0: u32, stack0: u64, stack1: u64, stack2: u64, reserved1: u64, ist: [u64; 7], reserved2: u64, reserved3: u16, iomap_base: u16, }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmx.rs
hypervisor/src/vmx.rs
//! Functions for working with the intel VMX extensions. use ::log::{error, info, trace}; use x86; use core::{mem, ptr}; use crate::msr::{rdmsr, rdmsrl, wrmsr, Msr}; use crate::vmcs_fields::VmcsField; use crate::{vmcs, VCpu}; const IA32_FEATURE_CONTROL_LOCK_BIT: u32 = 1 << 0; const IA32_FEATURE_CONTROL_VMX_ENABLED_OUTSIDE_SMX_BIT: u32 = 1 << 2; #[repr(u32)] pub enum CPUIDLeaf { ProcessorInfoAndFeatures = 1, } #[repr(u32)] pub enum CPUIDLeafProcessorInfoAndFeaturesECXBits { VMXAvailable = 1 << 5, HypervisorPresent = 1 << 31, } pub const fn is_page_aligned(n: u64) -> bool { n.trailing_zeros() >= 12 } /// Read a field from the currently loaded virtual machine control structure. /// /// # Safety /// This must be called from within VMX root operation (i.e. after vmxon happens), /// and after a vmcs has been loaded with vmptrld. pub fn vmread(field: VmcsField) -> Result<u64, x86::vmx::VmFail> { unsafe { x86::bits64::vmx::vmread(field as u32) } } /// Write a field to the currently loaded virtual machine control structure. /// /// # Safety /// This must be called from within VMX root operation (i.e. after vmxon happens), /// and after a vmcs has been loaded with vmptrld. pub fn vmwrite(field: VmcsField, val: u64) -> Result<(), x86::vmx::VmFail> { unsafe { x86::bits64::vmx::vmwrite(field as u32, val) } } /// Read the contents of the current machine's dr7 (debug register 7). pub fn read_dr7() -> u64 { let ret: u64; unsafe { asm!("mov {}, dr7", out(reg)(ret)); } ret } /// Returns true if the Intel vmx extensions are available and a hypervisor is not present, false otherwise. fn vmx_available() -> bool { let result = unsafe { core::arch::x86_64::__cpuid(CPUIDLeaf::ProcessorInfoAndFeatures as u32) }; result.ecx & (CPUIDLeafProcessorInfoAndFeaturesECXBits::VMXAvailable as u32) != 0 && result.ecx & (CPUIDLeafProcessorInfoAndFeaturesECXBits::HypervisorPresent as u32) == 0 } /// Gets the current VMCS revision identifier. /// This is used to initialize the vmxon region and the vmcs. fn get_vmcs_revision_identifier() -> u32 { let pair = rdmsr(Msr::Ia32VmxBasic); let vmcs_revision_identifier = pair.eax; assert!((vmcs_revision_identifier & (1 << 31)) == 0); vmcs_revision_identifier } fn set_cr0_bits() { let fixed0 = rdmsrl(Msr::Ia32VmxCr0Fixed0); let fixed1 = rdmsrl(Msr::Ia32VmxCr0Fixed1); let mut cr0 = unsafe { x86::controlregs::cr0() }; cr0 |= x86::controlregs::Cr0::from_bits_truncate(fixed0 as usize); cr0 &= x86::controlregs::Cr0::from_bits_truncate(fixed1 as usize); unsafe { x86::controlregs::cr0_write(cr0); } } fn set_cr4_bits() { let fixed0 = rdmsrl(Msr::Ia32VmxCr4Fixed0); let fixed1 = rdmsrl(Msr::Ia32VmxCr4Fixed1); let mut cr4 = unsafe { x86::controlregs::cr4() }; cr4 |= x86::controlregs::Cr4::from_bits_truncate(fixed0 as usize); cr4 &= x86::controlregs::Cr4::from_bits_truncate(fixed1 as usize); unsafe { x86::controlregs::cr4_write(cr4); } } fn set_lock_bit() -> Result<(), ()> { let mut pair = rdmsr(Msr::Ia32FeatureControl); if (pair.eax & IA32_FEATURE_CONTROL_LOCK_BIT) == 0 { info!("Setting lock bit"); pair.eax |= IA32_FEATURE_CONTROL_VMX_ENABLED_OUTSIDE_SMX_BIT | IA32_FEATURE_CONTROL_LOCK_BIT; wrmsr(Msr::Ia32FeatureControl, pair); Ok(()) } else if (pair.eax & IA32_FEATURE_CONTROL_VMX_ENABLED_OUTSIDE_SMX_BIT) == 0 { error!("Lock bit is set but vmx is disabled. Hypervisor cannot start"); Err(()) } else { Ok(()) } } fn prepare_vmx_memory_region(vmx_region: *mut u32, vmx_region_size: usize) { assert!(!vmx_region.is_null()); assert!(vmx_region_size <= 0x1000); assert!(vmx_region_size > mem::size_of::<u32>()); unsafe { ptr::write_bytes(vmx_region, 0, vmx_region_size / core::mem::size_of::<u32>()); ptr::write(vmx_region, get_vmcs_revision_identifier()); trace!("Setting vmxon region identifier {:x}", *vmx_region); } } pub enum VmxEnablementError { VmxExtensionsAbsent, InvalidVmxOnRegion, LockBitSetButVmxDisabled, VmxOnFailure, } pub fn enable( vmxon_region: *mut u32, vmxon_region_phys: u64, vmxon_region_size: usize, ) -> Result<(), VmxEnablementError> { assert!(is_page_aligned(vmxon_region as u64)); assert!(is_page_aligned(vmxon_region_phys)); if vmxon_region.is_null() { error!("Bad VMX on region"); return Err(VmxEnablementError::VmxExtensionsAbsent); } if !vmx_available() { error!("VMX unavailable"); return Err(VmxEnablementError::InvalidVmxOnRegion); } trace!("Setting lock bit"); set_lock_bit().map_err(|_| { error!("Lock bit not set"); VmxEnablementError::LockBitSetButVmxDisabled })?; trace!("Setting cr0 bits"); set_cr0_bits(); trace!("Setting cr4 bits"); set_cr4_bits(); trace!("Preparing vmxon region"); prepare_vmx_memory_region(vmxon_region, vmxon_region_size); trace!("Doing vmxon"); match unsafe { x86::bits64::vmx::vmxon(vmxon_region_phys) } { Ok(()) => { trace!("vmxon succeeded"); Ok(()) } Err(e) => { error!("vmxon failed {:x?}", e); Err(VmxEnablementError::VmxOnFailure) } } } pub fn disable() { unimplemented!(); } extern "C" { fn _guest_first_entry() -> usize; } pub fn load_vm(vcpu: &VCpu) -> Result<(), x86::vmx::VmFail> { trace!( "Loading vmm with vcpu {:x?} {:x?}", vcpu, vcpu as *const VCpu ); assert!(is_page_aligned(vcpu.vmcs as u64)); assert!(is_page_aligned(vcpu.vmcs_phys)); trace!("Preparing vmcs"); prepare_vmx_memory_region(vcpu.vmcs, vcpu.vmcs_size); trace!("vmclear"); unsafe { x86::bits64::vmx::vmclear(vcpu.vmcs_phys)?; } trace!("vmptrld"); unsafe { x86::bits64::vmx::vmptrld(vcpu.vmcs_phys)?; } trace!("Initializing vm control values "); vmcs::initialize_vm_control_values(vcpu)?; trace!("Initializing host state"); vmcs::initialize_host_state(vcpu)?; trace!("Initializing guest state"); vmcs::initialize_guest_state(vcpu)?; trace!("Launching..."); crate::vmcs_dump::dump(); let guest_first_entry_result = unsafe { _guest_first_entry() }; match guest_first_entry_result { 0 => { //trace!("Successfully entered the guest"); Ok(()) } 1 => { trace!("vmfailvalid"); Err(x86::vmx::VmFail::VmFailValid) } 2 => { trace!("vmfailinvalid"); Err(x86::vmx::VmFail::VmFailInvalid) } other => { trace!("unknown guest entry code {:x}", other); Err(x86::vmx::VmFail::VmFailInvalid) } } } pub fn unload_vm() { /* if let Ok(vmcs_phys) = vmptrst() { if let Err(code) = vmclear(vmcs_phys) { error!("vmclear failed with error code {}", code); } } */ unimplemented!(); }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmexit_handlers.rs
hypervisor/src/vmexit_handlers.rs
//! This module defines the host's VM exit handlers. //use crate::interrupt_controller; use crate::hypercall_handler; use crate::register_state::GeneralPurposeRegisterState; use crate::vmcs_dump; use crate::vmcs_fields::VmcsField; use crate::vmexit_reasons::*; use crate::vmx; use crate::vmx::vmread; use crate::vmx::vmwrite; use log::trace; /// Advance the guest's instruction pointer by the length of the instruction /// being executed by the guest when the VM exit occurred. When the guest /// resumes, it will start executing the next instruction. /// This function should not be called more than once per VM exit, or the guest /// may begin executing illegal or unintended instructions. fn advance_guest_rip() -> Result<(), x86::vmx::VmFail> { let mut rip = vmread(VmcsField::GuestRip)?; let len = vmread(VmcsField::VmExitInstructionLen)?; rip += len; vmwrite(VmcsField::GuestRip, rip) } /// Handle CPUID /// In most cases, report back the host's CPUID values with the following exceptions: /// - Clear the VMX available bit /// - If RAX has the magic value 'rsty' or 0x72737479 this is a hypercall, so /// call the hypercall handler. /// - Do not set the hypervisor bit, to be stealthy. fn handle_cpuid(gprs: &mut GeneralPurposeRegisterState) -> Result<(), x86::vmx::VmFail> { advance_guest_rip()?; if gprs.rax as u32 == hypervisor_abi::HYPERCALL_MAGIC { return hypercall_handler::handle_hypercall(gprs); } let mut result = unsafe { core::arch::x86_64::__cpuid(gprs.rax as u32) }; if gprs.rax == vmx::CPUIDLeaf::ProcessorInfoAndFeatures as u64 { result.ecx &= vmx::CPUIDLeafProcessorInfoAndFeaturesECXBits::VMXAvailable as u32; } gprs.rax = u64::from(result.eax); gprs.rbx = u64::from(result.ebx); gprs.rcx = u64::from(result.ecx); gprs.rdx = u64::from(result.edx); Ok(()) } /// Emulate control register access. When a control register access VM exit /// occurs, perform that access, e.g. load from the control register or a store /// to it, on the underlying hardware (since this is a mostly passthrough /// hypervisor). /// At present we do not implement the CLTS or LMSW instructions since they are /// unused by major operating systems. fn handle_control_register_access( gprs: &mut GeneralPurposeRegisterState, ) -> Result<(), x86::vmx::VmFail> { // 27-6 vol 3c table 27-3 exit qual for cr access let qualification = vmread(VmcsField::ExitQualificatIon)?; let crnum = qualification & 0xf; let access_type = (qualification >> 4) & 0x3; // Presently unimplemented, but here when I need it. See comment below. //usize lmsw_type = (qualification >> 6) & 1; let regnum = (qualification >> 8) & 0xf; let field = match crnum { 0 => VmcsField::GuestCr0, 3 => VmcsField::GuestCr3, 4 => VmcsField::GuestCr4, _ => panic!("Illegal crnum from qualification {:x}", qualification), }; let register = gprs.by_mod_rm_index(regnum); match access_type { // Write 0 => { let value = match register { Some(reg) => *reg, None => vmread(VmcsField::GuestRsp)?, }; vmwrite(field, value)?; } // Read 1 => { let value = vmread(field)?; match register { Some(reg) => { *reg = value; } None => vmwrite(VmcsField::GuestRsp, value)?, } } // FIXME: implement LMSW & CLTS. // I don't believe any major OS uses them. _ => { unimplemented!("Unhandled CR access. Qualification {:x}", qualification); } } advance_guest_rip()?; Ok(()) } /// Handle a VM Exit. This function will be called by the assembly code in /// the function _host_entrypoint when a VM exit occurs. /// This function must handle the exit reason or panic. /// The guest will be resumed using the current vmcs and the guest general /// purpose register state when this function returns. #[no_mangle] pub extern "C" fn hypervisor_handle_vmexit(gprs: *mut GeneralPurposeRegisterState) { let gprs = unsafe { &mut *gprs }; let vmexit_reasion = vmread(VmcsField::VmExitReason).expect("vm exit reason shouldn't error"); let qualification = vmread(VmcsField::ExitQualificatIon).unwrap_or(0); match vmexit_reasion { VMEXIT_REASON_CPUID => handle_cpuid(gprs).unwrap(), VMEXIT_REASON_CONTROL_REGISTER_ACCESS => { handle_control_register_access(gprs).unwrap(); } /* VMEXIT_REASON_EXTERNAL_INTERRUPT => { trace!("Got external interrupt {:x?}", vmread(VmcsField::GuestRip)); crate::debug::breakpoint(); interrupt_controller::received_external_interrupt().unwrap(); vmcs_dump::dump(); }, VMEXIT_REASON_PREEMPTION_TIMER_EXPIRED => { trace!("vmx preemption timer expired"); interrupt_controller::received_preemption_timer().unwrap(); }, VMEXIT_REASON_INTERRUPT_WINDOW => { trace!("vmx interrupt window available"); interrupt_controller::received_interrupt_window_exit().unwrap(); } */ reason => { trace!("{:x?}", gprs); vmcs_dump::dump(); panic!( "Unhandled vm exit reason {:x} qualification {:x}", reason, qualification ); } } } /// Called by [_host_entrypoint](../vmcs/fn._host_entrypoint.html) when a VM /// resume failure occurs. If the host cannot resume the guest, it must have /// misconfigured the guest's state, which is a bug in the hypervisor. /// This function panics. #[no_mangle] pub extern "C" fn hypervisor_vmresume_failure() { unimplemented!(); }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/lib.rs
hypervisor/src/lib.rs
#![no_std] #![feature(asm)] #![feature(lang_items)] #![allow(unknown_lints)] #![warn(missing_docs)] //! A library implementing a mostly-passthrough hypervisor. //! A mostly passthrough hypervisor mostly virtualizes the guest and does very //! little emulation of hardware or devices, but can be used to inspect guest //! state. //! This library is expected to be embedded in a loader environment, e.g. a //! UEFI runtim service or a Linux kernel module. //! //! This library exports the [VCpu structure](struct.VCpu.html), and four functions. //! The loader environment is expected to allocate and initialize a VCpu for //! each logical core, and then load the hypervisor. //! The loader environment may unload the hypervisor or the hypervisor may //! unload itself. //! //! To load the hypervisor: //! 1. Once globally, call [rustyvisor_load](fn.rustyvisor_load.html) //! 2. On each logical core, call [rustyvisor_core_load](fn.rustyvisor_core_load.html) //! //! To unload the hypervisor after it has been loaded: //! 1. On each logical core, call [rustyvisor_core_unload](fn.rustyvisor_core_unload.html) //! 2. Once globally, call [rustyvisor_unload](fn.rustyvisor_unload.html) use ::log::{error, info, trace, LevelFilter}; extern crate hypervisor_abi; mod debug; mod hypercall_handler; pub mod interrupt_controller; mod interrupts; mod isr; mod msr; mod panic; mod register_state; pub mod segmentation; mod vcpu; mod vmcs; mod vmcs_dump; mod vmcs_fields; mod vmexit_handlers; mod vmexit_reasons; mod vmx; #[cfg(target_os = "uefi")] use pcuart::logger; #[cfg(target_os = "uefi")] /// Logger used by the hypervisor when loading the guest and while running. pub static LOGGER: logger::UartLogger = logger::UartLogger::new(pcuart::UartComPort::Com1); #[cfg(target_os = "uefi")] /// Logger used by the hypervisor when panicking. pub static UNSYNCHRONIZED_LOGGER: logger::UnsynchronizedUartLogger = logger::UnsynchronizedUartLogger::new(pcuart::UartComPort::Com1); #[cfg(not(target_os = "uefi"))] use dmesg_logger as logger; #[cfg(not(target_os = "uefi"))] /// Logger used by the hypervisor when loading the guest and while running. pub static LOGGER: logger::DMesgLogger = logger::DMesgLogger {}; #[cfg(not(target_os = "uefi"))] /// Logger used by the hypervisor when panicking. pub static UNSYNCHRONIZED_LOGGER: logger::DMesgLogger = logger::DMesgLogger {}; /// This structure represents all of the data the hypervisor needs for a single CPU. /// The environment loader, e.g. UEFI bindings or linux kernel bindings, needs /// to allocate this structure on memory which will be accessible for the /// lifetime of the hypervisor. /// /// At present we represent fields as C-style pointers for virtual addresses /// usable by the host instead of rust style references, so that we can write /// the environment loader in another language like C. /// Physical addresses are represented as u64s. #[derive(Debug)] #[repr(C)] pub struct VCpu { /// A pointer to the virtual address representing this VCpu structure. /// In hypervisor host context we will set the fs base to point to this /// structure. This way we can get a pointer to this structure by accessing /// fs:0. See [get_current_vcpu](vcpu/fn.get_current_vcpu.html) for more /// details. pub this_vcpu: *mut VCpu, /// The virtual address of this core's vmx on region. This is used by the /// hardware as scratch space and its contents are largely opaque to the /// hypervisor. Must be at least a page. pub vmxon_region: *mut u32, /// A pointer to this core's virtual machine control structure. /// The virtual machine control structure, or vmcs, is used to control the /// state of the processor when entering and exiting virtualization, as /// well as control what events cause vm exits and the hardware /// capabilitiesexposed by the hypervisor. Must be at least a page. pub vmcs: *mut u32, /// The physical address of the vmxon region. Must back the vmxon_region /// virtual address above. pub vmxon_region_phys: u64, /// The physical address of the vmcs. Must back the vmxon_region /// virtual address above. pub vmcs_phys: u64, /// Size in bytes of the vmx on region. Must be at least a page. pub vmxon_region_size: usize, /// Size in bytes of the vmcs. Must be at least a page. pub vmcs_size: usize, /// True if the hypervisor loaded successfully on this core, false /// otherwise. pub loaded_successfully: bool, /// The virtual address of the base of the hypervisor host's stack. pub stack_base: *mut u8, /// The size of the hypervisor host's stack. pub stack_size: usize, /// The virtual address of the top of the hypervisor host's stack. pub stack_top: *mut u8, /// The base address of the host's global descriptor table. Get using the /// instruction sgdt. pub host_gdt_base: *mut u64, /// The limit, or size in bytes minus one, of the host's global descriptor /// table. Get using the instruction sgdt. pub host_gdt_limit: u64, /// The virtual address of the host's virtual interrupt controller. Must be /// initialized as zeroes. pub virtual_local_interrupt_controller: *mut interrupt_controller::VirtualLocalInterruptController, /// The physical address of the 4k/1 page MSR bitmap on processes which /// support MSR bitmaps. /// The backing memory must be zeroed. pub msr_bitmap: u64, /// The virtual address of the base of the TSS, a mostly vestigal structure /// required by the CPU for hardware task switching. pub tr_base: u64, /// The selector of the TSS segment. pub tr_selector: u16, } /// Set up hypervisor global state. Must be one called only once by the loader /// before rustyvisor_core_load is called. Sets up the logger, the Interrupt /// Descriptor Table and any host state used for every core. /// This function must be called at most once per load of the hypervisor and in /// the following sequence of calls: /// 1. Once globally, call [rustyvisor_load](fn.rustyvisor_load.html) /// 2. On each logical core, call [rustyvisor_core_load](fn.rustyvisor_core_load.html) /// 3. On each logical core, call [rustyvisor_core_unload](fn.rustyvisor_core_unload.html) /// 4. Once globally, call [rustyvisor_unload](fn.rustyvisor_unload.html) /// This function may be called on any processor, not just the bootstrap /// processor. #[no_mangle] pub extern "C" fn rustyvisor_load() -> i32 { let logger_result = log::set_logger(&LOGGER).map(|()| log::set_max_level(LevelFilter::Trace)); match logger_result { Ok(()) => {} Err(_) => return -1, } info!("{}", "rustyvisor_load"); interrupts::init_interrupt_handlers(x86::segmentation::cs().bits()); #[cfg(feature = "runtime_tests")] runtime_tests(); 0 } /// Load the hypervisor on the current logical core. /// Enables VMX on the current core and enters vmx guest operation. /// After returning, the caller will be running as a VM guest. /// This function must be called at most once per-core and in the following /// sequence of calls: /// 1. Once globally, call [rustyvisor_load](fn.rustyvisor_load.html) /// 2. On each logical core, call [rustyvisor_core_load](fn.rustyvisor_core_load.html) /// 3. On each logical core, call [rustyvisor_core_unload](fn.rustyvisor_core_unload.html) /// 4. Once globally, call [rustyvisor_unload](fn.rustyvisor_unload.html) #[no_mangle] pub extern "C" fn rustyvisor_core_load(data: &VCpu) -> i32 { trace!( "VCPU in rustyvisor_core_load {:x?} {:x?}\r\n", data, data as *const VCpu ); trace!("Enabling vmx"); if vmx::enable( data.vmxon_region, data.vmxon_region_phys, data.vmxon_region_size, ) .is_err() { error!("Failed to enable VMX"); return -1; } trace!( "VCPU in rustyvisor_core_load enable {:x?} {:x?}\r\n", data, data as *const VCpu ); trace!("Vmx enabled"); trace!("Loading vmm {:x?}", data); if vmx::load_vm(data).is_err() { error!("Failed to load VMX"); return 1; } 0 } /// Unload the hypervisor from the current logical core. Disables VMX operation once /// the hypervisor is unloaded. When this function returns, the core will be /// running in VMX root operation, i.e. not as a VM guest. /// This function must be called at most once per-core and in the following /// sequence of calls: /// 1. Once globally, call [rustyvisor_load](fn.rustyvisor_load.html) /// 2. On each logical core, call [rustyvisor_core_load](fn.rustyvisor_core_load.html) /// 3. On each logical core, call [rustyvisor_core_unload](fn.rustyvisor_core_unload.html) /// 4. Once globally, call [rustyvisor_unload](fn.rustyvisor_unload.html) #[no_mangle] pub extern "C" fn rustyvisor_core_unload() { info!("Core unload"); vmx::unload_vm(); vmx::disable(); } /// Tear down hypervisor global state. /// This function must be called at most once per load of the hypervisor and in /// the following sequence of calls: /// 1. Once globally, call [rustyvisor_load](fn.rustyvisor_load.html) /// 2. On each logical core, call [rustyvisor_core_load](fn.rustyvisor_core_load.html) /// 3. On each logical core, call [rustyvisor_core_unload](fn.rustyvisor_core_unload.html) /// 4. Once globally, call [rustyvisor_unload](fn.rustyvisor_unload.html) /// This function may be called on any processor, not just the bootstrap /// processor. #[no_mangle] pub extern "C" fn rustyvisor_unload() { info!("Hypervisor unloaded."); } /// Stub for hypervisor runtime tests. #[cfg(feature = "runtime_tests")] fn runtime_tests() { info!("Executing runtime tests..."); info!("Runtime tests succeeded"); }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmcs_dump.rs
hypervisor/src/vmcs_dump.rs
//! Dump the state of the current vmcs. use crate::vmcs; use crate::vmcs_fields::VmcsField; use crate::vmx::vmread; use log::debug; /// Log the state of the current vmcs at debug level. pub fn dump() { let val = vmread(VmcsField::VirtualProcessorID).unwrap_or(0xbadc0de); debug!("VirtualProcessorID: {:x}", val); let val = vmread(VmcsField::PostedIntrNV).unwrap_or(0xbadc0de); debug!("PostedIntrNV: {:x}", val); let val = vmread(VmcsField::GuestEsSelector).unwrap_or(0xbadc0de); debug!("GuestEsSelector: {:x}", val); let val = vmread(VmcsField::GuestCsSelector).unwrap_or(0xbadc0de); debug!("GuestCsSelector: {:x}", val); let val = vmread(VmcsField::GuestSsSelector).unwrap_or(0xbadc0de); debug!("GuestSsSelector: {:x}", val); let val = vmread(VmcsField::GuestDsSelector).unwrap_or(0xbadc0de); debug!("GuestDsSelector: {:x}", val); let val = vmread(VmcsField::GuestFsSelector).unwrap_or(0xbadc0de); debug!("GuestFsSelector: {:x}", val); let val = vmread(VmcsField::GuestGsSelector).unwrap_or(0xbadc0de); debug!("GuestGsSelector: {:x}", val); let val = vmread(VmcsField::GuestLdtrSelector).unwrap_or(0xbadc0de); debug!("GuestLdtrSelector: {:x}", val); let val = vmread(VmcsField::GuestTrSelector).unwrap_or(0xbadc0de); debug!("GuestTrSelector: {:x}", val); let val = vmread(VmcsField::GuestIntrStatus).unwrap_or(0xbadc0de); debug!("GuestIntrStatus: {:x}", val); let val = vmread(VmcsField::GuestPmlIndex).unwrap_or(0xbadc0de); debug!("GuestPmlIndex: {:x}", val); let val = vmread(VmcsField::HostEsSelector).unwrap_or(0xbadc0de); debug!("HostEsSelector: {:x}", val); let val = vmread(VmcsField::HostCsSelector).unwrap_or(0xbadc0de); debug!("HostCsSelector: {:x}", val); let val = vmread(VmcsField::HostSsSelector).unwrap_or(0xbadc0de); debug!("HostSsSelector: {:x}", val); let val = vmread(VmcsField::HostDsSelector).unwrap_or(0xbadc0de); debug!("HostDsSelector: {:x}", val); let val = vmread(VmcsField::HostFsSelector).unwrap_or(0xbadc0de); debug!("HostFsSelector: {:x}", val); let val = vmread(VmcsField::HostGsSelector).unwrap_or(0xbadc0de); debug!("HostGsSelector: {:x}", val); let val = vmread(VmcsField::HostTrSelector).unwrap_or(0xbadc0de); debug!("HostTrSelector: {:x}", val); let val = vmread(VmcsField::IoBitmapA).unwrap_or(0xbadc0de); debug!("IoBitmapA: {:x}", val); let val = vmread(VmcsField::IoBitmapAHigh).unwrap_or(0xbadc0de); debug!("IoBitmapAHigh: {:x}", val); let val = vmread(VmcsField::IoBitmapB).unwrap_or(0xbadc0de); debug!("IoBitmapB: {:x}", val); let val = vmread(VmcsField::IoBitmapBHigh).unwrap_or(0xbadc0de); debug!("IoBitmapBHigh: {:x}", val); let val = vmread(VmcsField::MsrBitmap).unwrap_or(0xbadc0de); debug!("MsrBitmap: {:x}", val); let val = vmread(VmcsField::MsrBitmapHigh).unwrap_or(0xbadc0de); debug!("MsrBitmapHigh: {:x}", val); let val = vmread(VmcsField::VmExitMsrStoreAddr).unwrap_or(0xbadc0de); debug!("VmExitMsrStoreAddr: {:x}", val); let val = vmread(VmcsField::VmExitMsrStoreAddrHigh).unwrap_or(0xbadc0de); debug!("VmExitMsrStoreAddrHigh: {:x}", val); let val = vmread(VmcsField::VmExitMsrLoadAddr).unwrap_or(0xbadc0de); debug!("VmExitMsrLoadAddr: {:x}", val); let val = vmread(VmcsField::VmExitMsrLoadAddrHigh).unwrap_or(0xbadc0de); debug!("VmExitMsrLoadAddrHigh: {:x}", val); let val = vmread(VmcsField::VmEntryMsrLoadAddr).unwrap_or(0xbadc0de); debug!("VmEntryMsrLoadAddr: {:x}", val); let val = vmread(VmcsField::VmEntryMsrLoadAddrHigh).unwrap_or(0xbadc0de); debug!("VmEntryMsrLoadAddrHigh: {:x}", val); let val = vmread(VmcsField::PMLAddress).unwrap_or(0xbadc0de); debug!("PMLAddress: {:x}", val); let val = vmread(VmcsField::PMLAddressHigh).unwrap_or(0xbadc0de); debug!("PMLAddressHigh: {:x}", val); let val = vmread(VmcsField::TscOffset).unwrap_or(0xbadc0de); debug!("TscOffset: {:x}", val); let val = vmread(VmcsField::TscOffsetHigh).unwrap_or(0xbadc0de); debug!("TscOffsetHigh: {:x}", val); let val = vmread(VmcsField::VirtualApicPageAddr).unwrap_or(0xbadc0de); debug!("VirtualApicPageAddr: {:x}", val); let val = vmread(VmcsField::VirtualApicPageAddrHigh).unwrap_or(0xbadc0de); debug!("VirtualApicPageAddrHigh: {:x}", val); let val = vmread(VmcsField::APICAccessAddr).unwrap_or(0xbadc0de); debug!("APICAccessAddr: {:x}", val); let val = vmread(VmcsField::APICAccessAddrHigh).unwrap_or(0xbadc0de); debug!("APICAccessAddrHigh: {:x}", val); let val = vmread(VmcsField::PostedIntrDescAddr).unwrap_or(0xbadc0de); debug!("PostedIntrDescAddr: {:x}", val); let val = vmread(VmcsField::PostedIntrDescAddrHigh).unwrap_or(0xbadc0de); debug!("PostedIntrDescAddrHigh: {:x}", val); let val = vmread(VmcsField::EPTPointer).unwrap_or(0xbadc0de); debug!("EPTPointer: {:x}", val); let val = vmread(VmcsField::EPTPointerHigh).unwrap_or(0xbadc0de); debug!("EPTPointerHigh: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap0).unwrap_or(0xbadc0de); debug!("EoiExitBitmap0: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap0High).unwrap_or(0xbadc0de); debug!("EoiExitBitmap0High: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap1).unwrap_or(0xbadc0de); debug!("EoiExitBitmap1: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap1High).unwrap_or(0xbadc0de); debug!("EoiExitBitmap1High: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap2).unwrap_or(0xbadc0de); debug!("EoiExitBitmap2: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap2High).unwrap_or(0xbadc0de); debug!("EoiExitBitmap2High: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap3).unwrap_or(0xbadc0de); debug!("EoiExitBitmap3: {:x}", val); let val = vmread(VmcsField::EoiExitBitmap3High).unwrap_or(0xbadc0de); debug!("EoiExitBitmap3High: {:x}", val); let val = vmread(VmcsField::VmReadBitmap).unwrap_or(0xbadc0de); debug!("VmReadBitmap: {:x}", val); let val = vmread(VmcsField::VmWriteBitmap).unwrap_or(0xbadc0de); debug!("VmWriteBitmap: {:x}", val); let val = vmread(VmcsField::XssExitBitmap).unwrap_or(0xbadc0de); debug!("XssExitBitmap: {:x}", val); let val = vmread(VmcsField::XssExitBitmapHigh).unwrap_or(0xbadc0de); debug!("XssExitBitmapHigh: {:x}", val); let val = vmread(VmcsField::TsxMultiplier).unwrap_or(0xbadc0de); debug!("TsxMultiplier: {:x}", val); let val = vmread(VmcsField::TsxMultiplierHigh).unwrap_or(0xbadc0de); debug!("TsxMultiplierHigh: {:x}", val); let val = vmread(VmcsField::GuestPhysicalAddress).unwrap_or(0xbadc0de); debug!("GuestPhysicalAddress: {:x}", val); let val = vmread(VmcsField::GuestPhysicalAddressHigh).unwrap_or(0xbadc0de); debug!("GuestPhysicalAddressHigh: {:x}", val); let val = vmread(VmcsField::VmcsLinkPointer).unwrap_or(0xbadc0de); debug!("VmcsLinkPointer: {:x}", val); let val = vmread(VmcsField::VmcsLinkPointerHigh).unwrap_or(0xbadc0de); debug!("VmcsLinkPointerHigh: {:x}", val); let val = vmread(VmcsField::GuestIA32Debugctl).unwrap_or(0xbadc0de); debug!("GuestIA32Debugctl: {:x}", val); let val = vmread(VmcsField::GuestIA32DebugctlHigh).unwrap_or(0xbadc0de); debug!("GuestIA32DebugctlHigh: {:x}", val); let val = vmread(VmcsField::GuestIA32Pat).unwrap_or(0xbadc0de); debug!("GuestIA32Pat: {:x}", val); let val = vmread(VmcsField::GuestIA32PatHigh).unwrap_or(0xbadc0de); debug!("GuestIA32PatHigh: {:x}", val); let val = vmread(VmcsField::GuestIA32Efer).unwrap_or(0xbadc0de); debug!("GuestIA32Efer: {:x}", val); let val = vmread(VmcsField::GuestIA32EferHigh).unwrap_or(0xbadc0de); debug!("GuestIA32EferHigh: {:x}", val); let val = vmread(VmcsField::GuestIA32PerfGlobalCtrl).unwrap_or(0xbadc0de); debug!("GuestIA32PerfGlobalCtrl: {:x}", val); let val = vmread(VmcsField::GuestIA32PerfGlobalCtrlHigh).unwrap_or(0xbadc0de); debug!("GuestIA32PerfGlobalCtrlHigh: {:x}", val); let val = vmread(VmcsField::GuestPDPtr0).unwrap_or(0xbadc0de); debug!("GuestPDPtr0: {:x}", val); let val = vmread(VmcsField::GuestPDPtr0High).unwrap_or(0xbadc0de); debug!("GuestPDPtr0High: {:x}", val); let val = vmread(VmcsField::GuestPDPtr1).unwrap_or(0xbadc0de); debug!("GuestPDPtr1: {:x}", val); let val = vmread(VmcsField::GuestPDPtr1High).unwrap_or(0xbadc0de); debug!("GuestPDPtr1High: {:x}", val); let val = vmread(VmcsField::GuestPDPtr2).unwrap_or(0xbadc0de); debug!("GuestPDPtr2: {:x}", val); let val = vmread(VmcsField::GuestPDPtr2High).unwrap_or(0xbadc0de); debug!("GuestPDPtr2High: {:x}", val); let val = vmread(VmcsField::GuestPDPtr3).unwrap_or(0xbadc0de); debug!("GuestPDPtr3: {:x}", val); let val = vmread(VmcsField::GuestPDPtr3High).unwrap_or(0xbadc0de); debug!("GuestPDPtr3High: {:x}", val); let val = vmread(VmcsField::GuestBndcfgs).unwrap_or(0xbadc0de); debug!("GuestBndcfgs: {:x}", val); let val = vmread(VmcsField::GuestBndcfgsHigh).unwrap_or(0xbadc0de); debug!("GuestBndcfgsHigh: {:x}", val); let val = vmread(VmcsField::HostIA32Pat).unwrap_or(0xbadc0de); debug!("HostIA32Pat: {:x}", val); let val = vmread(VmcsField::HostIA32PatHigh).unwrap_or(0xbadc0de); debug!("HostIA32PatHigh: {:x}", val); let val = vmread(VmcsField::HostIA32Efer).unwrap_or(0xbadc0de); debug!("HostIA32Efer: {:x}", val); let val = vmread(VmcsField::HostIA32EferHigh).unwrap_or(0xbadc0de); debug!("HostIA32EferHigh: {:x}", val); let val = vmread(VmcsField::HostIA32PerfGlobalCtrl).unwrap_or(0xbadc0de); debug!("HostIA32PerfGlobalCtrl: {:x}", val); let val = vmread(VmcsField::HostIA32PerfGlobalCtrlHigh).unwrap_or(0xbadc0de); debug!("HostIA32PerfGlobalCtrlHigh: {:x}", val); let val = vmread(VmcsField::PinBasedVmExecControl).unwrap_or(0xbadc0de); debug!("PinBasedVmExecControl: {:x}", val); let val = vmread(VmcsField::CpuBasedVmExecControl).unwrap_or(0xbadc0de); debug!("CpuBasedVmExecControl: {:x}", val); let val = vmread(VmcsField::ExceptIonBitmap).unwrap_or(0xbadc0de); debug!("ExceptIonBitmap: {:x}", val); let val = vmread(VmcsField::PageFaultErrorCodeMask).unwrap_or(0xbadc0de); debug!("PageFaultErrorCodeMask: {:x}", val); let val = vmread(VmcsField::PageFaultErrorCodeMatch).unwrap_or(0xbadc0de); debug!("PageFaultErrorCodeMatch: {:x}", val); let val = vmread(VmcsField::Cr3TargetCount).unwrap_or(0xbadc0de); debug!("Cr3TargetCount: {:x}", val); let val = vmread(VmcsField::VmExitControls).unwrap_or(0xbadc0de); debug!("VmExitControls: {:x}", val); let val = vmread(VmcsField::VmExitMsrStoreCount).unwrap_or(0xbadc0de); debug!("VmExitMsrStoreCount: {:x}", val); let val = vmread(VmcsField::VmExitMsrLoadCount).unwrap_or(0xbadc0de); debug!("VmExitMsrLoadCount: {:x}", val); let val = vmread(VmcsField::VmEntryControls).unwrap_or(0xbadc0de); debug!("VmEntryControls: {:x}", val); let val = vmread(VmcsField::VmEntryMsrLoadCount).unwrap_or(0xbadc0de); debug!("VmEntryMsrLoadCount: {:x}", val); let val = vmread(VmcsField::VmEntryIntrInfoField).unwrap_or(0xbadc0de); debug!("VmEntryIntrInfoField: {:x}", val); let val = vmread(VmcsField::VmEntryExceptIonErrorCode).unwrap_or(0xbadc0de); debug!("VmEntryExceptIonErrorCode: {:x}", val); let val = vmread(VmcsField::VmEntryInstructionLen).unwrap_or(0xbadc0de); debug!("VmEntryInstructionLen: {:x}", val); let val = vmread(VmcsField::TPRThreshold).unwrap_or(0xbadc0de); debug!("TPRThreshold: {:x}", val); let val = vmread(VmcsField::SecondaryVmExecControl).unwrap_or(0xbadc0de); debug!("SecondaryVmExecControl: {:x}", val); let val = vmread(VmcsField::PLEGap).unwrap_or(0xbadc0de); debug!("PLEGap: {:x}", val); let val = vmread(VmcsField::PLEWindow).unwrap_or(0xbadc0de); debug!("PLEWindow: {:x}", val); let val = vmread(VmcsField::VmInstructionError).unwrap_or(0xbadc0de); debug!("VmInstructionError: {:x}", val); debug!( "VmInstructionError: {}", vmcs::vm_instruction_error_number_message(val) ); let val = vmread(VmcsField::VmExitReason).unwrap_or(0xbadc0de); debug!("VmExitReason: {:x}", val); let val = vmread(VmcsField::VmExitIntrInfo).unwrap_or(0xbadc0de); debug!("VmExitIntrInfo: {:x}", val); let val = vmread(VmcsField::VmExitIntrErrorCode).unwrap_or(0xbadc0de); debug!("VmExitIntrErrorCode: {:x}", val); let val = vmread(VmcsField::IdtVectoringInfoField).unwrap_or(0xbadc0de); debug!("IdtVectoringInfoField: {:x}", val); let val = vmread(VmcsField::IdtVectoringErrorCode).unwrap_or(0xbadc0de); debug!("IdtVectoringErrorCode: {:x}", val); let val = vmread(VmcsField::VmExitInstructionLen).unwrap_or(0xbadc0de); debug!("VmExitInstructionLen: {:x}", val); let val = vmread(VmcsField::VmxInstructionInfo).unwrap_or(0xbadc0de); debug!("VmxInstructionInfo: {:x}", val); let val = vmread(VmcsField::GuestEsLimit).unwrap_or(0xbadc0de); debug!("GuestEsLimit: {:x}", val); let val = vmread(VmcsField::GuestCsLimit).unwrap_or(0xbadc0de); debug!("GuestCsLimit: {:x}", val); let val = vmread(VmcsField::GuestSsLimit).unwrap_or(0xbadc0de); debug!("GuestSsLimit: {:x}", val); let val = vmread(VmcsField::GuestDsLimit).unwrap_or(0xbadc0de); debug!("GuestDsLimit: {:x}", val); let val = vmread(VmcsField::GuestFsLimit).unwrap_or(0xbadc0de); debug!("GuestFsLimit: {:x}", val); let val = vmread(VmcsField::GuestGsLimit).unwrap_or(0xbadc0de); debug!("GuestGsLimit: {:x}", val); let val = vmread(VmcsField::GuestLdtrLimit).unwrap_or(0xbadc0de); debug!("GuestLdtrLimit: {:x}", val); let val = vmread(VmcsField::GuestTrLimit).unwrap_or(0xbadc0de); debug!("GuestTrLimit: {:x}", val); let val = vmread(VmcsField::GuestGdtrLimit).unwrap_or(0xbadc0de); debug!("GuestGdtrLimit: {:x}", val); let val = vmread(VmcsField::GuestIdtrLimit).unwrap_or(0xbadc0de); debug!("GuestIdtrLimit: {:x}", val); let val = vmread(VmcsField::GuestEsArBytes).unwrap_or(0xbadc0de); debug!("GuestEsArBytes: {:x}", val); let val = vmread(VmcsField::GuestCsArBytes).unwrap_or(0xbadc0de); debug!("GuestCsArBytes: {:x}", val); let val = vmread(VmcsField::GuestSsArBytes).unwrap_or(0xbadc0de); debug!("GuestSsArBytes: {:x}", val); let val = vmread(VmcsField::GuestDsArBytes).unwrap_or(0xbadc0de); debug!("GuestDsArBytes: {:x}", val); let val = vmread(VmcsField::GuestFsArBytes).unwrap_or(0xbadc0de); debug!("GuestFsArBytes: {:x}", val); let val = vmread(VmcsField::GuestGsArBytes).unwrap_or(0xbadc0de); debug!("GuestGsArBytes: {:x}", val); let val = vmread(VmcsField::GuestLdtrArBytes).unwrap_or(0xbadc0de); debug!("GuestLdtrArBytes: {:x}", val); let val = vmread(VmcsField::GuestTrArBytes).unwrap_or(0xbadc0de); debug!("GuestTrArBytes: {:x}", val); let val = vmread(VmcsField::GuestInterruptibilityInfo).unwrap_or(0xbadc0de); debug!("GuestInterruptibilityInfo: {:x}", val); let val = vmread(VmcsField::GuestActivityState).unwrap_or(0xbadc0de); debug!("GuestActivityState: {:x}", val); let val = vmread(VmcsField::GuestSysenterCs).unwrap_or(0xbadc0de); debug!("GuestSysenterCs: {:x}", val); let val = vmread(VmcsField::VmxPreemptionTimerValue).unwrap_or(0xbadc0de); debug!("VmxPreemptionTimerValue: {:x}", val); let val = vmread(VmcsField::HostIA32SysenterCs).unwrap_or(0xbadc0de); debug!("HostIA32SysenterCs: {:x}", val); let val = vmread(VmcsField::Cr0GuestHostMask).unwrap_or(0xbadc0de); debug!("Cr0GuestHostMask: {:x}", val); let val = vmread(VmcsField::Cr4GuestHostMask).unwrap_or(0xbadc0de); debug!("Cr4GuestHostMask: {:x}", val); let val = vmread(VmcsField::Cr0ReadShadow).unwrap_or(0xbadc0de); debug!("Cr0ReadShadow: {:x}", val); let val = vmread(VmcsField::Cr4ReadShadow).unwrap_or(0xbadc0de); debug!("Cr4ReadShadow: {:x}", val); let val = vmread(VmcsField::Cr3TargetValue0).unwrap_or(0xbadc0de); debug!("Cr3TargetValue0: {:x}", val); let val = vmread(VmcsField::Cr3TargetValue1).unwrap_or(0xbadc0de); debug!("Cr3TargetValue1: {:x}", val); let val = vmread(VmcsField::Cr3TargetValue2).unwrap_or(0xbadc0de); debug!("Cr3TargetValue2: {:x}", val); let val = vmread(VmcsField::Cr3TargetValue3).unwrap_or(0xbadc0de); debug!("Cr3TargetValue3: {:x}", val); let val = vmread(VmcsField::ExitQualificatIon).unwrap_or(0xbadc0de); debug!("ExitQualificatIon: {:x}", val); let val = vmread(VmcsField::GuestLinearAddress).unwrap_or(0xbadc0de); debug!("GuestLinearAddress: {:x}", val); let val = vmread(VmcsField::GuestCr0).unwrap_or(0xbadc0de); debug!("GuestCr0: {:x}", val); let val = vmread(VmcsField::GuestCr3).unwrap_or(0xbadc0de); debug!("GuestCr3: {:x}", val); let val = vmread(VmcsField::GuestCr4).unwrap_or(0xbadc0de); debug!("GuestCr4: {:x}", val); let val = vmread(VmcsField::GuestEsBase).unwrap_or(0xbadc0de); debug!("GuestEsBase: {:x}", val); let val = vmread(VmcsField::GuestCsBase).unwrap_or(0xbadc0de); debug!("GuestCsBase: {:x}", val); let val = vmread(VmcsField::GuestSsBase).unwrap_or(0xbadc0de); debug!("GuestSsBase: {:x}", val); let val = vmread(VmcsField::GuestDsBase).unwrap_or(0xbadc0de); debug!("GuestDsBase: {:x}", val); let val = vmread(VmcsField::GuestFsBase).unwrap_or(0xbadc0de); debug!("GuestFsBase: {:x}", val); let val = vmread(VmcsField::GuestGsBase).unwrap_or(0xbadc0de); debug!("GuestGsBase: {:x}", val); let val = vmread(VmcsField::GuestLdtrBase).unwrap_or(0xbadc0de); debug!("GuestLdtrBase: {:x}", val); let val = vmread(VmcsField::GuestTrBase).unwrap_or(0xbadc0de); debug!("GuestTrBase: {:x}", val); let val = vmread(VmcsField::GuestGdtrBase).unwrap_or(0xbadc0de); debug!("GuestGdtrBase: {:x}", val); let val = vmread(VmcsField::GuestIdtrBase).unwrap_or(0xbadc0de); debug!("GuestIdtrBase: {:x}", val); let val = vmread(VmcsField::GuestDr7).unwrap_or(0xbadc0de); debug!("GuestDr7: {:x}", val); let val = vmread(VmcsField::GuestRsp).unwrap_or(0xbadc0de); debug!("GuestRsp: {:x}", val); let val = vmread(VmcsField::GuestRip).unwrap_or(0xbadc0de); debug!("GuestRip: {:x}", val); let val = vmread(VmcsField::GuestRFlags).unwrap_or(0xbadc0de); debug!("GuestRFlags: {:x}", val); let val = vmread(VmcsField::GuestPendingDbgExceptions).unwrap_or(0xbadc0de); debug!("GuestPendingDbgExceptions: {:x}", val); let val = vmread(VmcsField::GuestSysenterEsp).unwrap_or(0xbadc0de); debug!("GuestSysenterEsp: {:x}", val); let val = vmread(VmcsField::GuestSysenterEip).unwrap_or(0xbadc0de); debug!("GuestSysenterEip: {:x}", val); let val = vmread(VmcsField::HostCr0).unwrap_or(0xbadc0de); debug!("HostCr0: {:x}", val); let val = vmread(VmcsField::HostCr3).unwrap_or(0xbadc0de); debug!("HostCr3: {:x}", val); let val = vmread(VmcsField::HostCr4).unwrap_or(0xbadc0de); debug!("HostCr4: {:x}", val); let val = vmread(VmcsField::HostFsBase).unwrap_or(0xbadc0de); debug!("HostFsBase: {:x}", val); let val = vmread(VmcsField::HostGsBase).unwrap_or(0xbadc0de); debug!("HostGsBase: {:x}", val); let val = vmread(VmcsField::HostTrBase).unwrap_or(0xbadc0de); debug!("HostTrBase: {:x}", val); let val = vmread(VmcsField::HostGdtrBase).unwrap_or(0xbadc0de); debug!("HostGdtrBase: {:x}", val); let val = vmread(VmcsField::HostIdtrBase).unwrap_or(0xbadc0de); debug!("HostIdtrBase: {:x}", val); let val = vmread(VmcsField::HostIA32SysenterEsp).unwrap_or(0xbadc0de); debug!("HostIA32SysenterEsp: {:x}", val); let val = vmread(VmcsField::HostIA32SysenterEip).unwrap_or(0xbadc0de); debug!("HostIA32SysenterEip: {:x}", val); let val = vmread(VmcsField::HostRsp).unwrap_or(0xbadc0de); debug!("HostRsp: {:x}", val); let val = vmread(VmcsField::HostRip).unwrap_or(0xbadc0de); debug!("HostRip: {:x}", val); }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vcpu.rs
hypervisor/src/vcpu.rs
//! This module defines functions for working with VCpus. use crate::VCpu; use x86::bits64::segmentation::fs_deref; /// Get a reference to the current VCpu structure. /// The reference is static because the VCpu structure must outlive the /// hypervisor. /// Each CPU has data used to represent the guest stored in the VCpu structure. /// A pointer to the VCpu structure for this core is placed in the fs base /// register. /// The first field of the vcpu structure is a pointer to itself, so if we load /// the first pointer of the fs base region, that is fs:0, we get a pointer to /// the current VCpu. pub fn get_current_vcpu() -> &'static mut VCpu { unsafe { &mut *(fs_deref() as *mut VCpu) } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/panic.rs
hypervisor/src/panic.rs
//! This module handles hypervisor panics. #![cfg(not(test))] use core::sync::atomic; use core::panic::PanicInfo; use crate::UNSYNCHRONIZED_LOGGER; /// Prevent recursive panicking. static HAVE_PANICKED: atomic::AtomicBool = atomic::AtomicBool::new(false); /// Called by the rust runtime when a panic occurs. /// Sets HAVE_PANICKED, and if this is the first time a panic has occurred, /// logs information about the panic. #[no_mangle] #[panic_handler] pub extern "C" fn panic_fmt(info: &PanicInfo) -> ! { if HAVE_PANICKED .compare_exchange( false, true, atomic::Ordering::SeqCst, atomic::Ordering::SeqCst, ) .is_ok() { write!(UNSYNCHRONIZED_LOGGER, "PANIC: {}", info); } loop { unsafe { asm!("cli; hlt;"); } } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/debug.rs
hypervisor/src/debug.rs
//! This module defines functions useful for debugging the hypervisor. /// A breakpoint function for debuggers to hook. /// /// This does NOT generate an int 3 breakpoint instruction. /// Instead it does the bochs magic breakpoint instruction to cause bochs to break if we are running under bochs and that feature is enabled. /// This function is never inlined so a debugger like GDB can hook it more easily. #[inline(never)] pub fn breakpoint() { // If feature inline asm... // Bochs magic breakpoint. unsafe { asm!("xchg bx, bx"); } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/interrupt_controller.rs
hypervisor/src/interrupt_controller.rs
//! This module defines a virtual interrupt controller to be used by each core. use log::trace; use crate::msr; use crate::vmcs_fields::PinBasedControlsVmxPreemption; use crate::{ vcpu::get_current_vcpu, vmcs_fields::{CpuBasedControlsInterruptWindowExiting, VmcsField}, vmx::{vmread, vmwrite}, }; const VM_PREEMPTION_TIMER_VALUE: u64 = 0xffff; const INTERRUPT_COUNT: usize = 256; /// A Virtualized Interrupt Controller /// Caches various interrupt information. /// Should be initialized as all zeroes. /// Each core should have their own VirtualLocalInterruptController. pub struct VirtualLocalInterruptController { total_interrupts_count: usize, delayed_delivery_interrupts: [usize; INTERRUPT_COUNT], requested_poll_of_interrupts_on_next_preemption_timer: bool, we_should_disable_preemption_timer: bool, } fn get_local_interrupt_controller() -> &'static mut VirtualLocalInterruptController { unsafe { &mut *get_current_vcpu().virtual_local_interrupt_controller } } fn delay_interrupt_delivery(interrupt_number: u64) { let interrupt_controller = get_local_interrupt_controller(); let count = &mut interrupt_controller.delayed_delivery_interrupts[interrupt_number as usize]; *count += 1; interrupt_controller.total_interrupts_count = interrupt_controller .total_interrupts_count .checked_add(1) .unwrap(); } fn check_for_highest_priority_interrupt() -> Option<u64> { let interrupt_controller = get_local_interrupt_controller(); if interrupt_controller.total_interrupts_count == 0 { return None; } for (interrupt_number, count) in &mut interrupt_controller .delayed_delivery_interrupts .iter_mut() .enumerate() { if *count > 0 { *count -= 1; interrupt_controller.total_interrupts_count -= 1; return Some(interrupt_number as u64); } } unreachable!(); } // See 33.3.3.4 Generation of Virtual Interrupt Events by VMM fn vmx_is_guest_interruptable() -> bool { let guest_rflags = vmread(VmcsField::GuestRFlags).unwrap(); // Is the guest interrupt flag clear? if (guest_rflags & 0x200) == 0 { return false; } // Are interrupts blocked by a hardware state like sti? // Remember, interrupts won't be injected until the instruction *after* sti. // There are other instructions which do this too, see vol 3 33.3.3.4 let guest_interruptability_info = vmread(VmcsField::GuestInterruptibilityInfo).unwrap(); // See Table 24-3. Format of Interruptibility State guest_interruptability_info == 0 } const VM_ENTRY_INTERRUPT_INFO_VALID: u64 = 1 << 31; const VM_ENTRY_INTERRUPT_INFO_TYPE_EXTERNAL_INTERRUPT: u64 = 0 << 8; fn vmx_inject_interrupt_into_guest(vector: u64) -> Result<(), x86::vmx::VmFail> { assert!(vector < INTERRUPT_COUNT as u64); let interrupt_info = vector | VM_ENTRY_INTERRUPT_INFO_VALID | VM_ENTRY_INTERRUPT_INFO_TYPE_EXTERNAL_INTERRUPT; crate::debug::breakpoint(); vmwrite(VmcsField::VmEntryIntrInfoField, interrupt_info) } fn vmx_configure_interrupts_wakeup() { let pair = msr::rdmsr(msr::Msr::Ia32VmxProcBasedControls); let disallowed_exit_values = pair.edx; // If we are allowed to set interrupt window exiting, set it. if u64::from(disallowed_exit_values) & CpuBasedControlsInterruptWindowExiting == 0 { trace!("CPU allows interrupt window exiting"); let mut cpu_based_controls = vmread(VmcsField::CpuBasedVmExecControl).unwrap(); cpu_based_controls |= CpuBasedControlsInterruptWindowExiting; vmwrite(VmcsField::CpuBasedVmExecControl, cpu_based_controls).unwrap(); } else { trace!("CPU does not allow interrupt window exiting, use a preemption timer instead"); let local_interrupt_controller = get_local_interrupt_controller(); let mut pin_based_controls = vmread(VmcsField::PinBasedVmExecControl).unwrap(); if (pin_based_controls & PinBasedControlsVmxPreemption) == 0 { pin_based_controls |= PinBasedControlsVmxPreemption; vmwrite(VmcsField::PinBasedVmExecControl, pin_based_controls).unwrap(); local_interrupt_controller.we_should_disable_preemption_timer = true; } else { local_interrupt_controller.we_should_disable_preemption_timer = false; } vmwrite( VmcsField::VmxPreemptionTimerValue, VM_PREEMPTION_TIMER_VALUE, ) .unwrap(); local_interrupt_controller.requested_poll_of_interrupts_on_next_preemption_timer = true; } } fn vmx_deconfigure_timer_wakeup() -> Result<(), x86::vmx::VmFail> { let mut pin_based_controls = vmread(VmcsField::PinBasedVmExecControl)?; pin_based_controls &= !PinBasedControlsVmxPreemption; vmwrite(VmcsField::PinBasedVmExecControl, pin_based_controls) } fn vmx_deconfigure_interrupt_window_exiting() -> Result<(), x86::vmx::VmFail> { let mut cpu_based_controls = vmread(VmcsField::CpuBasedVmExecControl)?; cpu_based_controls &= !CpuBasedControlsInterruptWindowExiting; vmwrite(VmcsField::CpuBasedVmExecControl, cpu_based_controls) } /// Call this function when an external interrupt is received. /// If the guest is interruptable, inject the interrupt into the guest. /// Otherwise, cache it for later delivery and configure the guest to wake up /// later for interrupt delivery. pub fn received_external_interrupt() -> Result<(), x86::vmx::VmFail> { let interrupt_info = vmread(VmcsField::VmExitIntrInfo)?; let interrupt_number = interrupt_info & 0xff; trace!("Received external interrupt {:x}", interrupt_info); if vmx_is_guest_interruptable() { trace!("Guest is interruptable"); vmx_inject_interrupt_into_guest(interrupt_number) } else { trace!("Guest is not interruptable, delay delivery"); delay_interrupt_delivery(interrupt_number); vmx_configure_interrupts_wakeup(); Ok(()) } } /// Call when the guest preemption timer fires. /// If the guest does not support interrupt window exiting, and there is an /// outstanding interrupt cached, and the guest is interruptable, /// an interrupt will be injected into the guest. /// /// If the interrupt controller requested the timer be enabled and the timer is /// not being used elsewhere in the hypervisor, and there are no outstanding /// interrupts, the timer will be disabled to allow the guest to run unimpeded. /// /// This function only does work if the guest does not support interrupt window /// exiting. pub fn received_preemption_timer() -> Result<(), x86::vmx::VmFail> { let local_interrupt_controller = get_local_interrupt_controller(); if local_interrupt_controller.requested_poll_of_interrupts_on_next_preemption_timer && vmx_is_guest_interruptable() { if let Some(interrupt_number) = check_for_highest_priority_interrupt() { trace!("Delivering interrupt into guest"); vmx_inject_interrupt_into_guest(interrupt_number as u64)?; } if local_interrupt_controller.total_interrupts_count == 0 && local_interrupt_controller.we_should_disable_preemption_timer { trace!("No more external interrupts cached and we should disable the preemption timer, disabling interrupt window exiting"); vmx_deconfigure_timer_wakeup()?; local_interrupt_controller.we_should_disable_preemption_timer = false; local_interrupt_controller.requested_poll_of_interrupts_on_next_preemption_timer = false; } } Ok(()) } /// If interrupt window exiting is supported by the guest, then this function /// should be called when an interrupt window exit occurs. This function will /// then inject any outstanding interrupts into the guest. pub fn received_interrupt_window_exit() -> Result<(), x86::vmx::VmFail> { let local_interrupt_controller = get_local_interrupt_controller(); assert!(vmx_is_guest_interruptable()); if let Some(interrupt_number) = check_for_highest_priority_interrupt() { trace!("Delivering interrupt into guest"); vmx_inject_interrupt_into_guest(interrupt_number)?; } if local_interrupt_controller.total_interrupts_count == 0 { trace!("No more external interrupts cached, disabling interrupt window exiting"); vmx_deconfigure_interrupt_window_exiting()?; } Ok(()) }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmcs.rs
hypervisor/src/vmcs.rs
//! This module defines functions used for setting up the guest's virtual //! machine control structures. use crate::msr::{rdmsr, rdmsrl, Msr}; use crate::segmentation::{get_current_gdt, unpack_gdt_entry}; use crate::vmcs_fields::*; use crate::vmx::{read_dr7, vmread, vmwrite}; use crate::VCpu; use core::convert::TryFrom; use log::{trace, warn}; use x86::dtables; extern "C" { /// The host entrypoint function. /// Implemented externally in assembly. /// Will be called when a VM exit occurs. /// When a function returns to the host entrypoint, the hypervisor will /// attempt to resume the guest, or, if resuming the guest fails, it will /// call /// [hypervisor_vmresume_failure](../vmexit_handlers/fn.hypervisor_vmresume_failure.html) fn _host_entrypoint(); } /// Initialize the host state for the currently loaded vmcs. pub fn initialize_host_state(vcpu: &VCpu) -> Result<(), x86::vmx::VmFail> { let cr0 = unsafe { x86::controlregs::cr0() }.bits() as u64; let cr3 = unsafe { x86::controlregs::cr3() }; let cr4 = unsafe { x86::controlregs::cr4() }.bits() as u64; vmwrite(VmcsField::HostCr0, cr0)?; vmwrite(VmcsField::HostCr3, cr3)?; vmwrite(VmcsField::HostCr4, cr4)?; let cs = x86::segmentation::cs(); vmwrite(VmcsField::HostCsSelector, u64::from(cs.bits()))?; let ds = x86::segmentation::ds(); vmwrite(VmcsField::HostDsSelector, u64::from(ds.bits()))?; let es = x86::segmentation::es(); vmwrite(VmcsField::HostEsSelector, u64::from(es.bits()))?; let fs = x86::segmentation::fs(); vmwrite(VmcsField::HostFsSelector, u64::from(fs.bits()))?; let gs = x86::segmentation::gs(); vmwrite(VmcsField::HostGsSelector, u64::from(gs.bits()))?; let ss = x86::segmentation::ss(); vmwrite(VmcsField::HostSsSelector, u64::from(ss.bits()))?; assert_eq!(vcpu.tr_selector & !0x7, vcpu.tr_selector); // TR RPL must be 0. See host entry error reasons chapter. vmwrite(VmcsField::HostTrSelector, u64::from(vcpu.tr_selector))?; vmwrite(VmcsField::HostTrBase, vcpu.tr_base)?; vmwrite(VmcsField::HostGdtrBase, vcpu.host_gdt_base as u64)?; vmwrite(VmcsField::HostIdtrBase, crate::interrupts::host_idt_base())?; vmwrite(VmcsField::HostFsBase, vcpu as *const VCpu as u64)?; vmwrite(VmcsField::HostGsBase, 0)?; vmwrite(VmcsField::HostRsp, vcpu.stack_top as u64)?; vmwrite(VmcsField::HostRip, _host_entrypoint as usize as u64)?; Ok(()) } /// Initialize the guest state for the currently loaded vmcs. pub fn initialize_guest_state(_vcpu: &VCpu) -> Result<(), x86::vmx::VmFail> { trace!("initialize_guest_state"); vmwrite(VmcsField::VmcsLinkPointer, !0)?; let mut guest_idtr: dtables::DescriptorTablePointer<u64> = Default::default(); unsafe { dtables::sidt(&mut guest_idtr); } trace!("got idtr {:x?}", guest_idtr); vmwrite(VmcsField::GuestIdtrLimit, u64::from(guest_idtr.limit))?; vmwrite(VmcsField::GuestIdtrBase, guest_idtr.base as u64)?; let mut guest_gdtr: dtables::DescriptorTablePointer<u64> = Default::default(); unsafe { dtables::sgdt(&mut guest_gdtr); } trace!("got idtr {:x?}", guest_gdtr); vmwrite(VmcsField::GuestGdtrLimit, u64::from(guest_gdtr.limit))?; vmwrite(VmcsField::GuestGdtrBase, guest_gdtr.base as u64)?; let gdt = get_current_gdt(); trace!("got gdt {:x?}", gdt); let cs = x86::segmentation::cs(); let cs_unpacked = unpack_gdt_entry(gdt, cs.bits()); vmwrite(VmcsField::GuestCsSelector, u64::from(cs_unpacked.selector))?; vmwrite(VmcsField::GuestCsLimit, cs_unpacked.limit)?; vmwrite( VmcsField::GuestCsArBytes, u64::from(cs_unpacked.access_rights), )?; vmwrite(VmcsField::GuestCsBase, cs_unpacked.base)?; let ds = x86::segmentation::ds(); let ds_unpacked = unpack_gdt_entry(gdt, ds.bits()); vmwrite(VmcsField::GuestDsSelector, u64::from(ds_unpacked.selector))?; vmwrite(VmcsField::GuestDsLimit, ds_unpacked.limit)?; vmwrite( VmcsField::GuestDsArBytes, u64::from(ds_unpacked.access_rights), )?; vmwrite(VmcsField::GuestDsBase, ds_unpacked.base)?; let es = x86::segmentation::es(); let es_unpacked = unpack_gdt_entry(gdt, es.bits()); vmwrite(VmcsField::GuestEsSelector, u64::from(es_unpacked.selector))?; vmwrite(VmcsField::GuestEsLimit, es_unpacked.limit)?; vmwrite( VmcsField::GuestEsArBytes, u64::from(es_unpacked.access_rights), )?; vmwrite(VmcsField::GuestEsBase, es_unpacked.base)?; let fs = x86::segmentation::fs(); let fs_unpacked = unpack_gdt_entry(gdt, fs.bits()); vmwrite(VmcsField::GuestFsSelector, u64::from(fs_unpacked.selector))?; vmwrite(VmcsField::GuestFsLimit, fs_unpacked.limit)?; vmwrite( VmcsField::GuestFsArBytes, u64::from(fs_unpacked.access_rights), )?; vmwrite(VmcsField::GuestFsBase, fs_unpacked.base)?; let gs = x86::segmentation::gs(); let gs_unpacked = unpack_gdt_entry(gdt, gs.bits()); vmwrite(VmcsField::GuestGsSelector, u64::from(gs_unpacked.selector))?; vmwrite(VmcsField::GuestGsLimit, gs_unpacked.limit)?; vmwrite( VmcsField::GuestGsArBytes, u64::from(gs_unpacked.access_rights), )?; vmwrite(VmcsField::GuestGsBase, gs_unpacked.base)?; let ss = x86::segmentation::ss(); let ss_unpacked = unpack_gdt_entry(gdt, ss.bits()); vmwrite(VmcsField::GuestSsSelector, u64::from(ss_unpacked.selector))?; vmwrite(VmcsField::GuestSsLimit, ss_unpacked.limit)?; vmwrite( VmcsField::GuestSsArBytes, u64::from(ss_unpacked.access_rights), )?; vmwrite(VmcsField::GuestSsBase, ss_unpacked.base)?; let tr = x86::task::tr(); let tr_unpacked = unpack_gdt_entry(gdt, tr.bits()); vmwrite(VmcsField::GuestTrSelector, u64::from(tr_unpacked.selector))?; vmwrite(VmcsField::GuestTrLimit, tr_unpacked.limit)?; if tr_unpacked.is_usable() { vmwrite( VmcsField::GuestTrArBytes, u64::from(tr_unpacked.access_rights), )?; } else { // 26.3.1.2 Checks on Guest Segment Registers // Vol. 3C 26-11 // Set present (bit 7), 64 bit (0xb in 0:3), rest is clear. vmwrite(VmcsField::GuestTrArBytes, (1 << 7) | 0xb)?; } vmwrite(VmcsField::GuestTrBase, tr_unpacked.base)?; let ldtr = unsafe { x86::dtables::ldtr() }; let ldtr_unpacked = unpack_gdt_entry(gdt, ldtr.bits()); vmwrite( VmcsField::GuestLdtrSelector, u64::from(ldtr_unpacked.selector), )?; vmwrite(VmcsField::GuestLdtrLimit, ldtr_unpacked.limit)?; vmwrite( VmcsField::GuestLdtrArBytes, u64::from(ldtr_unpacked.access_rights), )?; vmwrite(VmcsField::GuestLdtrBase, ldtr_unpacked.base)?; let cr4 = unsafe { x86::controlregs::cr4() }; vmwrite(VmcsField::GuestCr4, cr4.bits() as u64)?; //vmwrite(VmcsField::GuestCr4ReadShadow, cr4)?; let cr3 = unsafe { x86::controlregs::cr3() }; vmwrite(VmcsField::GuestCr3, cr3)?; let cr0 = unsafe { x86::controlregs::cr0() }; vmwrite(VmcsField::GuestCr0, cr0.bits() as u64)?; //vmwrite(VmcsField::GuestCr0ReadShadow, cr0)?; vmwrite(VmcsField::GuestIA32Debugctl, rdmsrl(Msr::Ia32DebugControl))?; let dr7 = read_dr7(); vmwrite(VmcsField::GuestDr7, dr7)?; Ok(()) } pub fn adjust_value_based_on_msr(msr: Msr, controls: u64) -> u64 { let controls = u32::try_from(controls).expect("Controls should be a 32 bit field"); // 503 953 2390 let pair = rdmsr(msr); let fixed0 = pair.edx; let fixed1 = pair.eax; if controls & fixed0 != controls { warn!( "Requested unsupported controls for msr {:?}, fixed0 {:x} fixed1 {:x} controls {:x}", msr, fixed0, fixed1, controls ); } u64::from(fixed1 | (controls & fixed0)) } /// Initialize the control values for the currently loaded vmcs. pub fn initialize_vm_control_values(vcpu: &VCpu) -> Result<(), x86::vmx::VmFail> { // Configure entry/exit and supported feature controls vmwrite( VmcsField::SecondaryVmExecControl, adjust_value_based_on_msr( Msr::Ia32VmxProcBasedControls2, SecondaryCpuBasedControlsRdtscpEnable | SecondaryCpuBasedControlsInvpcidEnable | SecondaryCpuBasedControlsXSavesEnable, ), )?; vmwrite( VmcsField::PinBasedVmExecControl, adjust_value_based_on_msr( Msr::Ia32VmxPinBasedControls, /*PinBasedControlsVmxPreemption | PinBasedControlsExternalInterruptExiting*/ 0, ), )?; let pin = vmread(VmcsField::PinBasedVmExecControl)?; if pin & PinBasedControlsExternalInterruptExiting != 0 { warn!("External interrupt exiting enabled"); } else { trace!("External interrupt exiting not enabled"); } vmwrite(VmcsField::VmxPreemptionTimerValue, 0xfffff)?; vmwrite( VmcsField::CpuBasedVmExecControl, adjust_value_based_on_msr( Msr::Ia32VmxProcBasedControls, CpuBasedControlsMsrBitmaps | CpuBasedControlsSecondaryEnable //| CpuBasedControlsIoBitmaps //| CpuBasedControlsIoExiting, ), )?; vmwrite( VmcsField::VmExitControls, adjust_value_based_on_msr( Msr::Ia32VmxExitControls, VmExitIa32eMode /*| VmExitAcknowledgeInterruptOnExit*/ | VmExitConcealVmxFromPt, ), )?; vmwrite( VmcsField::VmEntryControls, adjust_value_based_on_msr(Msr::Ia32VmxEntryControls, VmEntryIa32eMode), )?; vmwrite(VmcsField::MsrBitmap, vcpu.msr_bitmap as u64)?; Ok(()) } /// Given a vm instruction error number, return a human readable string /// representing the error, taken from the Intel manual. pub fn vm_instruction_error_number_message(vm_instruction_error_number: u64) -> &'static str { match vm_instruction_error_number { 0 => "No error", 1 => "VMALL executed in VMX root operation", 2 => "VMCLEAR with invalid physical address", 3 => "VMCLEAR with VMXON pointer", 4 => "VMLAUNCH with non-clear VMCS", 5 => "VMRESUME with non-launched VMCS", 6 => "VMRESUME after VMXOFF (VMXOFF and VMXON between VMLAUNCH and VMRESUME)", 7 => "VM entry with invalid control field(s)", 8 => "VM entry with invalid host-state field(s)", 9 => "VMPTRLD with invalid physical address", 10 => "VMPTRLD with VMXON pointer", 11 => "VMPTRLD with incorrect VMCS revision identifier", 12 => "VMREAD/VMWRITE from/to unsupported VMCS component", 13 => "VMWRITE to read-only VMCS component", 15 => "VMXON executed in VMX root operation", 16 => "VM entry with invalid executive-VMCS pointer", 17 => "VM entry with non-launched executive VMCS", 18 => { "VM entry with executive-VMCS pointer not VMXON pointer (when attempting to deactivate \ the dual-monitor treatment of" } 19 => { "VMCALL with non-clear VMCS (when attempting to activate the dual-monitor treatment of \ SMIs and SMM)" } 20 => "VMCALL with invalid VM-exit control fields", 22 => { "VMCALL with incorrect MSEG revision identifier (when attempting to activate the \ dual-monitor treatment of SMIs and SMM)" } 23 => "VMXOFF under dual-monitor treatment of SMIs and SMM", 24 => { "VMCALL with invalid SMM-monitor features (when attempting to activate the \ dual-monitor treatment of SMIs and SMM)" } 25 => { "VM entry with invalid VM-execution control fields in executive VMCS (when attempting \ to return from SMM)" } 26 => "VM entry with events blocked by MOV SS.", 28 => "Invalid operand to INVEPT/INVVPID.", _ => "Unknown VM instruction error number.", } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/vmexit_reasons.rs
hypervisor/src/vmexit_reasons.rs
//! Defines the codes representing the reason a VM exit occurred. #![allow(dead_code)] pub const VMEXIT_REASON_NMI_OR_EXCEPTION: u64 = 0; pub const VMEXIT_REASON_EXTERNAL_INTERRUPT: u64 = 1; pub const VMEXIT_REASON_TRIPLE_FAULT: u64 = 2; pub const VMEXIT_REASON_INIT_SIGNAL: u64 = 3; pub const VMEXIT_REASON_START_UP_IPI: u64 = 4; pub const VMEXIT_REASON_IO_SMI: u64 = 5; pub const VMEXIT_REASON_OTHER_SMI: u64 = 6; pub const VMEXIT_REASON_INTERRUPT_WINDOW: u64 = 7; pub const VMEXIT_REASON_NMI_WINDOWS: u64 = 8; pub const VMEXIT_REASON_TASK_SWITCH: u64 = 9; pub const VMEXIT_REASON_CPUID: u64 = 10; pub const VMEXIT_REASON_GETSEC: u64 = 11; pub const VMEXIT_REASON_HLT: u64 = 12; pub const VMEXIT_REASON_INVD: u64 = 13; pub const VMEXIT_REASON_INVLPG: u64 = 14; pub const VMEXIT_REASON_RDPMC: u64 = 15; pub const VMEXIT_REASON_RDTSC: u64 = 16; pub const VMEXIT_REASON_RSM: u64 = 17; pub const VMEXIT_REASON_VMCALL: u64 = 18; pub const VMEXIT_REASON_VMCLEAR: u64 = 19; pub const VMEXIT_REASON_VMLAUNCH: u64 = 20; pub const VMEXIT_REASON_VMPTRLD: u64 = 21; pub const VMEXIT_REASON_VMPTRST: u64 = 22; pub const VMEXIT_REASON_VMREAD: u64 = 23; pub const VMEXIT_REASON_VMRESUME: u64 = 24; pub const VMEXIT_REASON_VMWRITE: u64 = 25; pub const VMEXIT_REASON_VMXOFF: u64 = 26; pub const VMEXIT_REASON_VMXON: u64 = 27; pub const VMEXIT_REASON_CONTROL_REGISTER_ACCESS: u64 = 28; pub const VMEXIT_REASON_MOV_DR: u64 = 29; pub const VMEXIT_REASON_IO_INSTRUCTION: u64 = 30; pub const VMEXIT_REASON_RDMSR: u64 = 31; pub const VMEXIT_REASON_WRMSR: u64 = 32; pub const VMEXIT_REASON_INVALID_GUEST_STATE: u64 = 33; pub const VMEXIT_REASON_VM_ENTRY_FAILURE_DUE_TO_MSR_LOADING: u64 = 34; pub const VMEXIT_REASON_MWAIT: u64 = 36; pub const VMEXIT_REASON_MONITOR_TRAP: u64 = 37; pub const VMEXIT_REASON_MONITOR: u64 = 39; pub const VMEXIT_REASON_PAUSE: u64 = 40; pub const VMEXIT_REASON_VM_ENTRY_DUE_TO_MACHINE_CHECK_EVENT: u64 = 41; pub const VMEXIT_REASON_TPR_BELOW_THRESHOLD: u64 = 43; pub const VMEXIT_REASON_APIC_ACCES: u64 = 44; pub const VMEXIT_REASON_VIRTUALIZED_EOI: u64 = 45; pub const VMEXIT_REASON_ACCESSING_GDT_OR_IDTR: u64 = 46; pub const VMEXIT_REASON_ACCESSING_LDTR_OR_TR: u64 = 47; pub const VMEXIT_REASON_EPT_VIOLATION: u64 = 48; pub const VMEXIT_REASON_EPT_MISCONFIGURATION: u64 = 49; pub const VMEXIT_REASON_INVEPT: u64 = 50; pub const VMEXIT_REASON_RDTSCP: u64 = 51; pub const VMEXIT_REASON_PREEMPTION_TIMER_EXPIRED: u64 = 52; pub const VMEXIT_REASON_INVVPID: u64 = 53; pub const VMEXIT_REASON_WBINVD: u64 = 54; pub const VMEXIT_REASON_XSETBV: u64 = 55; pub const VMEXIT_REASON_APIC_WRITE: u64 = 56; pub const VMEXIT_REASON_RDRAND: u64 = 57; pub const VMEXIT_REASON_INVPCID: u64 = 58; pub const VMEXIT_REASON_VMFUNC: u64 = 59; pub const VMEXIT_REASON_ENCLS: u64 = 60; pub const VMEXIT_REASON_RDSEED: u64 = 61; pub const VMEXIT_REASON_PAGE_MODIFICATION_LOG_FULL: u64 = 62; pub const VMEXIT_REASON_XSAVES: u64 = 63; pub const VMEXIT_REASON_XRSTORS: u64 = 64; pub const VMEXIT_REASON_SPP_RELATED: u64 = 66; pub const VMEXIT_REASON_UMWAIT: u64 = 67; pub const VMEXIT_REASON_TPAUSE: u64 = 68;
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/hypercall_handler.rs
hypervisor/src/hypercall_handler.rs
use crate::register_state::GeneralPurposeRegisterState; const HYPERVISOR_VERSION: &str = env!("CARGO_PKG_VERSION"); fn parse_version(version_string: &str) -> [u32; 3] { let mut index = 0; let mut version: [u32; 3] = [0, 0, 0]; for c in version_string.chars() { if index > version.len() { break; } if let Some(digit) = c.to_digit(10) { version[index] *= 10; version[index] += digit; } else { index += 1; continue; } } version } /// Handle a hypercall. /// Expects gprs.rax to hold hypercall::HYPERCALL_MAGIC and gprs.rcx to hold a /// valid hypercall reason. pub fn handle_hypercall(gprs: &mut GeneralPurposeRegisterState) -> Result<(), x86::vmx::VmFail> { assert_eq!(hypervisor_abi::HYPERCALL_MAGIC, gprs.rax as u32); let reason = gprs.rcx as u32; match reason { hypervisor_abi::HYPERCALL_REASON_VERSION => { let version = parse_version(&HYPERVISOR_VERSION); gprs.rax = u64::from(version[0]); gprs.rbx = u64::from(version[1]); gprs.rcx = u64::from(version[2]); gprs.rdx = 0; // Reserved 0 } _ => { gprs.rax = 0; gprs.rbx = 0; gprs.rcx = 0; gprs.rdx = 0; } } Ok(()) }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/hypervisor/src/msr.rs
hypervisor/src/msr.rs
//! This module is used to work with Model Specific Registers. //! A Model Specific Register, or MSR, is a hardware register used to configure //! the hardware, learn about the current hardware configuration, or monitor the //! state of the hardware. //! MSRs may be unique per core, unique per NUMA node, or global for the whole //! machine. /// The values of various Model Specific Registers. #[allow(dead_code)] #[derive(Debug, Copy, Clone)] #[repr(u32)] pub enum Msr { EFER = 0xc000_0080, Ia32FeatureControl = 0x0000_003a, Ia32DebugControl = 0x0000_01d9, Ia32VmxBasic = 0x0000_0480, Ia32VmxPinBasedControls = 0x0000_0481, Ia32VmxProcBasedControls = 0x0000_0482, Ia32VmxExitControls = 0x0000_0483, Ia32VmxEntryControls = 0x0000_0484, Ia32VmxMisc = 0x0000_0485, Ia32VmxCr0Fixed0 = 0x0000_0486, Ia32VmxCr0Fixed1 = 0x0000_0487, Ia32VmxCr4Fixed0 = 0x0000_0488, Ia32VmxCr4Fixed1 = 0x0000_0489, Ia32VmxVmcsEnum = 0x0000_048a, Ia32VmxProcBasedControls2 = 0x0000_048b, Ia32VmxEptVpidCap = 0x0000_048c, Ia32VmxTruePinBasedControls = 0x0000_048d, Ia32VmxTrueProcBasedControls = 0x0000_048e, Ia32VmxTrueExitControls = 0x0000_048f, Ia32VmxTrueEntryControls = 0x0000_0490, Ia32VmxVmFunc = 0x0000_0491, } /// Represents the value of an Model specific register. /// rdmsr returns the value with the high bits of the MSR in edx and the low bits in eax. /// wrmsr recieves the value similarly. pub struct MsrValuePair { pub edx: u32, pub eax: u32, } /// Read a model specific register as a pair of two values. pub fn rdmsr(msr: Msr) -> MsrValuePair { let edx: u32; let eax: u32; unsafe { asm!( "rdmsr", lateout("eax")(eax), lateout("edx")(edx), in("ecx")(msr as u32) ); } MsrValuePair { edx, eax } } /// Read a model specific register as a single 64 bit value. pub fn rdmsrl(msr: Msr) -> u64 { let pair = rdmsr(msr); (u64::from(pair.edx) << 32) | u64::from(pair.eax) } /// Write to a model specific register. pub fn wrmsr(msr: Msr, pair: MsrValuePair) { unsafe { asm!( "wrmsr", in("eax")(pair.eax), in("edx")(pair.edx), in("ecx")(msr as u32) ); } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/uefi/build.rs
uefi/build.rs
use std::path::Path; use std::process::Command; use std::{env, error::Error}; const ASM_FILES: [&str; 2] = ["host_entrypoint.S", "isr.S"]; fn main() -> Result<(), Box<dyn Error>> { let src_dir = &format!("{}/src", env::var("CARGO_MANIFEST_DIR").unwrap()); let out_dir = env::var("OUT_DIR").unwrap(); let full_lib = &format!("{}/{}", out_dir, "asm.lib"); let mut objs = Vec::new(); for filename in ASM_FILES.iter() { let full_filename = &format!("{}/{}", src_dir, filename); let obj = format!("{}/{}.obj", out_dir, filename).clone(); { Command::new("clang") .args(&[ full_filename, "-target", "x86_64-unknown-windows", "-o", &obj, "-c", ]) .current_dir(&Path::new(&out_dir)) .status() .unwrap(); } objs.push(obj); println!("cargo:rerun-if-changed={}", filename); } let mut args = vec![format!("-out:{}", full_lib)]; args.append(&mut objs); Command::new("llvm-lib") .args(args) .current_dir(&Path::new(&out_dir)) .status() .unwrap(); println!("cargo:rustc-link-search=native={}", out_dir); println!("cargo:rustc-link-lib=static=asm"); Ok(()) }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/uefi/src/main.rs
uefi/src/main.rs
//! A UEFI Runtime Service which implements a mostly-passthrough //! [hypervisor](../hypervisor/index.html). //! Invoke via the UEFI shell like so: //! ```text //! UEFI Interactive Shell v2.2 //! EDK II //! UEFI v2.70 (EDK II, 0x00010000) //! Mapping table //! FS0: Alias(s):F0a:;BLK0: //! PciRoot(0x0)/Pci(0x1,0x1)/Ata(0x0) //! Press ESC in 1 seconds to skip startup.nsh or any other key to continue. //! Shell> fs0: //! FS0:\> dir //! Directory of: FS0:\ //! 06/03/2021 23:33 342,016 uefi.efi //! 06/03/2021 23:42 10,383 NvVars //! 2 File(s) 433,807 bytes //! 0 Dir(s) //! FS0:\> load .\uefi.efi //! FS0:\> //! ``` #![no_std] #![no_main] #![feature(abi_efiapi)] #![warn(missing_docs)] extern crate hypervisor; extern crate uefi; use core::ffi::c_void; use core::convert::TryFrom; use hypervisor::segmentation; use hypervisor::segmentation::{GdtEntry, GdtEntry64}; use hypervisor::segmentation::Tss; use uefi::proto::pi::mp::MpServices; use uefi::{prelude::*, table::boot::MemoryType}; /// Convert a physical address to a virtual address. UEFI memory is paged and /// identity mapped. fn efi_phys_to_virt<T>(phys: u64) -> *mut T { phys as *mut T } extern "C" { /// A symbol defined by the linker representing the base of the image in /// memory. There should be a PE header here. static __ImageBase: u8; } /// Size of a page in bytes. const PAGE_SIZE: usize = 0x1000; /// Allocate and initialize a VCpu. fn efi_create_vcpu(system_table: &SystemTable<Boot>) -> uefi::Result<*mut hypervisor::VCpu> { let vcpu = system_table .boot_services() .allocate_pool( MemoryType::RUNTIME_SERVICES_DATA, core::mem::size_of::<hypervisor::VCpu>(), )? .expect("Allocation completed") as *mut hypervisor::VCpu; let tss = system_table .boot_services() .allocate_pool( MemoryType::RUNTIME_SERVICES_DATA, core::mem::size_of::<hypervisor::segmentation::Tss>(), )? .expect("Allocation completed"); let virtual_local_interrupt_controller = system_table .boot_services() .allocate_pool( MemoryType::RUNTIME_SERVICES_DATA, core::mem::size_of::<hypervisor::interrupt_controller::VirtualLocalInterruptController>( ), )? .expect("Allocation completed") as *mut hypervisor::interrupt_controller::VirtualLocalInterruptController; let vmx_on_region_phys = system_table.boot_services().allocate_pages( uefi::table::boot::AllocateType::AnyPages, MemoryType::RUNTIME_SERVICES_DATA, 1, )?; let vmcs_phys = system_table.boot_services().allocate_pages( uefi::table::boot::AllocateType::AnyPages, MemoryType::RUNTIME_SERVICES_DATA, 1, )?; let stack_pages = 1; let stack = system_table.boot_services().allocate_pages( uefi::table::boot::AllocateType::AnyPages, MemoryType::RUNTIME_SERVICES_DATA, stack_pages, )?; let msr_bitmap = system_table .boot_services() .allocate_pages( uefi::table::boot::AllocateType::AnyPages, MemoryType::RUNTIME_SERVICES_DATA, 1, )? .expect("msr bitmap allocated"); let gdt = hypervisor::segmentation::get_current_gdt(); let original_gdt_size = gdt.len() * core::mem::size_of::<GdtEntry>(); let host_gdt_size = core::mem::size_of_val(&gdt) + core::mem::size_of::<GdtEntry64>(); let host_tr_index = gdt.len(); let host_gdt = system_table .boot_services() .allocate_pool(MemoryType::RUNTIME_SERVICES_DATA, host_gdt_size)? .expect("Completion failed?"); unsafe { (*vcpu).this_vcpu = vcpu; system_table.boot_services().memmove( host_gdt, &gdt as *const _ as *const u8, original_gdt_size, ); (*vcpu).loaded_successfully = false; (*vcpu).vmcs_phys = vmcs_phys.expect("vmcs allocation"); (*vcpu).vmcs_size = PAGE_SIZE; (*vcpu).vmcs = efi_phys_to_virt((*vcpu).vmcs_phys); (*vcpu).virtual_local_interrupt_controller = virtual_local_interrupt_controller; system_table.boot_services().memset( (*vcpu).virtual_local_interrupt_controller as *mut u8, core::mem::size_of::<hypervisor::interrupt_controller::VirtualLocalInterruptController>( ), 0, ); system_table .boot_services() .memset((*vcpu).vmcs as *mut u8, (*vcpu).vmcs_size, 0); (*vcpu).vmxon_region_phys = vmx_on_region_phys.expect("vmx on allocation"); (*vcpu).vmxon_region_size = PAGE_SIZE; (*vcpu).vmxon_region = efi_phys_to_virt((*vcpu).vmxon_region_phys); system_table.boot_services().memset( (*vcpu).vmxon_region as *mut u8, (*vcpu).vmxon_region_size, 0, ); (*vcpu).msr_bitmap = msr_bitmap; system_table .boot_services() .memset(efi_phys_to_virt((*vcpu).msr_bitmap), PAGE_SIZE, 0); (*vcpu).stack_base = efi_phys_to_virt(stack.expect("Stack")); (*vcpu).stack_size = stack_pages * PAGE_SIZE; // Page size (*vcpu).stack_top = (*vcpu).stack_base.add((*vcpu).stack_size); (*vcpu).host_gdt_base = host_gdt as *mut u64; (*vcpu).host_gdt_limit = host_gdt_size as u64 - 1; system_table .boot_services() .memset(tss, core::mem::size_of::<segmentation::Tss>(), 0); let tss_base = tss as u64; (*vcpu).tr_base = tss_base; (*vcpu).tr_selector = u16::try_from(host_tr_index * core::mem::size_of::<GdtEntry>()).unwrap(); let tss_gdt_entry = host_gdt.add(original_gdt_size) as *mut GdtEntry64; (*tss_gdt_entry).access = 0xe9; (*tss_gdt_entry).granularity = 0; (*tss_gdt_entry).limit_low = u16::try_from(core::mem::size_of::<Tss>() - 1).unwrap(); (*tss_gdt_entry).base_low = tss_base as u16; (*tss_gdt_entry).base_middle = (tss_base >> 16) as u8; (*tss_gdt_entry).base_high = (tss_base >> 24) as u8; (*tss_gdt_entry).base_highest = (tss_base >> 32) as u32; (*tss_gdt_entry).reserved0 = 0; }; Ok(uefi::Completion::new(Status::SUCCESS, vcpu)) } /// Load the hypervisor on the current core. extern "efiapi" fn efi_core_load(arg: *mut c_void) { let system_table = unsafe { &*(arg as *const SystemTable<Boot>) }; let vcpu_result = efi_create_vcpu(system_table); let vcpu_ptr = vcpu_result.unwrap().unwrap(); let vcpu = unsafe { &*vcpu_ptr }; hypervisor::rustyvisor_core_load(vcpu); } /// The entrypoint of the UEFI runtime service. /// Sets up the hypervisor and loads it on every core using the UEFI /// multi-processing protocol. #[no_mangle] pub extern "efiapi" fn efi_main( _image_handle: uefi::Handle, system_table: SystemTable<Boot>, ) -> Status { hypervisor::rustyvisor_load(); efi_core_load(&system_table as *const SystemTable<Boot> as *mut c_void); let mp_proto = system_table .boot_services() .locate_protocol::<MpServices>() .expect("Mp services not found") .expect("Completion failure"); let mp_proto = unsafe { &mut *mp_proto.get() }; match mp_proto.startup_all_aps( false, efi_core_load, &system_table as *const SystemTable<Boot> as *mut c_void, None, ) { Ok(_) => Status::SUCCESS, Err(e) => match e.status() { Status::NOT_STARTED => Status::SUCCESS, e => e, }, } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/dmesg_logger/src/lib.rs
dmesg_logger/src/lib.rs
#![no_std] #![warn(missing_docs)] //! A logging facade for writing logging information to the Linux Kernel System //! Log. use log; use core::fmt; use core::fmt::Write; extern "C" { fn printk(fmt: *const u8, ...) -> i32; } /// A logger which writes to the Linux Kernel System Log. pub struct DMesgLogger {} struct PrintK {} const KERN_INFO: &[u8; 2] = b"6\0"; // https://www.kernel.org/doc/html/latest/core-api/printk-basics.html impl fmt::Write for PrintK { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { unsafe { printk(KERN_INFO.as_ptr()); } for c in s.bytes() { unsafe { printk(b"c%c\0".as_ptr(), c as u32); } } Ok(()) } } impl DMesgLogger { /// A function similar to core::fmt::Write, except that self is not /// mutable, so we can use it without doing any locking. We let Linux /// handle the locking for us. pub fn write_fmt(&self, args: core::fmt::Arguments) { let mut printk_obj = PrintK {}; let _ = write!(printk_obj, "{}\r\n", args); } } impl log::Log for DMesgLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::Level::Trace } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { self.write_fmt(*record.args()); } } fn flush(&self) {} }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/pcuart/src/lib.rs
pcuart/src/lib.rs
#![no_std] #![feature(asm)] #![warn(missing_docs)] //! A logging crate for writing logs to a PC's COM port. //! For more information see the Wikipedia page for the //! [16550 UART //chip](https://en.wikipedia.org/wiki/16550_UART), and the OS //! Dev wiki page on [Serial Ports](https://wiki.osdev.org/Serial_Ports). use core::fmt; /// Implements a logging facade over the underlying UART. pub mod logger; /// The port to be used by the UART object. #[derive(Copy, Clone)] #[repr(u16)] pub enum UartComPort { /// COM1 port, with IO port 0x3f8 Com1 = 0x3f8, /// COM2 port, with IO port 0x2f8 Com2 = 0x2f8, /// COM3 port, with IO port 0x3e8 Com3 = 0x3e8, /// COM4 port, with IO port 0x4e8 Com4 = 0x2e8, } const UART_OFFSET_TRANSMITTER_HOLDING_BUFFER: u16 = 0; //const UART_OFFSET_RECEIVER_BUFFER: u16 = 0; const UART_OFFSET_DIVISOR_LATCH_LOW: u16 = 0; const UART_OFFSET_INTERRUPT_ENABLE: u16 = 1; const UART_OFFSET_DIVISOR_LATCH_HIGH: u16 = 1; //const UART_OFFSET_INTERRUPT_IDENTIFICATION: u16 = 2; const UART_OFFSET_FIFO_CONTROL: u16 = 2; const UART_OFFSET_LINE_CONTROL: u16 = 3; const UART_OFFSET_MODEM_CONTROL: u16 = 4; const UART_OFFSET_LINE_STATUS: u16 = 5; //const UART_OFFSET_MODEM_STATUS: u16 = 6; //const UART_OFFSET_SCRATCH: u16 = 7; /// A UART object. #[derive(Default)] pub struct Uart { io_port_base: u16, } /// The baud rate for the UART. #[derive(Copy, Clone)] pub enum UartBaudRate { /// Configure the UART to use an 115200 baud rate. Baud115200 = 115200, /// Configure the UART to use a 9600 baud rate. Baud9600 = 9600, } impl Uart { /// Creates a new UART on the given COM port. pub const fn new(com: UartComPort) -> Self { Self { io_port_base: com as u16, } } /// Configures the UART with the given baud rate. pub fn init(&self, enable_receiver_interrupts: bool, baud_rate: UartBaudRate) { outw(self.io_port_base + UART_OFFSET_INTERRUPT_ENABLE, 0x00); outw(self.io_port_base + UART_OFFSET_LINE_CONTROL, 0x80); let dlab_low: u16 = baud_rate as u16 & 0xff; let dlab_high: u16 = (baud_rate as u16 >> 8) & 0xff; outw(self.io_port_base + UART_OFFSET_DIVISOR_LATCH_LOW, dlab_low); outw( self.io_port_base + UART_OFFSET_DIVISOR_LATCH_HIGH, dlab_high, ); outw(self.io_port_base + UART_OFFSET_LINE_CONTROL, 0x03); outw(self.io_port_base + UART_OFFSET_FIFO_CONTROL, 0xc7); outw(self.io_port_base + UART_OFFSET_MODEM_CONTROL, 0x0b); if enable_receiver_interrupts { //outw(self.io_port_base + UART_OFFSET_INTERRUPT_ENABLE, 0x01); unimplemented!(); } else { outw(self.io_port_base + UART_OFFSET_INTERRUPT_ENABLE, 0x00); } } } fn outw(port: u16, data: u16) { unsafe { x86::io::outw(port, data) } } fn outb(port: u16, data: u8) { unsafe { x86::io::outb(port, data) } } fn inb(port: u16) -> u8 { unsafe { x86::io::inb(port) } } impl fmt::Write for Uart { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { for c in s.chars() { while (inb(self.io_port_base + UART_OFFSET_LINE_STATUS) & 0x20) == 0 {} outb( self.io_port_base + UART_OFFSET_TRANSMITTER_HOLDING_BUFFER, c as u8, ); } Ok(()) } }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
iankronquist/rustyvisor
https://github.com/iankronquist/rustyvisor/blob/1fae5813b5c42c58bdc654b93209b46badae2dae/pcuart/src/logger.rs
pcuart/src/logger.rs
use log; use super::{Uart, UartBaudRate, UartComPort}; use core::fmt::Write; use spin::Mutex; /// A logger object suitable to writing logging information to a UART. /// Unlike the UART object, this handles synchronization. pub struct UartLogger { port: Mutex<Uart>, } /// Allows direct write access to a uart COM port without any synchronization. /// Does not allow the COM port to be reconfigured. /// This is safe because at the end of the day it's just a series of outb instructions, there are no possible memory safety issues. /// Messages can get jumbled together, but that's not necessarily an issue. /// This is useful during panics, when we want to try to write out to the serial port without causing a potential deadlock. pub struct UnsynchronizedUartLogger { port: UartComPort, } impl UnsynchronizedUartLogger { /// Creates a new UnsynchronizedUartLogger for the provided serial port. pub const fn new(port: UartComPort) -> Self { Self { port } } } impl UnsynchronizedUartLogger { /// Write the formatter directly to the UART COM port without any synchronization. /// Has a signature very similar to one of the methods in core::fmt::Write so that /// we can call it via the write! macro, but self is not mutable so we can safely /// call it on global static variables without something like a mutex. pub fn write_fmt(&self, args: core::fmt::Arguments) { let mut uart = Uart::new(self.port); let _ = write!(uart, "{}\r\n", args); } } impl UartLogger { /// Creates a new UART logger which will use the given port. pub const fn new(port: UartComPort) -> Self { Self { port: Mutex::new(Uart::new(port)), } } /// Configures the UART to use an 115200 baud rate. pub fn init(&self) { self.port.lock().init(false, UartBaudRate::Baud115200); } fn lock_port_with_timeout(&self) -> spin::MutexGuard<Uart> { let timeout = 0x1000; let mut count = 0; while count < timeout { if let Some(guard) = self.port.try_lock() { return guard; } count += 1; } panic!("Timeout exceeded"); } } impl log::Log for UartLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::Level::Trace } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { let _ = write!( self.lock_port_with_timeout(), "{}: {}\r\n", record.level(), record.args() ); } } fn flush(&self) {} } impl log::Log for UnsynchronizedUartLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::Level::Trace } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { let mut uart = Uart::new(self.port); let _ = write!(uart, "{}: {}\r\n", record.level(), record.args()); } } fn flush(&self) {} }
rust
MIT
1fae5813b5c42c58bdc654b93209b46badae2dae
2026-01-04T20:25:32.050337Z
false
gahag/bgrep
https://github.com/gahag/bgrep/blob/921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a/src/args.rs
src/args.rs
use std::ffi::OsString; use std::path::PathBuf; use clap::{self, App, Arg, ArgMatches}; use clap::{crate_authors, crate_version, crate_name, crate_description}; /// The output mode. #[derive(Debug)] pub enum Output { FileName, Bytes, Offset } impl Default for Output { fn default() -> Output { Output::FileName } } /// The values of all flags, except help and version. #[derive(Default, Debug)] pub struct Options { pub inverse: bool, pub case_insensitive: bool, pub trim_ending_newline: bool, pub non_matching: bool, // Whether to print non matching files. Only true when (-L). pub print_filename: bool, pub output: Output } /// The arguments when the action is grep. #[derive(Default, Debug)] pub struct Args { pub options: Options, pub pattern: String, pub files: Box<[PathBuf]> } /// The action to be executed. #[derive(Debug)] pub enum Command { Help(String), Version(String), Grep(Args) } /// The error type for the argument parser. Contains only the error message. #[derive(Debug)] pub struct Error { pub message: String } /// The path used to denote reading from stdin. pub const STDIN: &str = "-"; /// Build clap's `App`. This specifies all arguments and metadata. fn build_app() -> App<'static, 'static> { App::new(crate_name!()) .about(crate_description!()) .author(crate_authors!()) .version(crate_version!()) .template("{bin} {version}\nMade by {author}\n{about}\n\n{usage}\n\nFLAGS:\n{flags}") // Positional arguments: .arg( Arg::with_name("pattern") .required(true) .index(1) ) .arg( Arg::with_name("files") .multiple(true) .default_value(STDIN) .index(2) ) // Matching flags: .arg( Arg::with_name("invert-match") .short("v") .long("invert-match") .help("Invert the sense of matching, to select non matching slices") ) .arg( Arg::with_name("ignore-case") .short("i") .long("ignore-case") .help("Case insensitive matching for ASCII alphabetic characters") ) // Input flags: .arg( Arg::with_name("trim-ending-newline") .short("n") .long("trim-ending-newline") .help("If the file ends with a newline, disconsider the last byte") ) // Output flags: .arg( Arg::with_name("with-filename") .short("H") .long("with-filename") .help("Print the file name for each match (default when there are multiple files).") .overrides_with("no-filename") ) .arg( Arg::with_name("no-filename") .short("h") .long("no-filename") .help("Suppress the file names on output (default when there is a single file).") .overrides_with("with-filename") .conflicts_with_all(&[ "files-with-matches", "files-without-matches", ]) ) .arg( Arg::with_name("only-matching") .short("o") .long("only-matching") .help("Prints the matched bytes of each match") .overrides_with_all(&[ "byte-offset", "files-with-matches", "files-without-matches", ]) ) .arg( Arg::with_name("byte-offset") .short("b") .long("byte-offset") .help("Prints the byte offset of each match") .overrides_with_all(&[ "only-matching", "files-with-matches", "files-without-matches", ]) ) .arg( Arg::with_name("files-with-matches") .short("l") .long("files-with-matches") .help("Prints the name of the matched files (default output mode)") .overrides_with_all(&[ "only-matching", "byte-offset", "files-without-matches", ]) ) .arg( Arg::with_name("files-without-matches") .short("L") .long("files-without-matches") .help("Prints the name of non-matched files") .overrides_with_all(&[ "only-matching", "byte-offset", "files-with-matches", ]) ) } /// Build an `Args` from clap's `ArgMatches`. /// The matches are supposed to be valid, therefore there is no error handling/reporting. fn build_args(args: ArgMatches) -> Args { let pattern = args.value_of("pattern") .expect("<pattern> not in ArgMatches") // pattern is required. .to_owned(); let files: Box<[PathBuf]> = args.values_of_os("files") .expect("<files> not in ArgMatches") .map(PathBuf::from) .collect(); let flag = |f| args.is_present(f); let output_flags = ( flag("only-matching"), flag("byte-offset"), flag("files-with-matches"), flag("files-without-matches") ); let output = match output_flags { (true, _, _, _) => Output::Bytes, (_, true, _, _) => Output::Offset, (_, _, true, _) => Output::FileName, (_, _, _, true) => Output::FileName, (_, _, _, _) => Default::default(), }; Args { options: Options { inverse: flag("invert-match"), case_insensitive: flag("ignore-case"), trim_ending_newline: flag("trim-ending-newline"), non_matching: flag("files-without-matches"), print_filename: flag("with-filename") || !(flag("no-filename") || files.len() == 1), output }, pattern, files } } /// Parse the arguments from `std::env::args_os`. /// Returns the command to be executed, or the error message. pub fn parse< T: Into<OsString> + Clone, A: IntoIterator<Item = T> >(args: A) -> Result<Command, Error> { let app = build_app(); match app.get_matches_from_safe(args) { Ok(arg_matches) => Ok(Command::Grep(build_args(arg_matches))), Err(e) => match e.kind { clap::ErrorKind::HelpDisplayed => Ok(Command::Help(e.message)), clap::ErrorKind::VersionDisplayed => Ok(Command::Version(e.message)), _ => Err(Error { message: e.message }) } } }
rust
BSD-3-Clause
921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a
2026-01-04T20:25:30.957998Z
false
gahag/bgrep
https://github.com/gahag/bgrep/blob/921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a/src/grep.rs
src/grep.rs
use std::io; use std::io::{Read, Write}; use std::fs::File; use std::path::{Path, PathBuf}; use std::fmt::Display; use regex::bytes::{Regex, RegexBuilder}; use crate::args::{self, Args}; /// Build the regex pattern with the given options. /// By default, the `unicode` flag is set to false, and `dot_matches_new_line` set to true. fn build_pattern<P: AsRef<str>>( pattern: &P, options: &args::Options ) -> Result<Regex, regex::Error> { let mut builder = RegexBuilder::new(pattern.as_ref()); builder.unicode(false); builder.dot_matches_new_line(true); builder.case_insensitive(options.case_insensitive); builder.build() } /// Run bgrep, outputting `path` to the given `out` if there is a match. /// Returns whether there was a match. fn grep_filename<O: Write, P: Display, B: AsRef<[u8]>>( out: &mut O, options: &args::Options, pattern: &Regex, path: P, buffer: B ) -> io::Result<bool> { let buffer = buffer.as_ref(); // When inverse matching, matches must be checked until a "hole" is found. // Otherwise, the more performant `Regex::is_match` can be used. if options.inverse { // if the pattern matches multiple times, comprising the entire buffer, then no // inverse match is present. let mut matches = pattern.find_iter(buffer); let mut end = 0; // Start from the beginning of the buffer. // Try to find a "hole" between matches: let inverse_match = matches.find( |m| { let matched = m.start() > end; end = m.end(); matched } ); // Also check for a "hole" after the last match. let matched = (inverse_match.is_some() || end < buffer.len()) ^ options.non_matching; // List non matching files. if matched { writeln!(out, "{}", path)?; } Ok(matched) } else { let matched = pattern.is_match(buffer) ^ options.non_matching; if matched { writeln!(out, "{}", path)?; } Ok(matched) } } /// Run bgrep, outputting the matched bytes to the given `out`. /// Returns whether there was a match. fn grep_bytes<O: Write, P: Display, B: AsRef<[u8]>>( out: &mut O, options: &args::Options, pattern: &Regex, path: P, buffer: B, ) -> io::Result<bool> { let buffer = buffer.as_ref(); let mut write_bytes = |bs| { if options.print_filename { write!(out, "{}: ", path)?; } out.write_all(bs)?; writeln!(out) }; let mut matched = false; if options.inverse { // `Regex::split` yields the slices outside the matches. let mut matches = pattern.split(buffer); // Set `matched` if there is a first occurrence: if let Some(bs) = matches.next() { if !bs.is_empty() { // A regex may have a empty match, but when inverse matching write_bytes(bs)?; // we disconsider empty intervals. matched = true; } }; // Iterate the remaining matches: for bs in matches { if !bs.is_empty() { write_bytes(bs)?; } } } else { let mut matches = pattern.find_iter(buffer); // Set `matched` if there is a first occurrence: if let Some(m) = matches.next() { write_bytes(m.as_bytes())?; matched = true; } // Iterate the remaining matches: for m in matches { write_bytes(m.as_bytes())?; } }; Ok(matched) } /// Run bgrep, outputting the matche's offset in hex to the given `out`. /// Returns whether there was a match. fn grep_offset<O: Write, P: Display, B: AsRef<[u8]>>( out: &mut O, options: &args::Options, pattern: &Regex, path: P, buffer: B ) -> io::Result<bool> { let buffer = buffer.as_ref(); let mut write_hex = |x| { if options.print_filename { writeln!(out, "{}: 0x{:x}", path, x) } else { writeln!(out, "0x{:x}", x) } }; let mut matches = pattern.find_iter(buffer); let mut matched = false; if options.inverse { // if the pattern matches multiple times, comprising the entire buffer, then no // inverse match is present. let mut end = 0; // Start from the beginning of the buffer. for m in matches { if m.start() > end { write_hex(end)?; matched = true; } end = m.end() } if end < buffer.len() { // Also check for a "hole" after the last match. write_hex(end)?; matched = true; } } else { // Set `matched` if there is a first occurrence: if let Some(m) = matches.next() { write_hex(m.start())?; matched = true; } // Iterate the remaining matches: for m in matches { write_hex(m.start())?; } } Ok(matched) } /// Run bgrep with the given options, outputting to the given `out`. /// Error detail may be outputted to stderr. /// Returns whether there was a match. fn run_file<O: Write, P: AsRef<Path>, B: AsMut<Vec<u8>>>( out: &mut O, options: &args::Options, pattern: &Regex, path: P, buffer: &mut B ) -> io::Result<bool> { let buffer = buffer.as_mut(); let path = path.as_ref(); buffer.clear(); let (read_result, path) = if path == Path::new(args::STDIN) { // Path::new is cost-free. (io::stdin().lock().read_to_end(buffer), Path::new("<stdin>").display()) } else { let mut file = File::open(path) .map_err(|e| { eprintln!("Error: failed to open file '{}'", path.display()); e })?; // Resize buffer to the file size if it exceeds the current size. // Currently, the strategy is to grow if needed, and otherwise do nothing. // Considering we never shrink the buffer, this can be bad if the first file // is huge and the others are small. let file_size = file.metadata() .map(|m| m.len()) .unwrap_or(0) as usize; buffer.reserve( file_size.saturating_sub(buffer.len()) ); (file.read_to_end(buffer), path.display()) }; if let Err(e) = read_result { eprintln!("Error: failed to read file '{}'", path); return Err(e); } // Trim the ending newline if requested and present: if options.trim_ending_newline && buffer.last() == Some(&b'\n') { buffer.pop(); }; let matched = match options.output { args::Output::FileName => grep_filename (out, options, pattern, path, buffer), args::Output::Bytes => grep_bytes (out, options, pattern, path, buffer), args::Output::Offset => grep_offset (out, options, pattern, path, buffer) }?; Ok(matched) } /// Run bgrep with the given args, outputting to stdout. /// Error detail may be outputted to stderr. /// Returns whether there was a match. pub fn run<O: Write>(args: Args, out: &mut O) -> io::Result<bool> { // Deconstruct to split ownership: let Args { options, pattern, files } = args; let pattern = build_pattern(&pattern, &options).map_err( |e| { eprintln!("Error: invalid pattern '{}', {}", pattern, e); io::ErrorKind::InvalidInput } )?; // Reuse the same buffer for all the files, minimizing allocations. let mut buffer = Vec::<u8>::new(); // The next part is a bit complicated: // Bgrep must return: // // 0 if there was any match, and no errors. `BrokenPipe` is not considered an error, // but a signal to stop processing. // // 1 if there was no match, and no errors. `BrokenPipe` cannot happen in this case, // because it should only happen when outputting, and no matches means no output. // // An error code corresponding to the last error. Common errors are `NotFound` and // `PermissionDenied`. // We need to store the last generated error if any, or whether there was a match: let mut result = Ok(false); // Converting to vec to use the owned iterator. Box<[T]> has no owned iterator. for file in files.to_vec() { let file: PathBuf = file; // Make sure we are using an owned iterator. match run_file(out, &options, &pattern, &file, &mut buffer) { Ok(false) => (), Ok(true) => result = result.map(|_| true), // Set to true if there was no error. Err(e) => if e.kind() == io::ErrorKind::BrokenPipe { // Bail early on `BronkenPipe`, conserving the previous error if any. result = result.map(|_| true); // `BrokenPipe` only happens when outputting, break; // and that means there was a match. } else { result = Err(e) // Store the error and move on. } } } result }
rust
BSD-3-Clause
921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a
2026-01-04T20:25:30.957998Z
false
gahag/bgrep
https://github.com/gahag/bgrep/blob/921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a/src/main.rs
src/main.rs
mod args; mod grep; use std::env; use std::io::{self, Write}; use std::process; use args::Command; /// Main does not return because we use `process::exit`. fn main() -> ! { /// Run bgrep with `std::env::args_os`, outputting to stdout. /// Error detail may be outputted to stderr. /// Returns whether there was a match. fn run() -> io::Result<bool> { // Returns whether there was a match. let args = env::args_os(); let command = args::parse(args).map_err( |e| { eprintln!("{}", e.message); io::ErrorKind::InvalidInput } )?; // Lock stdout to prevent repetitive locking. let stdout = io::stdout(); let mut stdout = stdout.lock(); match command { Command::Grep(args) => grep::run(args, &mut stdout), Command::Help(msg) | Command::Version(msg) => { writeln!(stdout, "{}", msg)?; Ok(true) } } } process::exit( match run() { Ok(true) => 0, // There was at least one match. Ok(false) => 1, // There was no match. Err(e) => match e.kind() { io::ErrorKind::InvalidInput => 3, io::ErrorKind::NotFound => 4, io::ErrorKind::PermissionDenied => 5, io::ErrorKind::Interrupted => 130, _ => 2 } } ) }
rust
BSD-3-Clause
921f84d6aa7d5daabe0d95a24ba912cfac8cdb5a
2026-01-04T20:25:30.957998Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/src/lib.rs
src/lib.rs
//! **wgpu-text** is a wrapper over **[glyph-brush](https://github.com/alexheretic/glyph-brush)** //! for simpler text rendering in **[wgpu](https://github.com/gfx-rs/wgpu)**. //! //! This project was inspired by and is similar to [wgpu_glyph](https://github.com/hecrj/wgpu_glyph), //! but has additional features and is more straightforward. Also, there is no need to //! include **glyph-brush** in your project. //! //! Since the crate **glyph-brush** is reexported and heavily dependent on, it's recommended to go through //! [Section docs](https://docs.rs/glyph_brush/latest/glyph_brush/struct.Section.html) and //! [Section examples](https://github.com/alexheretic/glyph-brush/tree/master/gfx-glyph/examples) //! for a better understanding of adding and managing text. //! //! To learn about GPU texture caching, see //! [`caching behaviour`](https://docs.rs/glyph_brush/latest/glyph_brush/struct.GlyphBrush.html#caching-behaviour) //! //! > Look trough [`examples`](https://github.com/Blatko1/wgpu_text/tree/master/examples). // TODO fix VULKAN error when running examples mod brush; mod cache; mod error; mod pipeline; pub use brush::{BrushBuilder, TextBrush}; pub use error::BrushError; pub use glyph_brush; /// Represents a two-dimensional array matrix with 4x4 dimensions. pub type Matrix = [[f32; 4]; 4]; /// Creates an orthographic matrix with given dimensions `width` and `height`. #[rustfmt::skip] pub fn ortho(width: f32, height: f32) -> Matrix { [ [2.0 / width, 0.0, 0.0, 0.0], [0.0, -2.0 / height, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [-1.0, 1.0, 0.0, 1.0] ] }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/src/error.rs
src/error.rs
use std::{error::Error, fmt::Display}; /// Result of `TextBrush` errors and problems. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BrushError { /// Cache texture exceeded the limitations stated in `wgpu::Device`. TooBigCacheTexture(u32), } impl Error for BrushError {} impl Display for BrushError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "wgpu-text: ")?; match self { BrushError::TooBigCacheTexture(dimensions) => write!( f, "While trying to resize the \ cache texture, the 'wgpu::Limits {{ max_texture_dimension_2d }}' \ limit of {dimensions} was crossed!\n\ Resizing the cache texture should be avoided \ from the start by building TextBrush with \ BrushBuilder::initial_cache_size() and providing bigger cache \ texture dimensions." ), } } }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/src/pipeline.rs
src/pipeline.rs
use std::num::NonZeroU32; use glyph_brush::{ Rectangle, ab_glyph::{Rect, point}, }; use wgpu::util::DeviceExt; use crate::{Matrix, cache::Cache}; /// Responsible for drawing text. #[derive(Debug)] pub struct Pipeline { inner: wgpu::RenderPipeline, cache: Cache, vertex_buffer: wgpu::Buffer, vertex_buffer_len: usize, vertices: u32, } impl Pipeline { pub fn new( device: &wgpu::Device, render_format: wgpu::TextureFormat, depth_stencil: Option<wgpu::DepthStencilState>, multisample: wgpu::MultisampleState, multiview_mask: Option<NonZeroU32>, tex_dimensions: (u32, u32), matrix: Matrix, ) -> Pipeline { let cache = Cache::new(device, tex_dimensions, matrix); let shader = device.create_shader_module(wgpu::include_wgsl!("shader/shader.wgsl")); let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("wgpu-text Vertex Buffer"), size: 0, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("wgpu-text Render Pipeline Layout"), bind_group_layouts: &[&cache.bind_group_layout], immediate_size: 0, }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("wgpu-text Render Pipeline"), layout: Some(&pipeline_layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some("vs_main"), buffers: &[Vertex::buffer_layout()], compilation_options: Default::default(), }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, strip_index_format: Some(wgpu::IndexFormat::Uint16), ..Default::default() }, depth_stencil, multisample, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: Some("fs_main"), targets: &[Some(wgpu::ColorTargetState { format: render_format, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: Default::default(), }), cache: None, multiview_mask, }); Self { inner: pipeline, cache, vertex_buffer, vertex_buffer_len: 0, vertices: 0, } } /// Raw draw. pub fn draw(&self, rpass: &mut wgpu::RenderPass) { if self.vertices != 0 { rpass.set_pipeline(&self.inner); rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); rpass.set_bind_group(0, &self.cache.bind_group, &[]); rpass.draw(0..4, 0..self.vertices); } } // TODO look into preallocating the vertex buffer instead of constantly reallocating pub fn update_vertex_buffer( &mut self, vertices: Vec<Vertex>, device: &wgpu::Device, queue: &wgpu::Queue, ) { self.vertices = vertices.len() as u32; let data: &[u8] = bytemuck::cast_slice(&vertices); if vertices.len() > self.vertex_buffer_len { self.vertex_buffer_len = vertices.len(); self.vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("wgpu-text Vertex Buffer"), usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, contents: data, }); return; } queue.write_buffer(&self.vertex_buffer, 0, data); } #[inline] pub fn update_matrix(&self, matrix: Matrix, queue: &wgpu::Queue) { self.cache.update_matrix(matrix, queue); } #[inline] pub fn update_texture(&self, size: Rectangle<u32>, data: &[u8], queue: &wgpu::Queue) { self.cache.update_texture(size, data, queue); } #[inline] pub fn resize_texture(&mut self, device: &wgpu::Device, tex_dimensions: (u32, u32)) { self.cache.recreate_texture(device, tex_dimensions); } } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { top_left: [f32; 3], bottom_right: [f32; 2], tex_top_left: [f32; 2], tex_bottom_right: [f32; 2], color: [f32; 4], } impl Vertex { pub fn to_vertex( glyph_brush::GlyphVertex { mut tex_coords, pixel_coords, bounds, extra, }: glyph_brush::GlyphVertex, ) -> Vertex { let mut rect = Rect { min: point(pixel_coords.min.x, pixel_coords.min.y), max: point(pixel_coords.max.x, pixel_coords.max.y), }; // handle overlapping bounds, modify uv_rect to preserve texture aspect if rect.max.x > bounds.max.x { let old_width = rect.width(); rect.max.x = bounds.max.x; tex_coords.max.x = tex_coords.min.x + tex_coords.width() * rect.width() / old_width; } if rect.min.x < bounds.min.x { let old_width = rect.width(); rect.min.x = bounds.min.x; tex_coords.min.x = tex_coords.max.x - tex_coords.width() * rect.width() / old_width; } if rect.max.y > bounds.max.y { let old_height = rect.height(); rect.max.y = bounds.max.y; tex_coords.max.y = tex_coords.min.y + tex_coords.height() * rect.height() / old_height; } if rect.min.y < bounds.min.y { let old_height = rect.height(); rect.min.y = bounds.min.y; tex_coords.min.y = tex_coords.max.y - tex_coords.height() * rect.height() / old_height; } Vertex { top_left: [rect.min.x, rect.min.y, extra.z], bottom_right: [rect.max.x, rect.max.y], tex_top_left: [tex_coords.min.x, tex_coords.min.y], tex_bottom_right: [tex_coords.max.x, tex_coords.max.y], color: extra.color, } } pub fn buffer_layout() -> wgpu::VertexBufferLayout<'static> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Instance, attributes: &[ wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0, }, wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, }, wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: std::mem::size_of::<[f32; 5]>() as wgpu::BufferAddress, shader_location: 2, }, wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: std::mem::size_of::<[f32; 7]>() as wgpu::BufferAddress, shader_location: 3, }, wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x4, offset: std::mem::size_of::<[f32; 9]>() as wgpu::BufferAddress, shader_location: 4, }, ], } } }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/src/brush.rs
src/brush.rs
use std::num::NonZeroU32; use crate::{ Matrix, error::BrushError, pipeline::{Pipeline, Vertex}, }; use glyph_brush::{ BrushAction, DefaultSectionHasher, Extra, GlyphCruncher, Section, SectionGlyphIter, ab_glyph::{Font, FontArc, FontRef, InvalidFont, Rect}, }; /// Wrapper over [`glyph_brush::GlyphBrush`]. In charge of drawing text. /// /// Used for queuing and rendering text with [`TextBrush::draw`]. pub struct TextBrush<F = FontArc, H = DefaultSectionHasher> { inner: glyph_brush::GlyphBrush<Vertex, Extra, F, H>, pipeline: Pipeline, } impl<F, H> TextBrush<F, H> where F: Font + Sync, H: std::hash::BuildHasher, { /// Queues section for drawing, processes all queued text and updates the /// inner vertex buffer, unless the text vertices remain unmodified when /// compared to the last frame. /// /// If utilizing *depth*, the `sections` list should have `Section`s ordered from /// furthest to closest. They will be drawn in the order they are given. /// /// - This method should be called every frame. /// /// If not called when required, the draw functions will continue drawing data from the /// inner vertex buffer meaning they will redraw old vertices. /// /// To learn about GPU texture caching, see /// [`caching behaviour`](https://docs.rs/glyph_brush/latest/glyph_brush/struct.GlyphBrush.html#caching-behaviour) #[inline] pub fn queue<'a, S, I: IntoIterator<Item = S>>( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, sections: I, ) -> Result<(), BrushError> where S: Into<std::borrow::Cow<'a, Section<'a>>>, { // Queue sections: for s in sections { self.inner.queue(s); } // Process sections: loop { // Contains BrushAction enum which marks for // drawing or redrawing (using old data). let brush_action = self.inner.process_queued( |rect, data| self.pipeline.update_texture(rect, data, queue), Vertex::to_vertex, ); match brush_action { Ok(action) => { break match action { BrushAction::Draw(vertices) => { self.pipeline.update_vertex_buffer(vertices, device, queue) } BrushAction::ReDraw => (), }; } Err(glyph_brush::BrushError::TextureTooSmall { suggested }) => { if log::log_enabled!(log::Level::Warn) { log::warn!( "Resizing cache texture! This should be avoided \ by building TextBrush with BrushBuilder::initial_cache_size() \ and providing bigger cache texture dimensions." ); } // Texture resizing: let max_image_dimension = device.limits().max_texture_dimension_2d; let (width, height) = if suggested.0 > max_image_dimension || suggested.1 > max_image_dimension { if self.inner.texture_dimensions().0 < max_image_dimension || self.inner.texture_dimensions().1 < max_image_dimension { (max_image_dimension, max_image_dimension) } else { return Err(BrushError::TooBigCacheTexture( max_image_dimension, )); } } else { suggested }; self.pipeline.resize_texture(device, (width, height)); self.inner.resize_texture(width, height); } } } Ok(()) } /// Returns a bounding box for the section glyphs calculated using each /// glyph's vertical & horizontal metrics. For more info, read about /// [`GlyphCruncher::glyph_bounds`]. #[inline] pub fn glyph_bounds<'a, S>(&mut self, section: S) -> Option<Rect> where S: Into<std::borrow::Cow<'a, Section<'a>>>, { self.inner.glyph_bounds(section) } /// Returns an iterator over the `PositionedGlyph`s of the given section. #[inline] pub fn glyphs_iter<'a, 'b, S>(&'b mut self, section: S) -> SectionGlyphIter<'b> where S: Into<std::borrow::Cow<'a, Section<'a>>>, { self.inner.glyphs(section) } /// Returns the available fonts. /// /// The `FontId` corresponds to the index of the font data. pub fn fonts(&self) -> &[F] { self.inner.fonts() } /// Draws all sections queued with [`queue`](#method.queue) function. #[inline] pub fn draw(&self, rpass: &mut wgpu::RenderPass) { self.pipeline.draw(rpass) } /// Resizes the view matrix. Updates the default orthographic view matrix with /// provided dimensions and uses it for rendering. /// /// Run this function whenever the surface config is resized. /// **Surface** dimensions are most commonly *width* and *height*. /// /// **Matrix**: /// ```rust /// pub fn ortho(width: f32, height: f32) -> [[f32; 4]; 4] { /// [ /// [2.0 / width, 0.0, 0.0, 0.0], /// [0.0, -2.0 / height, 0.0, 0.0], /// [0.0, 0.0, 1.0, 0.0], /// [-1.0, 1.0, 0.0, 1.0] /// ] /// } /// ``` #[inline] pub fn resize_view(&self, width: f32, height: f32, queue: &wgpu::Queue) { self.update_matrix(crate::ortho(width, height), queue); } /// Resizes the view. Updates text rendering matrix with the provided one. /// /// Use [`Self::resize_view()`] to update and replace the current render matrix /// with a default orthographic matrix. /// /// Feel free to use [`ortho()`] to create more complex matrices by yourself. #[inline] pub fn update_matrix<M>(&self, matrix: M, queue: &wgpu::Queue) where M: Into<Matrix>, { self.pipeline.update_matrix(matrix.into(), queue); } } /// Builder for [`TextBrush`]. #[non_exhaustive] pub struct BrushBuilder<F, H = DefaultSectionHasher> { inner: glyph_brush::GlyphBrushBuilder<F, H>, depth_stencil: Option<wgpu::DepthStencilState>, multisample: wgpu::MultisampleState, multiview: Option<NonZeroU32>, matrix: Option<Matrix>, } impl BrushBuilder<()> { /// Creates a [`BrushBuilder`] with [`Font`]. pub fn using_font<F: Font>(font: F) -> BrushBuilder<F> { BrushBuilder::using_fonts(vec![font]) } /// Creates a [`BrushBuilder`] with font byte data. pub fn using_font_bytes( data: &[u8], ) -> Result<BrushBuilder<FontRef<'_>>, InvalidFont> { let font = FontRef::try_from_slice(data)?; Ok(BrushBuilder::using_fonts(vec![font])) } /// Creates a [`BrushBuilder`] with multiple fonts byte data. pub fn using_font_bytes_vec( data: &[u8], ) -> Result<BrushBuilder<FontRef<'_>>, InvalidFont> { let font = FontRef::try_from_slice(data)?; Ok(BrushBuilder::using_fonts(vec![font])) } /// Creates a [`BrushBuilder`] with multiple [`Font`]. pub fn using_fonts<F: Font>(fonts: Vec<F>) -> BrushBuilder<F> { BrushBuilder { inner: glyph_brush::GlyphBrushBuilder::using_fonts(fonts), depth_stencil: None, multisample: wgpu::MultisampleState::default(), multiview: None, matrix: None, } } } impl<F, H> BrushBuilder<F, H> where F: Font, H: std::hash::BuildHasher, { // Default `BrushBuilder` functions: glyph_brush::delegate_glyph_brush_builder_fns!(inner); /// Uses the provided `matrix` when rendering. /// /// To update the render matrix use [`TextBrush::update_matrix()`]. pub fn with_matrix<M>(mut self, matrix: M) -> Self where M: Into<Matrix>, { self.matrix = Some(matrix.into()); self } /// Provide the `wgpu::MultisampleState` used by the inner pipeline. /// /// Defaults to value returned by [`wgpu::MultisampleState::default()`]. pub fn with_multisample(mut self, multisample: wgpu::MultisampleState) -> Self { self.multisample = multisample; self } /// Provide the `multiview` attribute used by the inner pipeline. /// /// Defaults to `None`. pub fn with_multiview(mut self, multiview: NonZeroU32) -> Self { self.multiview = Some(multiview); self } /// Provide the *depth_stencil* if you are planning to utilize depth testing. /// /// For each section, depth can be set by modifying the z coordinate /// ([`glyph_brush::OwnedText::with_z()`]). /// /// `z` coordinate should be in range /// [0.0, 1.0] not including 1.0. pub fn with_depth_stencil( mut self, depth_stencil: Option<wgpu::DepthStencilState>, ) -> BrushBuilder<F, H> { self.depth_stencil = depth_stencil; self } /// Builds a [`TextBrush`] while consuming [`BrushBuilder`], for later drawing text /// onto a texture of the specified `render_width`, `render_height` and [`wgpu::TextureFormat`]. /// /// If you are drawing a basic UI, you'd most likely want to be using /// [`wgpu::SurfaceConfiguration`]'s dimensions and texture format. pub fn build( self, device: &wgpu::Device, render_width: u32, render_height: u32, render_format: wgpu::TextureFormat, ) -> TextBrush<F, H> { let inner = self.inner.build(); let matrix = self .matrix .unwrap_or_else(|| crate::ortho(render_width as f32, render_height as f32)); let pipeline = Pipeline::new( device, render_format, self.depth_stencil, self.multisample, self.multiview, inner.texture_dimensions(), matrix, ); TextBrush { inner, pipeline } } }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/src/cache.rs
src/cache.rs
use glyph_brush::Rectangle; use wgpu::util::DeviceExt; use crate::Matrix; /// Responsible for texture caching and the global matrix. #[derive(Debug)] pub struct Cache { pub bind_group_layout: wgpu::BindGroupLayout, pub bind_group: wgpu::BindGroup, matrix_buffer: wgpu::Buffer, texture: wgpu::Texture, sampler: wgpu::Sampler, } impl Cache { pub fn new( device: &wgpu::Device, tex_dimensions: (u32, u32), matrix: Matrix, ) -> Self { let texture = Self::create_cache_texture(device, tex_dimensions); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("wgpu-text Cache Texture Sampler"), address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, ..Default::default() }); let matrix_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("wgpu-text Matrix Buffer"), contents: bytemuck::cast_slice(&matrix), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("wgpu-text Matrix, Texture and Sampler Bind Group Layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: std::num::NonZeroU64::new( std::mem::size_of::<Matrix>() as wgpu::BufferAddress, ), }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true, }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler( wgpu::SamplerBindingType::Filtering, ), count: None, }, ], }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("wgpu-text Bind Group"), layout: &bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: matrix_buffer.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView( &texture.create_view(&wgpu::TextureViewDescriptor::default()), ), }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&sampler), }, ], }); Self { matrix_buffer, texture, sampler, bind_group, bind_group_layout, } } pub fn recreate_texture( &mut self, device: &wgpu::Device, tex_dimensions: (u32, u32), ) { self.texture = Self::create_cache_texture(device, tex_dimensions); self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("wgpu-text Bind Group"), layout: &self.bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: self.matrix_buffer.as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView( &self .texture .create_view(&wgpu::TextureViewDescriptor::default()), ), }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler), }, ], }); } pub fn update_matrix(&self, matrix: Matrix, queue: &wgpu::Queue) { queue.write_buffer(&self.matrix_buffer, 0, bytemuck::cast_slice(&matrix)); } pub fn update_texture(&self, size: Rectangle<u32>, data: &[u8], queue: &wgpu::Queue) { queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &self.texture, mip_level: 0, origin: wgpu::Origin3d { x: size.min[0], y: size.min[1], z: 0, }, aspect: wgpu::TextureAspect::All, }, data, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size.width()), rows_per_image: Some(size.height()), }, wgpu::Extent3d { width: size.width(), height: size.height(), depth_or_array_layers: 1, }, ) } fn create_cache_texture( device: &wgpu::Device, dimensions: (u32, u32), ) -> wgpu::Texture { let size = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth_or_array_layers: 1, }; device.create_texture(&wgpu::TextureDescriptor { label: Some("wgpu-text Cache Texture"), size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::R8Unorm, usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, view_formats: &[], }) } }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/simple.rs
examples/simple.rs
#[path = "ctx.rs"] mod ctx; use ctx::Ctx; use glyph_brush::OwnedSection; use glyph_brush::ab_glyph::FontRef; use std::sync::Arc; use std::time::{Duration, Instant}; use wgpu_text::glyph_brush::{ BuiltInLineBreaker, Layout, OwnedText, Section, Text, VerticalAlign, }; use wgpu_text::{BrushBuilder, TextBrush}; use winit::application::ApplicationHandler; use winit::event::{ElementState, WindowEvent}; use winit::event::{KeyEvent, MouseScrollDelta}; use winit::event_loop::{self, ActiveEventLoop, ControlFlow}; use winit::keyboard::{Key, NamedKey}; use winit::window::Window; struct State<'a> { // Use an `Option` to allow the window to not be available until the // application is properly running. window: Option<Arc<Window>>, font: &'a [u8], brush: Option<TextBrush<FontRef<'a>>>, font_size: f32, section_0: Option<OwnedSection>, section_1: Option<OwnedSection>, target_framerate: Duration, delta_time: Instant, fps_update_time: Instant, fps: i32, // wgpu ctx: Option<Ctx>, } impl ApplicationHandler for State<'_> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { let window = Arc::new( event_loop .create_window( Window::default_attributes() .with_title("wgpu-text: 'simple' example"), ) .unwrap(), ); self.ctx = Some(Ctx::new(window.clone())); let ctx = self.ctx.as_ref().unwrap(); let device = &ctx.device; let config = &ctx.config; self.brush = Some(BrushBuilder::using_font_bytes(self.font).unwrap().build( device, config.width, config.height, config.format, )); self.section_0 = Some( Section::default() .add_text( Text::new( "Try typing some text,\n \ del - delete all, backspace - remove last character", ) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ) .with_bounds((config.width as f32 * 0.4, config.height as f32)) .with_layout( Layout::default() .v_align(VerticalAlign::Center) .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ) .with_screen_position((50.0, config.height as f32 * 0.5)) .to_owned(), ); self.section_1 = Some( Section::default() .add_text( Text::new("Other section") .with_scale(40.0) .with_color([0.2, 0.5, 0.8, 1.0]), ) .with_bounds((config.width as f32 * 0.5, config.height as f32)) .with_layout( Layout::default() .v_align(VerticalAlign::Top) .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ) .with_screen_position((500.0, config.height as f32 * 0.2)) .to_owned(), ); self.window = Some(window); } fn window_event( &mut self, elwt: &ActiveEventLoop, _window_id: winit::window::WindowId, event: WindowEvent, ) { match event { WindowEvent::Resized(new_size) => { let ctx = self.ctx.as_mut().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &mut ctx.config; let surface = &ctx.surface; let section_0 = self.section_0.as_mut().unwrap(); let brush = self.brush.as_mut().unwrap(); config.width = new_size.width.max(1); config.height = new_size.height.max(1); surface.configure(device, config); section_0.bounds = (config.width as f32 * 0.4, config.height as _); section_0.screen_position.1 = config.height as f32 * 0.5; brush.resize_view(config.width as f32, config.height as f32, queue); // You can also do this! // brush.update_matrix(wgpu_text::ortho(config.width, config.height), &queue); } WindowEvent::CloseRequested => elwt.exit(), WindowEvent::KeyboardInput { event: KeyEvent { logical_key, state: ElementState::Pressed, .. }, .. } => match logical_key { Key::Named(k) => match k { NamedKey::Escape => elwt.exit(), NamedKey::Delete => self.section_0.as_mut().unwrap().text.clear(), NamedKey::Backspace if !self.section_0.clone().unwrap().text.is_empty() => { let section = self.section_0.as_mut().unwrap(); let mut end_text = section.text.remove(section.text.len() - 1); end_text.text.pop(); if !end_text.text.is_empty() { self.section_0.as_mut().unwrap().text.push(end_text.clone()); } } _ => (), }, Key::Character(char) => { let c = char.as_str(); if c != "\u{7f}" && c != "\u{8}" { if self.section_0.clone().unwrap().text.is_empty() { self.section_0.as_mut().unwrap().text.push( OwnedText::default() .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ); } self.section_0.as_mut().unwrap().text.push( OwnedText::new(c.to_string()) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ); } } _ => (), }, WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_, y), .. } => { // increase/decrease font size let mut size = self.font_size; if y > 0.0 { size += (size / 4.0).max(2.0) } else { size *= 4.0 / 5.0 }; self.font_size = (size.clamp(3.0, 25000.0) * 2.0).round() / 2.0; } WindowEvent::RedrawRequested => { let brush = self.brush.as_mut().unwrap(); let ctx = self.ctx.as_ref().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &ctx.config; let surface = &ctx.surface; let section_0 = self.section_0.as_ref().unwrap(); let section_1 = self.section_1.as_ref().unwrap(); match brush.queue(device, queue, [section_0, section_1]) { Ok(_) => (), Err(err) => { panic!("{err}"); } }; let frame = match surface.get_current_texture() { Ok(frame) => frame, Err(_) => { surface.configure(device, config); surface .get_current_texture() .expect("Failed to acquire next surface texture!") } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Command Encoder"), }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.2, g: 0.2, b: 0.3, a: 1., }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, }); brush.draw(&mut rpass); } queue.submit([encoder.finish()]); frame.present(); } _ => (), } } fn new_events(&mut self, _elwt: &ActiveEventLoop, _cause: winit::event::StartCause) { if self.target_framerate <= self.delta_time.elapsed() && let Some(window) = self.window.clone().as_mut() { window.request_redraw(); self.delta_time = Instant::now(); self.fps += 1; if self.fps_update_time.elapsed().as_millis() > 1000 { window.set_title(&format!( "wgpu-text: 'simple' example, FPS: {}", self.fps )); self.fps = 0; self.fps_update_time = Instant::now(); } } } fn exiting(&mut self, _event_loop: &ActiveEventLoop) { println!("Exiting!"); } } // TODO text layout of characters like 'š, ć, ž, đ' doesn't work correctly. fn main() { if std::env::var("RUST_LOG").is_err() { unsafe { std::env::set_var("RUST_LOG", "error"); } } env_logger::init(); let event_loop = event_loop::EventLoop::new().unwrap(); event_loop.set_control_flow(ControlFlow::Poll); let mut state = State { window: None, font: include_bytes!("fonts/DejaVuSans.ttf"), brush: None, font_size: 25., section_0: None, section_1: None, // FPS and window updating: // change '60.0' if you want different FPS cap target_framerate: Duration::from_secs_f64(1.0 / 60.0), delta_time: Instant::now(), fps_update_time: Instant::now(), fps: 0, ctx: None, }; let _ = event_loop.run_app(&mut state); }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/depth.rs
examples/depth.rs
#[path = "ctx.rs"] mod ctx; use ctx::Ctx; use glyph_brush::OwnedSection; use glyph_brush::ab_glyph::FontRef; use std::sync::Arc; use std::time::{Duration, Instant}; use wgpu::{DepthStencilState, TextureView}; use wgpu_text::glyph_brush::{ BuiltInLineBreaker, Layout, OwnedText, Section, Text, VerticalAlign, }; use wgpu_text::{BrushBuilder, TextBrush}; use winit::application::ApplicationHandler; use winit::event::{ElementState, WindowEvent}; use winit::event::{KeyEvent, MouseScrollDelta}; use winit::event_loop::{self, ActiveEventLoop, ControlFlow}; use winit::keyboard::{Key, NamedKey}; use winit::window::Window; const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; struct State<'a> { // Use an `Option` to allow the window to not be available until the // application is properly running. window: Option<Arc<Window>>, font: &'a [u8], brush: Option<TextBrush<FontRef<'a>>>, font_size: f32, section_0: Option<OwnedSection>, section_1: Option<OwnedSection>, target_framerate: Duration, delta_time: Instant, fps_update_time: Instant, fps: i32, // wgpu ctx: Option<Ctx>, depth_stencil: Option<DepthStencilState>, depth_view: Option<TextureView>, } impl ApplicationHandler for State<'_> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { let window = Arc::new( event_loop .create_window( Window::default_attributes().with_title("wgpu-text: 'depth' example"), ) .unwrap(), ); self.ctx = Some(Ctx::new(window.clone())); let ctx = self.ctx.as_ref().unwrap(); let device = &ctx.device; let config = &ctx.config; self.depth_view = Some(create_depth_view(device, config.width, config.height)); self.brush = Some( BrushBuilder::using_font_bytes(self.font) .unwrap() .with_depth_stencil(self.depth_stencil.clone()) .build(device, config.width, config.height, config.format), ); self.section_0 = Some( Section::default() .add_text( Text::new( "Try typing some text,\n \ del - delete all, backspace - remove last character", ) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]) .with_z(0.08), // In range 0.0 - 1.0 bigger number means it's more at the back ) .with_bounds((config.width as f32 / 2.0, config.height as f32)) .with_layout( Layout::default() .v_align(VerticalAlign::Center) .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ) .with_screen_position((50.0, config.height as f32 * 0.5)) .to_owned(), ); self.section_1 = Some( Section::default() .add_text( Text::new("Other section") .with_scale(80.0) .with_color([0.2, 0.5, 0.8, 1.0]) .with_z(0.1), // In range 0.0 - 1.0 bigger number means it's more at the back ) .with_bounds((config.width as f32 / 2.0, config.height as f32)) .with_layout( Layout::default() .v_align(VerticalAlign::Top) .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ) .with_screen_position((50.0, config.height as f32 * 0.5)) .to_owned(), ); self.window = Some(window); } fn window_event( &mut self, elwt: &ActiveEventLoop, _window_id: winit::window::WindowId, event: WindowEvent, ) { match event { WindowEvent::Resized(new_size) => { let ctx = self.ctx.as_mut().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &mut ctx.config; let surface = &ctx.surface; let section_0 = self.section_0.as_mut().unwrap(); let brush = self.brush.as_mut().unwrap(); config.width = new_size.width.max(1); config.height = new_size.height.max(1); surface.configure(device, config); let width = config.width as f32; let height = config.height as f32; section_0.bounds = (width * 0.5, height); section_0.screen_position.1 = height * 0.5; self.depth_view.replace(create_depth_view( device, config.width, config.height, )); brush.resize_view(width, height, queue); // You can also do this! // brush.update_matrix(wgpu_text::ortho(config.width, config.height), &queue); } WindowEvent::CloseRequested => elwt.exit(), WindowEvent::KeyboardInput { event: KeyEvent { logical_key, state: ElementState::Pressed, .. }, .. } => match logical_key { Key::Named(k) => match k { NamedKey::Escape => elwt.exit(), NamedKey::Delete => self.section_0.as_mut().unwrap().text.clear(), NamedKey::Backspace if !self.section_0.clone().unwrap().text.is_empty() => { let section = self.section_0.as_mut().unwrap(); let mut end_text = section.text.remove(section.text.len() - 1); end_text.text.pop(); if !end_text.text.is_empty() { self.section_0.as_mut().unwrap().text.push(end_text.clone()); } } _ => (), }, Key::Character(char) => { let c = char.as_str(); if c != "\u{7f}" && c != "\u{8}" { let section_0 = self.section_0.as_mut().unwrap(); if section_0.text.is_empty() { section_0.text.push( OwnedText::default() .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]) .with_z(0.08), ); } section_0.text.push( OwnedText::new(c.to_string()) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]) .with_z(0.08), ); } } _ => (), }, WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_, y), .. } => { // increase/decrease font size let mut size = self.font_size; if y > 0.0 { size += (size / 4.0).max(2.0) } else { size *= 4.0 / 5.0 }; self.font_size = (size.clamp(3.0, 25000.0) * 2.0).round() / 2.0; } WindowEvent::RedrawRequested => { let brush = self.brush.as_mut().unwrap(); let ctx = self.ctx.as_ref().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &ctx.config; let surface = &ctx.surface; let section_0 = self.section_0.as_ref().unwrap(); let section_1 = self.section_1.as_ref().unwrap(); match brush.queue(device, queue, [section_1, section_0]) { Ok(_) => (), Err(err) => { panic!("{err}"); } }; let frame = match surface.get_current_texture() { Ok(frame) => frame, Err(_) => { surface.configure(device, config); surface .get_current_texture() .expect("Failed to acquire next surface texture!") } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Command Encoder"), }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.2, g: 0.2, b: 0.3, a: 1., }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: Some( wgpu::RenderPassDepthStencilAttachment { view: self.depth_view.as_ref().unwrap(), depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard, }), stencil_ops: None, }, ), timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, }); brush.draw(&mut rpass); } queue.submit([encoder.finish()]); frame.present(); } _ => (), } } fn new_events(&mut self, _elwt: &ActiveEventLoop, _cause: winit::event::StartCause) { if self.target_framerate <= self.delta_time.elapsed() && let Some(window) = self.window.clone().as_mut() { window.request_redraw(); self.delta_time = Instant::now(); self.fps += 1; if self.fps_update_time.elapsed().as_millis() > 1000 { window .set_title(&format!("wgpu-text: 'depth' example, FPS: {}", self.fps)); self.fps = 0; self.fps_update_time = Instant::now(); } } } fn exiting(&mut self, _event_loop: &ActiveEventLoop) { println!("Exiting!"); } } fn main() { if std::env::var("RUST_LOG").is_err() { unsafe { std::env::set_var("RUST_LOG", "error"); } } env_logger::init(); let event_loop = event_loop::EventLoop::new().unwrap(); event_loop.set_control_flow(ControlFlow::Poll); let mut state = State { window: None, font: include_bytes!("fonts/DejaVuSans.ttf"), brush: None, font_size: 45., section_0: None, section_1: None, // FPS and window updating: // change '60.0' if you want different FPS cap target_framerate: Duration::from_secs_f64(1.0 / 60.0), delta_time: Instant::now(), fps_update_time: Instant::now(), fps: 0, ctx: None, depth_stencil: Some(wgpu::DepthStencilState { format: DEPTH_FORMAT, depth_write_enabled: true, depth_compare: wgpu::CompareFunction::LessEqual, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }), depth_view: None, }; let _ = event_loop.run_app(&mut state); } fn create_depth_view( device: &wgpu::Device, width: u32, height: u32, ) -> wgpu::TextureView { let depth_texture = device.create_texture(&wgpu::TextureDescriptor { size: wgpu::Extent3d { width, height, depth_or_array_layers: 1, }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: DEPTH_FORMAT, usage: wgpu::TextureUsages::RENDER_ATTACHMENT, label: Some("Depth Texture"), view_formats: &[], }); depth_texture.create_view(&wgpu::TextureViewDescriptor::default()) }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/ctx.rs
examples/ctx.rs
use std::sync::Arc; use pollster::block_on; use wgpu::{Device, Queue, Surface, SurfaceConfiguration}; // TODO add cache texture preview example // TODO add mip-mapping example // TODO add wasm example pub struct Ctx { pub device: Device, pub queue: Queue, pub surface: Surface<'static>, pub config: SurfaceConfiguration, } impl Ctx { pub fn new(window: Arc<winit::window::Window>) -> Self { let size = window.inner_size(); let backends = wgpu::Backends::from_env().unwrap_or_else(wgpu::Backends::all); let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor { backends, flags: wgpu::InstanceFlags::default(), memory_budget_thresholds: Default::default(), backend_options: wgpu::BackendOptions { gl: wgpu::GlBackendOptions { gles_minor_version: wgpu::Gles3MinorVersion::Automatic, fence_behavior: wgpu::GlFenceBehavior::default(), }, dx12: wgpu::Dx12BackendOptions::default(), noop: wgpu::NoopBackendOptions::from_env_or_default(), }, }); let surface = instance.create_surface(window).unwrap(); let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { compatible_surface: Some(&surface), ..Default::default() })) .expect("No adapters found!"); let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("Device"), required_features: wgpu::Features::empty(), required_limits: wgpu::Limits::default(), memory_hints: wgpu::MemoryHints::default(), trace: wgpu::Trace::Off, experimental_features: wgpu::ExperimentalFeatures::disabled(), })) .unwrap(); let config = surface .get_default_config(&adapter, size.width, size.height) .expect("Surface isn't supported by the adapter."); surface.configure(&device, &config); Self { device, queue, surface, config, } } } #[allow(dead_code)] fn main() {}
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/performance.rs
examples/performance.rs
#[path = "ctx.rs"] mod ctx; use ctx::Ctx; use glyph_brush::ab_glyph::FontRef; use rand::Rng; use std::sync::Arc; use std::time::{Duration, Instant}; use wgpu_text::glyph_brush::{BuiltInLineBreaker, Layout, Section, Text}; use wgpu_text::{BrushBuilder, TextBrush}; use winit::application::ApplicationHandler; use winit::event::{KeyEvent, MouseScrollDelta}; use winit::event_loop::{ActiveEventLoop, ControlFlow}; use winit::keyboard::{Key, NamedKey}; use winit::window::Window; use winit::{ event::{ElementState, WindowEvent}, event_loop::{self}, }; const RANDOM_CHARACTERS: usize = 30_000; fn generate_random_chars() -> String { let mut result = String::new(); let mut rng = rand::rng(); for _ in 0..RANDOM_CHARACTERS { let rand = rng.random_range(0x0041..0x0070); let char = char::from_u32(rand).unwrap(); result.push(char); } result.trim().to_owned() } struct State<'a> { // Use an `Option` to allow the window to not be available until the // application is properly running. window: Option<Arc<Window>>, font: &'a [u8], brush: Option<TextBrush<FontRef<'a>>>, random_text: String, font_size: f32, target_framerate: Duration, delta_time: Instant, fps_update_time: Instant, fps: i32, // wgpu ctx: Option<Ctx>, } impl ApplicationHandler for State<'_> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { let window = Arc::new( event_loop .create_window( Window::default_attributes() .with_title("wgpu-text: 'simple' example"), ) .unwrap(), ); self.ctx = Some(Ctx::new(window.clone())); let ctx = self.ctx.as_ref().unwrap(); let device = &ctx.device; let config = &ctx.config; self.brush = Some(BrushBuilder::using_font_bytes(self.font).unwrap().build( device, config.width, config.height, config.format, )); self.window = Some(window); } fn window_event( &mut self, elwt: &ActiveEventLoop, _window_id: winit::window::WindowId, event: WindowEvent, ) { match event { WindowEvent::Resized(new_size) => { let ctx = self.ctx.as_mut().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &mut ctx.config; let surface = &ctx.surface; let brush = self.brush.as_mut().unwrap(); config.width = new_size.width.max(1); config.height = new_size.height.max(1); surface.configure(device, config); brush.resize_view(config.width as f32, config.height as f32, queue); // You can also do this! // brush.update_matrix(wgpu_text::ortho(config.width, config.height), &queue); } WindowEvent::CloseRequested => elwt.exit(), WindowEvent::KeyboardInput { event: KeyEvent { logical_key, state: ElementState::Pressed, .. }, .. } => match logical_key { Key::Named(k) => match k { NamedKey::Escape => elwt.exit(), NamedKey::Delete => self.random_text.clear(), NamedKey::Backspace => { self.random_text.pop(); } _ => (), }, Key::Character(char) => { self.random_text.push_str(char.as_str()); } _ => (), }, WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_, y), .. } => { // increase/decrease font size let mut size = self.font_size; if y > 0.0 { size += (size / 4.0).max(2.0) } else { size *= 4.0 / 5.0 }; self.font_size = (size.clamp(3.0, 300.0) * 2.0).round() / 2.0; } WindowEvent::RedrawRequested => { let brush = self.brush.as_mut().unwrap(); let ctx = self.ctx.as_ref().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &ctx.config; let surface = &ctx.surface; let section = Section::default() .add_text( Text::new(&self.random_text) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ) .with_bounds((config.width as f32, config.height as f32)) .with_layout( Layout::default() .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ); match brush.queue(device, queue, [section]) { Ok(_) => (), Err(err) => { panic!("{err}"); } }; let frame = match surface.get_current_texture() { Ok(frame) => frame, Err(_) => { surface.configure(device, config); surface .get_current_texture() .expect("Failed to acquire next surface texture!") } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Command Encoder"), }); { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.2, g: 0.2, b: 0.3, a: 1., }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, }); brush.draw(&mut rpass) } queue.submit([encoder.finish()]); frame.present(); } _ => (), } } fn new_events(&mut self, _elwt: &ActiveEventLoop, _cause: winit::event::StartCause) { if self.target_framerate <= self.delta_time.elapsed() && let Some(window) = self.window.clone().as_mut() { window.request_redraw(); self.delta_time = Instant::now(); self.fps += 1; if self.fps_update_time.elapsed().as_millis() > 1000 { window.set_title(&format!( "wgpu-text: 'performance' example, FPS: {}", self.fps )); self.fps = 0; self.fps_update_time = Instant::now(); } } } fn exiting(&mut self, _event_loop: &ActiveEventLoop) { println!("Exiting!"); } } fn main() { if std::env::var("RUST_LOG").is_err() { unsafe { std::env::set_var("RUST_LOG", "error"); } } env_logger::init(); if cfg!(debug_assertions) { eprintln!( "You should probably run an example called 'performance' in release mode.\n\ e.g. use `cargo run --example performance --release`\n" ); } let event_loop = event_loop::EventLoop::new().unwrap(); event_loop.set_control_flow(ControlFlow::Poll); let mut state = State { window: None, font: include_bytes!("fonts/DejaVuSans.ttf"), brush: None, random_text: generate_random_chars(), font_size: 9., // FPS and window updating: // change '60.0' if you want different FPS cap target_framerate: Duration::from_secs_f64(1.0 / 60.0), delta_time: Instant::now(), fps_update_time: Instant::now(), fps: 0, ctx: None, }; let _ = event_loop.run_app(&mut state); }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/custom_target/custom_target.rs
examples/custom_target/custom_target.rs
mod camera; #[path = "../ctx.rs"] mod ctx; mod pipeline; use camera::Camera; use ctx::Ctx; use glyph_brush::ab_glyph::FontRef; use glyph_brush::{OwnedSection, OwnedText, VerticalAlign}; use pipeline::{Vertex, create_pipeline}; use std::sync::Arc; use std::time::{Duration, Instant}; use wgpu::util::DeviceExt; use wgpu::{BindGroup, Buffer, RenderPipeline, TextureView}; use wgpu_text::glyph_brush::{BuiltInLineBreaker, Layout, Section, Text}; use wgpu_text::{BrushBuilder, TextBrush}; use winit::application::ApplicationHandler; use winit::event::{ElementState, WindowEvent}; use winit::event::{KeyEvent, MouseScrollDelta, StartCause}; use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop}; use winit::keyboard::{Key, NamedKey}; use winit::window::{Window, WindowId}; // TODO test with custom .png texture const VERTICES: &[Vertex] = &[ Vertex { position: [-0.5, -0.5, 0.0], tex_pos: [0.0, 1.0], }, Vertex { position: [0.5, -0.5, 0.0], tex_pos: [1.0, 1.0], }, Vertex { position: [0.5, 0.5, 0.0], tex_pos: [1.0, 0.0], }, Vertex { position: [0.5, 0.5, 0.0], tex_pos: [1.0, 0.0], }, Vertex { position: [-0.5, 0.5, 0.0], tex_pos: [0.0, 0.0], }, Vertex { position: [-0.5, -0.5, 0.0], tex_pos: [0.0, 1.0], }, ]; struct State<'a> { // Use an `Option` to allow the window to not be available until the // application is properly running. window: Option<Arc<Window>>, font: &'a [u8], brush: Option<TextBrush<FontRef<'a>>>, font_size: f32, section: Option<OwnedSection>, camera: Option<Camera>, matrix_buffer: Option<Buffer>, texture_view: Option<TextureView>, pipeline: Option<RenderPipeline>, bind_group: Option<BindGroup>, vertex_buffer: Option<Buffer>, target_framerate: Duration, delta_time: Instant, fps_update_time: Instant, fps: i32, // wgpu ctx: Option<Ctx>, } impl ApplicationHandler for State<'_> { fn resumed(&mut self, event_loop: &ActiveEventLoop) { let window = Arc::new( event_loop .create_window( Window::default_attributes() .with_title("wgpu-text: 'simple' example"), ) .unwrap(), ); self.ctx = Some(Ctx::new(window.clone())); let ctx = self.ctx.as_ref().unwrap(); let device = &ctx.device; let config = &ctx.config; self.brush = Some(BrushBuilder::using_font_bytes(self.font).unwrap().build( device, config.width, config.height, config.format, )); self.camera = Some(Camera::new(config)); let size = wgpu::Extent3d { width: 256 * 4, height: 256 * 4, depth_or_array_layers: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some("Custom Surface Texture"), size, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Bgra8UnormSrgb, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }); let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_w: wgpu::AddressMode::ClampToEdge, mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); self.texture_view = Some(texture.create_view(&Default::default())); self.vertex_buffer = Some(device.create_buffer_init( &wgpu::util::BufferInitDescriptor { label: Some("Custom Surface Vertex Buffer"), contents: bytemuck::cast_slice(VERTICES), usage: wgpu::BufferUsages::VERTEX, }, )); self.matrix_buffer = Some(device.create_buffer_init( &wgpu::util::BufferInitDescriptor { label: Some("Custom Surface Global Matrix Buffer"), contents: bytemuck::cast_slice( self.camera.as_ref().unwrap().global_matrix.as_slice(), ), usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, }, )); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Custom Surface Bind Group Layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true, }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStages::FRAGMENT, ty: wgpu::BindingType::Sampler( wgpu::SamplerBindingType::Filtering, ), count: None, }, ], }); self.bind_group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("Custom Surface Bind Group"), layout: &bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: self.matrix_buffer.as_ref().unwrap().as_entire_binding(), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView( self.texture_view.as_ref().unwrap(), ), }, wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&sampler), }, ], })); self.pipeline = Some(create_pipeline(device, &[&bind_group_layout], config)); self.section = Some( Section::default() .add_text( Text::new( "Try typing some text,\n \ del - delete all, backspace - remove last character", ) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ) .with_bounds((config.width as f32 / 2.0, config.height as f32)) .with_layout( Layout::default() .v_align(VerticalAlign::Center) .line_breaker(BuiltInLineBreaker::AnyCharLineBreaker), ) .with_screen_position((50.0, config.height as f32 * 0.5)) .to_owned(), ); self.window = Some(window); } fn window_event( &mut self, event_loop: &ActiveEventLoop, _window_id: WindowId, event: WindowEvent, ) { match event { WindowEvent::Resized(new_size) => { let ctx = self.ctx.as_mut().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &mut ctx.config; let surface = &ctx.surface; let brush = self.brush.as_mut().unwrap(); config.width = new_size.width.max(1); config.height = new_size.height.max(1); surface.configure(device, config); self.camera.as_mut().unwrap().resize(config); brush.resize_view(config.width as f32, config.height as f32, queue); // You can also do this! // brush.update_matrix(wgpu_text::ortho(config.width, config.height), &queue); } WindowEvent::CloseRequested => event_loop.exit(), WindowEvent::KeyboardInput { event: KeyEvent { logical_key, state: ElementState::Pressed, .. }, .. } => match logical_key { Key::Named(k) => match k { NamedKey::Escape => event_loop.exit(), NamedKey::Delete => self.section.as_mut().unwrap().text.clear(), NamedKey::Backspace if !self.section.clone().unwrap().text.is_empty() => { let section = self.section.as_mut().unwrap(); let mut end_text = section.text.remove(section.text.len() - 1); end_text.text.pop(); if !end_text.text.is_empty() { self.section.as_mut().unwrap().text.push(end_text.clone()); } } _ => (), }, Key::Character(char) => { let c = char.as_str(); if c != "\u{7f}" && c != "\u{8}" { if self.section.clone().unwrap().text.is_empty() { self.section.as_mut().unwrap().text.push( OwnedText::default() .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ); } self.section.as_mut().unwrap().text.push( OwnedText::new(c.to_string()) .with_scale(self.font_size) .with_color([0.9, 0.5, 0.5, 1.0]), ); } } _ => (), }, WindowEvent::MouseWheel { delta: MouseScrollDelta::LineDelta(_, y), .. } => { // increase/decrease font size let mut size = self.font_size; if y > 0.0 { size += (size / 4.0).max(2.0) } else { size *= 4.0 / 5.0 }; self.font_size = (size.max(3.0).min(25000.0) * 2.0).round() / 2.0; } WindowEvent::RedrawRequested => { let brush = self.brush.as_mut().unwrap(); let ctx = self.ctx.as_ref().unwrap(); let queue = &ctx.queue; let device = &ctx.device; let config = &ctx.config; let surface = &ctx.surface; let section = self.section.as_ref().unwrap(); let camera = self.camera.as_mut().unwrap(); camera.update(); queue.write_buffer( self.matrix_buffer.as_ref().unwrap(), 0, bytemuck::cast_slice(camera.global_matrix.as_slice()), ); match brush.queue(device, queue, [section]) { Ok(_) => (), Err(err) => { panic!("{err}"); } }; let frame = match surface.get_current_texture() { Ok(frame) => frame, Err(_) => { surface.configure(device, config); surface .get_current_texture() .expect("Failed to acquire next surface texture!") } }; let view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Custom Surface Command Encoder"), }); // Custom output render pass. Renders to custom texture. { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Custom Surface Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: self.texture_view.as_ref().unwrap(), depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, }); brush.draw(&mut rpass); } // Default render pass: { let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Custom Surface Render Pass"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { view: &view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.2, g: 0.2, b: 0.3, a: 1., }), store: wgpu::StoreOp::Store, }, })], depth_stencil_attachment: None, timestamp_writes: None, occlusion_query_set: None, multiview_mask: None, }); rpass.set_pipeline(self.pipeline.as_ref().unwrap()); rpass.set_bind_group(0, self.bind_group.as_ref().unwrap(), &[]); rpass.set_vertex_buffer( 0, self.vertex_buffer.as_ref().unwrap().slice(..), ); rpass.draw(0..6, 0..1); } queue.submit([encoder.finish()]); frame.present(); } _ => (), } } fn new_events(&mut self, _event_loop: &ActiveEventLoop, _cause: StartCause) { if self.target_framerate <= self.delta_time.elapsed() { self.window.clone().unwrap().request_redraw(); self.delta_time = Instant::now(); self.fps += 1; if self.fps_update_time.elapsed().as_millis() > 1000 { let window = self.window.as_mut().unwrap(); window.set_title(&format!( "wgpu-text: 'custom_target' example, FPS: {}", self.fps )); self.fps = 0; self.fps_update_time = Instant::now(); } } } fn user_event(&mut self, event_loop: &ActiveEventLoop, event: ()) { let _ = (event_loop, event); } fn exiting(&mut self, _event_loop: &ActiveEventLoop) { println!("Exiting!"); } } fn main() { if std::env::var("RUST_LOG").is_err() { unsafe { std::env::set_var("RUST_LOG", "error"); } } env_logger::init(); let event_loop = EventLoop::new().unwrap(); event_loop.set_control_flow(ControlFlow::Poll); let mut state = State { window: None, font: include_bytes!("../fonts/DejaVuSans.ttf"), brush: None, font_size: 25., section: None, camera: None, matrix_buffer: None, texture_view: None, pipeline: None, bind_group: None, vertex_buffer: None, // FPS and window updating: // change '60.0' if you want different FPS cap target_framerate: Duration::from_secs_f64(1.0 / 60.0), delta_time: Instant::now(), fps_update_time: Instant::now(), fps: 0, ctx: None, }; let _ = event_loop.run_app(&mut state); }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/custom_target/pipeline.rs
examples/custom_target/pipeline.rs
#[repr(C)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { pub position: [f32; 3], pub tex_pos: [f32; 2], } impl Vertex { pub fn buffer_layout<'a>() -> wgpu::VertexBufferLayout<'a> { wgpu::VertexBufferLayout { array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress, step_mode: wgpu::VertexStepMode::Vertex, attributes: &[ wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0, }, wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress, shader_location: 1, }, ], } } } pub fn create_pipeline( device: &wgpu::Device, bind_group_layouts: &[&wgpu::BindGroupLayout], config: &wgpu::SurfaceConfiguration, ) -> wgpu::RenderPipeline { let vertex_module = device.create_shader_module(wgpu::include_wgsl!("shaders/vertex.vert.wgsl")); let fragment_module = device.create_shader_module(wgpu::include_wgsl!("shaders/fragment.frag.wgsl")); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Custom Surface Render Pipeline Layout"), bind_group_layouts, immediate_size: 0, }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Custom Surface Render Pipeline"), layout: Some(&layout), vertex: wgpu::VertexState { module: &vertex_module, entry_point: Some("main"), buffers: &[Vertex::buffer_layout()], compilation_options: Default::default(), }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, front_face: wgpu::FrontFace::Ccw, cull_mode: Some(wgpu::Face::Back), polygon_mode: wgpu::PolygonMode::Fill, ..Default::default() }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, fragment: Some(wgpu::FragmentState { module: &fragment_module, entry_point: Some("main"), targets: &[Some(wgpu::ColorTargetState { format: config.format, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })], compilation_options: Default::default(), }), multiview_mask: None, cache: None, }); pipeline }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
Blatko1/wgpu-text
https://github.com/Blatko1/wgpu-text/blob/0a411831589eeda112f63c0d59a74b6f08b68d75/examples/custom_target/camera.rs
examples/custom_target/camera.rs
use nalgebra::{Matrix4, Point3, Vector3}; pub struct Camera { pub eye: Point3<f32>, pub target: Point3<f32>, up: Vector3<f32>, pub aspect: f32, pub fov: f32, near: f32, far: f32, pub controller: CameraController, pub global_matrix: Matrix4<f32>, } #[rustfmt::skip] const OPENGL_TO_WGPU_MATRIX: Matrix4<f32> = Matrix4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 1.0, ); impl Camera { pub fn new(config: &wgpu::SurfaceConfiguration) -> Self { let controller = CameraController::new(); Self { eye: Point3::new(0., 0., 1.), target: Point3::new(0., 0., -1.), up: Vector3::y(), aspect: config.width as f32 / config.height as f32, fov: 60., near: 0.01, far: 100.0, controller, global_matrix: OPENGL_TO_WGPU_MATRIX, } } fn update_global_matrix(&mut self) { let target = Point3::new( self.eye.x + self.target.x, self.eye.y + self.target.y, self.eye.z + self.target.z, ); let projection = Matrix4::new_perspective( self.aspect, self.fov.to_degrees(), self.near, self.far, ); let view = Matrix4::look_at_rh(&self.eye, &target, &self.up); self.global_matrix = OPENGL_TO_WGPU_MATRIX * projection * view; } pub fn resize(&mut self, config: &wgpu::SurfaceConfiguration) { self.aspect = config.width as f32 / config.height as f32; } pub fn update(&mut self) { self.controller.update(); self.fov += self.controller.fov_delta; self.controller.fov_delta = 0.; self.target = Point3::new( self.controller.yaw.to_radians().cos() * self.controller.pitch.to_radians().cos(), self.controller.pitch.to_radians().sin(), self.controller.yaw.to_radians().sin() * self.controller.pitch.to_radians().cos(), ); let target = Vector3::new(self.target.x, 0.0, self.target.z).normalize(); self.eye += target * self.controller.speed * (self.controller.forward - self.controller.backward); self.eye += target.cross(&self.up) * self.controller.speed * (self.controller.right - self.controller.left); self.eye += Vector3::new(0.0, 1.0, 0.0) * self.controller.speed * (self.controller.up - self.controller.down); self.update_global_matrix(); } pub fn _input(&mut self, event: &winit::event::DeviceEvent) { self.controller._process_input(event); } } pub struct CameraController { speed: f32, _sensitivity: f64, forward: f32, backward: f32, left: f32, right: f32, up: f32, down: f32, pub yaw: f32, pub pitch: f32, fov_delta: f32, time: std::time::Instant, } impl CameraController { pub fn new() -> Self { CameraController { speed: 0.4, _sensitivity: 0.1, forward: 0., backward: 0., left: 0., right: 0., up: 0., down: 0., yaw: 0., pitch: 0.0, fov_delta: 0., time: std::time::Instant::now(), } } pub fn update(&mut self) { let time = self.time.elapsed().as_millis() as f64 * 0.01; self.yaw = 270.0 + 20.0 * time.to_radians().sin() as f32; } pub fn _process_input(&mut self, _event: &winit::event::DeviceEvent) { /*match event { DeviceEvent::MouseMotion { delta } => { self.yaw += (delta.0 * self.sensitivity) as f32; self.pitch -= (delta.1 * self.sensitivity) as f32; if self.pitch > 89.0 { self.pitch = 89.0; } else if self.pitch < -89.0 { self.pitch = -89.0; } if self.yaw > 360.0 { self.yaw = 0.0; } else if self.yaw < 0.0 { self.yaw = 360.0; } } DeviceEvent::Motion { .. } => {} DeviceEvent::Button { .. } => {} DeviceEvent::Key(KeyboardInput { state, virtual_keycode, .. }) => { let value: f32; if *state == winit::event::ElementState::Pressed { value = 1. } else { value = 0.; } match virtual_keycode.unwrap() { VirtualKeyCode::Space => { self.up = value; } VirtualKeyCode::LShift => { self.down = value; } VirtualKeyCode::W => { self.forward = value; } VirtualKeyCode::S => { self.backward = value; } VirtualKeyCode::A => { self.left = value; } VirtualKeyCode::D => { self.right = value; } _ => (), } } _ => (), }*/ } }
rust
MIT
0a411831589eeda112f63c0d59a74b6f08b68d75
2026-01-04T20:25:30.143858Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/lib.rs
oxeylyzer-repl/src/lib.rs
pub mod corpus_transposition; pub mod flags; pub mod repl; pub mod tui; #[test] fn thing() { let x = std::path::PathBuf::from("this/is/a/path"); println!("{}", x.display()) } // fn main() { // use languages::*; // let x = CorpusConfig::new("english", None); // } // use oxeylyzer_core::load_text; // fn pause() -> Result<(), std::io::Error> { // println!("\nPress any key to continue..."); // let mut _s = String::new(); // std::io::stdin().read_line(&mut _s)?; // Ok(()) // } // fn main() -> Result<(), std::io::Error> { // load_text::load_all_default().expect("sussy impostor lol sus"); // pause() // }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/repl.rs
oxeylyzer-repl/src/repl.rs
use std::io::Write; use std::path::Path; use indexmap::IndexMap; use itertools::Itertools; use oxeylyzer_core::{generate::LayoutGeneration, layout::*, load_text, rayon, weights::Config}; use crate::corpus_transposition::CorpusConfig; use crate::tui::*; pub struct Repl { language: String, gen: LayoutGeneration, saved: IndexMap<String, FastLayout>, temp_generated: Vec<FastLayout>, pins: Vec<usize>, thread_pool: rayon::ThreadPool, } impl Repl { pub fn new<P>(generator_base_path: P) -> Result<Self, String> where P: AsRef<Path>, { let config = Config::with_loaded_weights(); let language = config.defaults.language.clone(); let pins = config.pins.clone(); let thread_pool = rayon::ThreadPoolBuilder::new() .num_threads(config.defaults.max_cores) .build() .unwrap(); let mut gen = LayoutGeneration::new( config.defaults.language.clone().as_str(), generator_base_path.as_ref(), Some(config), ) .unwrap_or_else(|_| panic!("Could not read language data for {}", language)); Ok(Self { saved: gen .load_layouts( generator_base_path.as_ref().join("layouts"), language.as_str(), ) .map_err(|e| e.to_string())?, language, gen, temp_generated: Vec::new(), pins, thread_pool, }) } pub fn run() -> Result<(), String> { let mut env = Self::new("static")?; loop { let line = readline().map_err(|e| e.to_string())?; let line = line.trim(); if line.is_empty() { continue; } match env.respond(line) { Ok(true) => break, Ok(false) => continue, Err(err) => { println!("{err}"); } } } Ok(()) } pub fn rank(&self) { for (name, layout) in self.saved.iter() { println!("{:10}{}", format!("{:.3}:", layout.score), name); } } pub fn layout_by_name(&self, name: &str) -> Option<&FastLayout> { self.saved.get(name) } pub fn analyze_name(&self, name: &str) { let l = match self.layout_by_name(name) { Some(layout) => layout, None => { println!("layout {} does not exist!", name); return; } }; println!("{}", name); self.analyze(l); } fn placeholder_name(&self, layout: &FastLayout) -> Result<String, String> { for i in 1..1000usize { let new_name_bytes = layout .matrix .into_iter() .skip(10) .take(4) .collect::<Vec<_>>(); let mut new_name = self .gen .data .convert_u8 .as_str(new_name_bytes.as_slice()) .replace('*', ""); new_name.push_str(format!("{}", i).as_str()); if !self.saved.contains_key(&new_name) { return Ok(new_name); } } Err("Could not find a good placeholder name for the layout.".to_string()) } pub fn save(&mut self, mut layout: FastLayout, name: Option<String>) -> Result<(), String> { let new_name = if let Some(n) = name { n.replace(' ', "_") } else { self.placeholder_name(&layout).unwrap() }; let mut f = std::fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .open(format!("static/layouts/{}/{}.kb", self.language, new_name)) .map_err(|e| e.to_string())?; let layout_formatted = layout.formatted_string(&self.gen.data.convert_u8); println!("saved {}\n{}", new_name, layout_formatted); f.write_all(layout_formatted.as_bytes()).unwrap(); layout.score = self.gen.score(&layout); self.saved.insert(new_name, layout); self.saved .sort_by(|_, a, _, b| a.score.partial_cmp(&b.score).unwrap()); Ok(()) } pub fn analyze(&self, layout: &FastLayout) { let stats = self.gen.get_layout_stats(layout); let score = if layout.score == 0.000 { self.gen.score(layout) } else { layout.score }; let layout_str = heatmap_string(&self.gen.data, layout); println!("{}\n{}\nScore: {:.3}", layout_str, stats, score); } pub fn compare_name(&self, name1: &str, name2: &str) { let l1 = match self.layout_by_name(name1) { Some(layout) => layout, None => { println!("layout {} does not exist!", name1); return; } }; let l2 = match self.layout_by_name(name2) { Some(layout) => layout, None => { println!("layout {} does not exist!", name2); return; } }; println!("\n{:31}{}", name1, name2); for y in 0..3 { for (n, layout) in [l1, l2].into_iter().enumerate() { for x in 0..10 { print!("{} ", heatmap_heat(&self.gen.data, layout.c(x + 10 * y))); if x == 4 { print!(" "); } } if n == 0 { print!(" "); } } println!(); } let s1 = self.gen.get_layout_stats(l1); let s2 = self.gen.get_layout_stats(l2); let ts1 = s1.trigram_stats; let ts2 = s2.trigram_stats; println!( concat!( "Sfb: {: <11} Sfb: {:.3}%\n", "Dsfb: {: <11} Dsfb: {:.3}%\n", "Finger Speed: {: <11} Finger Speed: {:.3}\n", "Scissors: {: <11} Scissors: {:.3}%\n", "Lsbs: {: <11} Lsbs: {:.3}%\n", "Pinky Ring Bigrams: {: <11} Pinky Ring Bigrams: {:.3}%\n\n", "Inrolls: {: <11} Inrolls: {:.2}%\n", "Outrolls: {: <11} Outrolls: {:.2}%\n", "Total Rolls: {: <11} Total Rolls: {:.2}%\n", "Onehands: {: <11} Onehands: {:.3}%\n\n", "Alternates: {: <11} Alternates: {:.2}%\n", "Alternates Sfs: {: <11} Alternates Sfs: {:.2}%\n", "Total Alternates: {: <11} Total Alternates: {:.2}%\n\n", "Redirects: {: <11} Redirects: {:.3}%\n", "Redirects Sfs: {: <11} Redirects Sfs: {:.3}%\n", "Bad Redirects: {: <11} Bad Redirects: {:.3}%\n", "Bad Redirects Sfs: {: <11} Bad Redirects Sfs: {:.3}%\n", "Total Redirects: {: <11} Total Redirects: {:.3}%\n\n", "Bad Sfbs: {: <11} Bad Sfbs: {:.3}%\n", "Sft: {: <11} Sft: {:.3}%\n\n", "Score: {: <11} Score: {:.3}\n" ), format!("{:.3}%", s1.sfb * 100.0), s2.sfb * 100.0, format!("{:.3}%", s1.dsfb * 100.0), s2.dsfb * 100.0, format!("{:.3}", s1.fspeed * 10.0), s2.fspeed * 10.0, format!("{:.3}%", s1.scissors * 100.0), s2.scissors * 100.0, format!("{:.3}%", s1.lsbs * 100.0), s2.lsbs * 100.0, format!("{:.3}%", s1.pinky_ring * 100.0), s2.pinky_ring * 100.0, format!("{:.2}%", ts1.inrolls * 100.0), ts2.inrolls * 100.0, format!("{:.2}%", ts1.outrolls * 100.0), ts2.outrolls * 100.0, format!("{:.2}%", (ts1.inrolls + ts1.outrolls) * 100.0), (ts2.inrolls + ts2.outrolls) * 100.0, format!("{:.3}%", ts1.onehands * 100.0), ts2.onehands * 100.0, format!("{:.2}%", ts1.alternates * 100.0), ts2.alternates * 100.0, format!("{:.2}%", ts1.alternates_sfs * 100.0), ts2.alternates_sfs * 100.0, format!("{:.2}%", (ts1.alternates + ts1.alternates_sfs) * 100.0), (ts2.alternates + ts2.alternates_sfs) * 100.0, format!("{:.3}%", ts1.redirects * 100.0), ts2.redirects * 100.0, format!("{:.3}%", ts1.redirects_sfs * 100.0), ts2.redirects_sfs * 100.0, format!("{:.3}%", ts1.bad_redirects * 100.0), ts2.bad_redirects * 100.0, format!("{:.3}%", ts1.bad_redirects_sfs * 100.0), ts2.bad_redirects_sfs * 100.0, format!( "{:.3}%", (ts1.redirects + ts1.redirects_sfs + ts1.bad_redirects + ts1.bad_redirects_sfs) * 100.0 ), (ts2.redirects + ts2.redirects_sfs + ts2.bad_redirects + ts2.bad_redirects_sfs) * 100.0, format!("{:.3}%", ts1.bad_sfbs * 100.0), ts2.bad_sfbs * 100.0, format!("{:.3}%", ts1.sfts * 100.0), ts2.sfts * 100.0, format!("{:.3}", l1.score), l2.score ); } fn get_nth(&self, nr: usize) -> Option<&FastLayout> { self.temp_generated.get(nr) } pub fn sfr_freq(&self) -> f64 { let len = self.gen.data.characters.len(); let chars = 0..len; chars .clone() .cartesian_product(chars) .filter(|(i1, i2)| i1 == i2) .map(|(c1, c2)| self.gen.data.bigrams.get(c1 * len + c2).unwrap_or(&0.0)) .sum() } fn sfbs(&self, name: &str, top_n: usize) { if let Some(layout) = self.layout_by_name(name) { println!("top {} sfbs for {name}:", top_n.min(48)); for (bigram, freq) in self.gen.sfbs(layout, top_n) { println!("{bigram}: {:.3}%", freq * 100.0) } } else { println!("layout {name} does not exist!") } } fn respond(&mut self, line: &str) -> Result<bool, String> { use crate::flags::{Repl, ReplCmd::*}; let args = shlex::split(line) .ok_or("Invalid quotations")? .into_iter() .map(std::ffi::OsString::from) .collect::<Vec<_>>(); let flags = Repl::from_vec(args).map_err(|e| e.to_string())?; match flags.subcommand { Analyze(a) => match a.name_or_nr.parse::<usize>() { Ok(nr) => match self.get_nth(nr) { Some(layout) => self.analyze(layout), None => { return Err(format!( "Index '{}' provided is out of bounds for {} generated layouts", a.name_or_nr, self.temp_generated.len() )) } }, Err(_) => self.analyze_name(&a.name_or_nr), }, Compare(c) => self.compare_name(&c.name1, &c.name2), Rank(_) => self.rank(), Generate(g) => { println!("generating {} layouts...", g.count); self.thread_pool.install(|| { self.temp_generated = generate_n(&self.gen, g.count); }); } Improve(i) => match self.layout_by_name(&i.name).cloned() { Some(l) => self.thread_pool.install(|| { self.temp_generated = generate_n_with_pins(&self.gen, i.count, l, &self.pins) }), None => return Err(format!("'{}' does not exist!", i.name)), }, Save(s) => match (self.get_nth(s.n), s.name) { (Some(layout), name) => self.save(layout.clone(), name)?, (None, _) => { return Err(format!( "Index '{}' provided is out of bounds for {} generated layouts", s.n, self.temp_generated.len() )) } }, Sfbs(s) => match s.count { Some(count) => self.sfbs(&s.name, count), None => self.sfbs(&s.name, 10), }, Language(l) => match l.language { Some(l) => { let config = Config::with_loaded_weights(); let language = l .to_str() .ok_or_else(|| format!("Language is invalid utf8: {:?}", l))?; println!("{language:?}"); if let Ok(generator) = LayoutGeneration::new(language, "static", Some(config)) { self.gen = generator; self.saved = self .gen .load_layouts("static/layouts", language) .expect("couldn't load layouts lol"); self.language = language.to_string(); println!( "Set language to {}. Sfr: {:.2}%", &language, self.sfr_freq() * 100.0 ); } else { return Err(format!("Could not load data for {}", language)); } } None => println!("Current language: {}", self.language), }, Include(l) => { self.gen .load_layouts("static/layouts", &l.language) .map_err(|e| e.to_string())? .into_iter() .for_each(|(name, layout)| { self.saved.insert(name, layout); }); self.saved .sort_by(|_, a, _, b| a.score.partial_cmp(&b.score).unwrap()); } Languages(_) => { std::fs::read_dir("static/language_data") .map_err(|e| e.to_string())? .flatten() .for_each(|p| { let name = p .file_name() .to_string_lossy() .replace('_', " ") .replace(".json", ""); if name != "test" { println!("{}", name); } }); } Load(l) => match (l.all, l.raw) { (true, true) => { return Err("You can't currently generate all corpora as raw".into()) } (true, _) => { for (language, config) in CorpusConfig::all() { println!("loading data for language: {language}..."); load_text::load_data(language.as_str(), config.translator()) .map_err(|e| e.to_string())?; } } (false, true) => { println!("loading raw data for language: {}...", l.language.display()); load_text::load_raw(&l.language.display().to_string()); } (false, false) => { let language = l .language .to_str() .ok_or_else(|| format!("Language is invalid utf8: {:?}", l.language))?; let translator = CorpusConfig::new_translator(language, None); let is_raw_translator = translator.is_raw; println!("loading data for {}...", &language); load_text::load_data(language, translator).map_err(|e| e.to_string())?; if !is_raw_translator { let config = Config::with_loaded_weights(); match LayoutGeneration::new(language, "static", Some(config)) { Ok(generator) => { self.language = language.into(); self.gen = generator; self.saved = self .gen .load_layouts("static/layouts", language) .map_err(|e| e.to_string())?; println!( "Set language to {}. Sfr: {:.2}%", language, self.sfr_freq() * 100.0 ); } Err(e) => return Err(e.to_string()), } } } }, Ngram(n) => println!("{}", get_ngram_info(&mut self.gen.data, &n.ngram)), Reload(_) => { let config = Config::with_loaded_weights(); self.pins.clone_from(&config.pins); match LayoutGeneration::new(&self.language, "static", Some(config)) { Ok(generator) => { self.gen = generator; self.saved = self .gen .load_layouts("static/layouts", &self.language) .map_err(|e| e.to_string())?; } Err(e) => return Err(e.to_string()), } } Quit(_) => { println!("Exiting analyzer..."); return Ok(true); } }; Ok(false) } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/flags.rs
oxeylyzer-repl/src/flags.rs
use std::path::PathBuf; xflags::xflags! { cmd repl { /// Analyze a layout. You can also specify a number to analyze a previously generated layout. cmd analyze a view layout { required name_or_nr: String } /// Compare two layouts cmd compare c comp cmp { required name1: String required name2: String } /// Rank all layouts for the currently specified language. A higher score is better. cmd rank {} /// Generate a number of layouts and displays the best 10. Note: layouts may not be correct after changing language. cmd generate gen g { required count: usize } /// Improves the the given layout by pinning keys specified in the `config.toml` and reordering everything else. cmd improve i optimize { required name: String required count: usize } /// Saves the nth layout that was generated. Optionally, you can provide a name as `-n <name>`. cmd save s { required n: usize optional name: String } /// Shows the top n sfbs on a layout. 10 by default. cmd sfbs { required name: String optional -c, --count count: usize } /// Set a language to be used for analysis. Tries to load corpus when not present. cmd language l lang { optional language: PathBuf } /// Include layouts stored under a different language cmd include { required language: String } /// Lists all currently available languages. cmd languages langs {} /// Loads a corpus for a certain language. cmd load { required language: PathBuf optional -a, --all optional -r, --raw } /// Gives information about a certain ngram. for 2 letter ones, skipgram info will be provided as well. cmd ngram n occ freq { required ngram: String } /// Refreshes the config, default characters for the analyzer. Will retain previously generated layouts. cmd reload r {} /// Quits the analyzer. cmd quit q exit {} } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/tui.rs
oxeylyzer-repl/src/tui.rs
use std::io::Write; use oxeylyzer_core::generate::LayoutGeneration; use oxeylyzer_core::language_data::LanguageData; use oxeylyzer_core::layout::*; use oxeylyzer_core::rayon::iter::ParallelIterator; use ansi_rgb::{rgb, Colorable}; use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle}; pub fn readline() -> std::io::Result<String> { write!(std::io::stdout(), "> ")?; std::io::stdout().flush()?; let mut buf = String::new(); std::io::stdin().read_line(&mut buf)?; Ok(buf) } pub fn heatmap_heat(data: &LanguageData, c: u8) -> String { let complement = 215.0 - *data.characters.get(c as usize).unwrap_or(&0.0) * 1720.0; let complement = complement.max(0.0) as u8; let heat = rgb(215, complement, complement); let c = data.convert_u8.from_single(c); format!("{}", c.to_string().fg(heat)) } pub fn heatmap_string(data: &LanguageData, layout: &FastLayout) -> String { let mut print_str = String::new(); for (i, c) in layout.matrix.iter().enumerate() { if i % 10 == 0 && i > 0 { print_str.push('\n'); } if (i + 5) % 10 == 0 { print_str.push(' '); } print_str.push_str(heatmap_heat(data, *c).as_str()); print_str.push(' '); } print_str } pub fn generate_n_with_pins( gen: &LayoutGeneration, amount: usize, based_on: FastLayout, pins: &[usize], ) -> Vec<FastLayout> { if amount == 0 { return Vec::new(); } let start = std::time::Instant::now(); let pb = ProgressBar::new(amount as u64); pb.set_style(ProgressStyle::default_bar() .template("[{elapsed_precise}] [{wide_bar:.white/white}] [eta: {eta:>3}] - {per_sec:>11} {pos:>6}/{len}") .expect("Couldn't initialize the progress bar template") .progress_chars("=>-")); let mut layouts = gen .generate_n_with_pins_iter(amount, based_on, pins) .progress_with(pb) .collect::<Vec<_>>(); println!( "Optimizing {} variants took: {} seconds", amount, start.elapsed().as_secs() ); layouts.sort_by(|l1, l2| l2.score.partial_cmp(&l1.score).unwrap()); for (i, layout) in layouts.iter().enumerate().take(10) { let printable = heatmap_string(&gen.data, layout); println!("#{}, score: {:.5}\n{}", i, layout.score, printable); } layouts } pub fn generate_n(gen: &LayoutGeneration, amount: usize) -> Vec<FastLayout> { if amount == 0 { return Vec::new(); } let start = std::time::Instant::now(); let pb = ProgressBar::new(amount as u64); pb.set_style(ProgressStyle::default_bar() .template("[{elapsed_precise}] [{wide_bar:.white/white}] [eta: {eta:>3}] - {per_sec:>11} {pos:>6}/{len}") .expect("couldn't initialize the progress bar template") .progress_chars("=>-")); let mut layouts = gen .generate_n_iter(amount) .progress_with(pb) .collect::<Vec<_>>(); println!( "optimizing {} variants took: {} seconds", amount, start.elapsed().as_secs() ); layouts.sort_by(|l1, l2| l2.score.partial_cmp(&l1.score).unwrap()); for (i, layout) in layouts.iter().enumerate().take(10) { let printable = heatmap_string(&gen.data, layout); println!("#{}, score: {:.5}\n{}", i, layout.score, printable); } layouts } pub fn get_ngram_info(data: &mut LanguageData, ngram: &str) -> String { match ngram.chars().count() { 1 => { let c = ngram.chars().next().unwrap(); let u = data.convert_u8.to_single(c); let occ = data.characters.get(u as usize).unwrap_or(&0.0) * 100.0; format!("{ngram}: {occ:.3}%") } 2 => { let bigram: [char; 2] = ngram.chars().collect::<Vec<char>>().try_into().unwrap(); let c1 = data.convert_u8.to_single(bigram[0]) as usize; let c2 = data.convert_u8.to_single(bigram[1]) as usize; let b1 = c1 * data.characters.len() + c2; let b2 = c2 * data.characters.len() + c1; let rev = bigram.into_iter().rev().collect::<String>(); let occ_b1 = data.bigrams.get(b1).unwrap_or(&0.0) * 100.0; let occ_b2 = data.bigrams.get(b2).unwrap_or(&0.0) * 100.0; let occ_s = data.skipgrams.get(b1).unwrap_or(&0.0) * 100.0; let occ_s2 = data.skipgrams.get(b2).unwrap_or(&0.0) * 100.0; format!( "{ngram} + {rev}: {:.3}%,\n {ngram}: {occ_b1:.3}%\n {rev}: {occ_b2:.3}%\n\ {ngram} + {rev} (skipgram): {:.3}%,\n {ngram}: {occ_s:.3}%\n {rev}: {occ_s2:.3}%", occ_b1 + occ_b2, occ_s + occ_s2 ) } 3 => { let trigram: [char; 3] = ngram.chars().collect::<Vec<char>>().try_into().unwrap(); let t = [ data.convert_u8.to_single(trigram[0]), data.convert_u8.to_single(trigram[1]), data.convert_u8.to_single(trigram[2]), ]; let &(_, occ) = data .trigrams .iter() .find(|&&(tf, _)| tf == t) .unwrap_or(&(t, 0.0)); format!("{ngram}: {:.3}%", occ * 100.0) } _ => "Invalid ngram! It must be 1, 2 or 3 chars long.".to_string(), } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/corpus_transposition.rs
oxeylyzer-repl/src/corpus_transposition.rs
use glob::glob; use oxeylyzer_core::translation::*; use serde::Deserialize; use std::fs::File; use std::io::Read; use std::path::PathBuf; #[derive(Deserialize, Default)] struct Multiple { #[serde(default)] uppercase_versions: bool, list: Vec<[String; 2]>, } #[derive(Deserialize, Default)] struct OneToOne { pub from: String, to: String, } impl std::ops::Add for OneToOne { type Output = OneToOne; fn add(mut self, rhs: Self) -> Self::Output { self.from.push_str(&rhs.from); self.to.push_str(&rhs.to); self } } #[derive(Deserialize)] struct CorpusConfigLoad { // source: Option<String>, // #[serde(from = "OneOrMany<_>")] #[serde(default)] inherits: Vec<String>, #[serde(default)] letters_to_lowercase: String, #[serde(default)] keep: String, #[serde(default)] multiple: Multiple, #[serde(default)] one_to_one: OneToOne, #[serde(default)] punct_unshifted: OneToOne, } impl CorpusConfigLoad { fn check_for_language(language: &str) -> Result<PathBuf, String> { let try_find_path = glob("static/corpus_configs/*/*.toml") .unwrap() .flatten() .find(|stem| stem.file_stem().unwrap_or_else(|| std::ffi::OsStr::new("")) == language); if let Some(path) = try_find_path { let res = path .as_path() .parent() .unwrap() .components() .next_back() .unwrap() .as_os_str(); Ok(PathBuf::from(res)) } else { Err("Could not find a fitting config".to_string()) } } pub fn new(language: &str, preferred_folder: Option<&str>) -> Result<Self, String> { let preferred_folder = if let Some(folder) = preferred_folder { Ok(PathBuf::from(folder)) } else { Self::check_for_language(language) }; if let Ok(preferred_folder) = preferred_folder { let file_name = format!("{language}.toml"); let path = PathBuf::from("static") .join("corpus_configs") .join(preferred_folder) .join(file_name); let mut f = File::open(path) .map_err(|_| "Couldn't open file because it does not exist.".to_string())?; let mut buf = String::new(); f.read_to_string(&mut buf) .map_err(|_| "Toml contains non-utf8 characters, aborting...".to_string())?; toml::from_str(buf.as_str()).map_err(|_| { "Toml contains invalid elements. Check the readme for what is allowed.".to_string() }) } else { Err("No config file found!".to_string()) } } } pub struct CorpusConfig { // source_language: String, inherits: Vec<String>, letters_to_lowercase: String, punct_unshifted: OneToOne, keep: String, to_multiple: Vec<(char, String)>, one_to_one: OneToOne, } impl CorpusConfig { pub fn new(language: &str, preferred_folder: Option<&str>) -> Result<Self, String> { let loaded = CorpusConfigLoad::new(language, preferred_folder)?; // let inherits = match loaded.inherits { // Some(Single(v)) => vec![v], // Some(Multiple(l)) => l, // None => Vec::new() // }; Ok(Self { // source_language: loaded.source.unwrap_or_else(|| language.to_string()), inherits: loaded.inherits, letters_to_lowercase: loaded.letters_to_lowercase, punct_unshifted: loaded.punct_unshifted, keep: loaded.keep, to_multiple: Self::get_to_multiple(loaded.multiple), one_to_one: loaded.one_to_one, }) } fn get_to_multiple(multiple: Multiple) -> Vec<(char, String)> { let mut res = Vec::new(); if multiple.uppercase_versions { for [from, to] in multiple.list { if from.chars().count() == 1 { let c = from.chars().next().unwrap(); res.push((c, to.clone())); let mut upper = c.to_uppercase(); if upper.clone().count() == 1 { let upper_c = upper.next().unwrap(); res.push((upper_c, to)) } } } } res } pub fn all() -> Vec<(String, Self)> { glob("static/text/*") .unwrap() .flatten() .filter(|pb| pb.is_dir()) .flat_map(|pb| pb.file_name().unwrap().to_os_string().into_string()) .map(|l| (l.clone(), Self::new(&l, None))) .flat_map(|(l, c)| c.ok().map(|cc| (l, cc))) .collect::<Vec<_>>() } pub fn new_translator(language: &str, preferred_folder: Option<&str>) -> Translator { match Self::new(language, preferred_folder) { Ok(config) => config.translator(), Err(error) => { println!("{error}\nUsing a raw translator instead."); Self::raw_translator() } } } pub fn translator(self) -> Translator { let mut res = Translator::new() .letters_to_lowercase(&self.letters_to_lowercase) .keep(&self.keep) .one_to_one(&self.one_to_one.from, &self.one_to_one.to) .custom_unshift(&self.punct_unshifted.from, &self.punct_unshifted.to) .to_multiple_string(&self.to_multiple) .build(); for inherits in self.inherits { if let Ok(new) = Self::new(&inherits, None) { res = res + new.translator(); } } res } pub fn raw_translator() -> Translator { Translator::raw(true) } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-repl/src/bin/main.rs
oxeylyzer-repl/src/bin/main.rs
// use oxeylyzer_core::generate_annealing::test; use oxeylyzer_repl::repl; fn main() -> Result<(), String> { repl::Repl::run() } // fn main() { // test() // }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/benches/generation.rs
benches/generation.rs
#![allow(dead_code)] use std::hint::black_box; use diol::prelude::*; use oxeylyzer_core::{ generate::*, utility::{PosPair, POSSIBLE_SWAPS}, }; fn main() -> std::io::Result<()> { let mut g = LayoutGeneration::new("english", "./static/", None).unwrap(); let saved = g.load_layouts("./static/layouts", "english").unwrap(); let layout_names = saved.keys().take(5).cloned().collect::<Vec<_>>(); let swaps = POSSIBLE_SWAPS .into_iter() .enumerate() .filter_map(|(i, swap)| ((i + 17) % 50 == 0).then_some(swap)) .collect::<Vec<_>>(); let mut bench = Bench::new(BenchConfig::from_args()?); bench.register(score_swap, swaps); bench.register(score_layout, layout_names.clone()); bench.register(generate, [0]); bench.register(best_swap_cached, layout_names); bench.run()?; Ok(()) } fn score_swap(bencher: Bencher, swap: PosPair) { let mut g = LayoutGeneration::new("english", "./static/", None).unwrap(); let saved = g.load_layouts("./static/layouts", "english").unwrap(); let (_name, mut layout) = saved.into_iter().next().unwrap(); let cache = g.initialize_cache(&layout); bencher.bench(|| g.score_swap_cached(&mut layout, &swap, &cache)) } fn score_layout(bencher: Bencher, name: String) { let mut g = LayoutGeneration::new("english", "./static/", None).unwrap(); let saved = g.load_layouts("./static/layouts", "english").unwrap(); let layout = black_box(saved.get(&name).unwrap()); bencher.bench(|| { g.score(layout); }) } fn best_swap_cached(bencher: Bencher, name: String) { let mut g = black_box(LayoutGeneration::new("english", "./static/", None).unwrap()); let saved = g.load_layouts("./static/layouts", "english").unwrap(); let mut layout = saved.get(&name).cloned().unwrap(); let cache = black_box(g.initialize_cache(&layout)); bencher.bench(|| { black_box(g.best_swap_cached(&mut layout, &cache, None, &POSSIBLE_SWAPS)); }) } fn generate(bencher: Bencher, _: usize) { let g = black_box(LayoutGeneration::new("english", "./static/", None).unwrap()); bencher.bench(|| { g.generate(); }) }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/load_text.rs
oxeylyzer-core/src/load_text.rs
use crate::translation::Translator; use std::fs::{read_dir, File}; use std::iter::FromIterator; use std::path::PathBuf; use std::time::Instant; use ahash::AHashMap as HashMap; use anyhow::Result; use file_chunker::FileChunker; use indexmap::IndexMap; use rayon::iter::{IntoParallelRefIterator, ParallelBridge, ParallelIterator}; use serde::{Deserialize, Serialize}; use smartstring::{LazyCompact, SmartString, SmartStringMode}; const FOUR_MB: u64 = 1024 * 1024 * 4; pub fn load_raw(language: &str) { load_data(language, Translator::raw(true)).unwrap(); } #[allow(dead_code)] pub(crate) fn load_default(language: &str) { let translator = Translator::language_or_raw(language); if let Err(error) = load_data(language, translator) { println!("{language} failed to update: '{error}'"); } } #[allow(dead_code)] pub(crate) fn load_all_default() -> Result<()> { let start_total = Instant::now(); std::fs::read_dir("static/text/")? .filter_map(Result::ok) .for_each(|language_dir| { let language = language_dir.path().display().to_string().replace('\\', "/"); let language = language.split('/').next_back().unwrap(); load_default(language); }); println!( "loading all languages took {}ms", (Instant::now() - start_total).as_millis() ); Ok(()) } pub fn load_data(language: &str, translator: Translator) -> Result<()> { let start_total = Instant::now(); let is_raw = translator.is_raw; let chunkers = read_dir(format!("static/text/{language}"))? .par_bridge() .filter_map(Result::ok) .flat_map(|dir_entry| File::open(dir_entry.path())) .map(|f| { let len = f.metadata().unwrap().len() + 1; let count = (len / FOUR_MB).max(1); (FileChunker::new(&f).unwrap(), count as usize) }) .collect::<Vec<_>>(); let chunkers_time = Instant::now(); println!( "Prepared text files in {}ms", (chunkers_time - start_total).as_millis() ); let strings = chunkers .par_iter() .flat_map(|(chunker, count)| chunker.chunks(*count, Some(' ')).unwrap()) .map(|chunk| { std::str::from_utf8(chunk).expect( "one of the files provided is not encoded as utf-8.\ Make sure all files in the directory are valid utf-8.", ) }) .map(|s| { let mut last_chars = SmartString::<LazyCompact>::new(); let mut inter = [' '; 5]; s.chars() .rev() .take(5) .enumerate() .for_each(|(i, c)| unsafe { *inter.get_unchecked_mut(4 - i) = c }); inter.into_iter().for_each(|c| last_chars.push(c)); last_chars.push_str(" "); (s, last_chars) }) .collect::<Vec<_>>(); println!( "Converted to utf8 in {}ms", (Instant::now() - chunkers_time).as_millis() ); let quingrams = strings .par_iter() .map(|(s, last)| TextNgrams::from_str_last(s, last)) .reduce(TextNgrams::default, |accum, new| accum.combine_with(new)); TextData::from((quingrams, language, translator)).save(is_raw)?; println!( "loading {} took {}ms", language, (Instant::now() - start_total).as_millis() ); Ok(()) } #[derive(Default, Debug)] pub struct TextNgrams<'a, const N: usize> { pub ngrams: HashMap<&'a str, usize>, } impl<'a, const N: usize> TextNgrams<'a, N> { fn from_str_last<M: SmartStringMode>(s: &'a str, last: &'a SmartString<M>) -> Self { let mut ngrams = HashMap::default(); let it1 = s.char_indices().map(|(i, _)| i); let it2 = s.char_indices().map(|(i, _)| i).skip(N); it1.zip(it2).map(|(i1, i2)| &s[i1..i2]).for_each(|ngram| { ngrams.entry(ngram).and_modify(|f| *f += 1).or_insert(1); }); let it1 = last.char_indices().map(|(i, _)| i); let it2 = last.char_indices().map(|(i, _)| i).skip(N); it1.zip(it2) .map(|(i1, i2)| &last[i1..i2]) .for_each(|ngram| { ngrams.entry(ngram).and_modify(|f| *f += 1).or_insert(1); }); Self { ngrams } } } impl<const N: usize> TextNgrams<'_, N> { fn combine_with(mut self, rhs: Self) -> Self { for (trigram, freq) in rhs.ngrams.into_iter() { self.ngrams .entry(trigram) .and_modify(|f| *f += freq) .or_insert(freq); } self } } #[derive(Default, Debug, Serialize, Deserialize)] pub struct TextData { language: String, characters: IndexMap<char, f64>, bigrams: IndexMap<SmartString<LazyCompact>, f64>, skipgrams: IndexMap<SmartString<LazyCompact>, f64>, skipgrams2: IndexMap<SmartString<LazyCompact>, f64>, skipgrams3: IndexMap<SmartString<LazyCompact>, f64>, trigrams: IndexMap<SmartString<LazyCompact>, f64>, #[serde(skip)] char_sum: f64, #[serde(skip)] bigram_sum: f64, #[serde(skip)] skipgram_sum: f64, #[serde(skip)] skipgram2_sum: f64, #[serde(skip)] skipgram3_sum: f64, #[serde(skip)] trigram_sum: f64, } impl std::fmt::Display for TextData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "{{\ \"language\": {},\ \"characters\": {:#?},\ \"bigrams\": {:#?},\ \"skipgrams\": {:#?},\ \"skipgrams2\": {:#?},\ \"skipgrams3\": {:#?},\ \"trigrams\": {:#?}\ }}", self.language, self.characters, self.bigrams, self.skipgrams, self.skipgrams2, self.skipgrams3, self.trigrams ) } } impl TextData { pub fn new(language: &str) -> Self { TextData { language: language.replace(' ', "_").to_lowercase().to_string(), ..Default::default() } } } impl From<(TextNgrams<'_, 5>, &str, Translator)> for TextData { fn from((ngrams, language, translator): (TextNgrams<5>, &str, Translator)) -> Self { let mut res = TextData::new(language); for (ngram, freq) in ngrams.ngrams.into_iter() { let first = unsafe { ngram.chars().next().unwrap_unchecked() }; if first != ' ' { if let Some(first_t) = translator.table.get(&first) { if first_t != " " { let mut trans = translator.translate(ngram); match trans.chars().count() { 5.. => { trans.push(' '); let first_t_len = first_t.chars().count().max(1); let it1 = trans.char_indices().map(|(i, _)| i).take(first_t_len); let it2 = trans .char_indices() .map(|(i, _)| i) .skip(5) .take(first_t_len); it1.zip(it2) .map(|(i1, i2)| &trans[i1..i2]) .for_each(|ngram| { res.add_n_subsequent::<5>(ngram, freq as f64) }); } 4 => { println!("4 long ngram: '{}'", &trans); res.add_n_subsequent::<4>(&trans, freq as f64) } 3 => res.add_n_subsequent::<3>(&trans, freq as f64), 2 => res.add_n_subsequent::<2>(&trans, freq as f64), 1 => res.add_n_subsequent::<1>(&trans, freq as f64), _ => {} } } } } } res.characters .iter_mut() .for_each(|(_, f)| *f /= res.char_sum); res.bigrams .iter_mut() .for_each(|(_, f)| *f /= res.bigram_sum); res.skipgrams .iter_mut() .for_each(|(_, f)| *f /= res.skipgram_sum); res.skipgrams2 .iter_mut() .for_each(|(_, f)| *f /= res.skipgram2_sum); res.skipgrams3 .iter_mut() .for_each(|(_, f)| *f /= res.skipgram3_sum); res.trigrams .iter_mut() .for_each(|(_, f)| *f /= res.trigram_sum); res.characters .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res.bigrams .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res.skipgrams .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res.skipgrams2 .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res.skipgrams3 .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res.trigrams .sort_by(|_, f1, _, f2| f2.partial_cmp(f1).unwrap()); res } } impl TextData { fn add_n_subsequent<const N: usize>(&mut self, ngram: &str, freq: f64) { let mut chars = ngram.chars(); match chars.next() { Some(c1) if N > 0 && c1 != ' ' => { self.add_character(c1, freq); // take first, first 2 etc chars of the trigram every time for the appropriate stat // as long as they don't contain spaces. return `c2` so I don't iter.next() too much let c2 = match chars.next() { Some(c2) if N > 1 && c2 != ' ' => { self.add_bigram([c1, c2], freq); c2 } _ => ' ', }; // c1 and c3 for skipgrams match chars.next() { Some(c3) if N > 2 && c3 != ' ' => { self.add_skipgram([c1, c3], freq); if c2 != ' ' { self.add_trigram([c1, c2, c3], freq); } match chars.next() { Some(c4) if N > 3 && c4 != ' ' => { self.add_skipgram2([c1, c4], freq); match chars.next() { Some(c5) if N > 4 && c5 != ' ' => { self.add_skipgram3([c1, c5], freq); } _ => {} } } _ => {} } } _ => {} } } _ => {} } } pub(crate) fn add_character(&mut self, c: char, freq: f64) { self.characters .entry(c) .and_modify(|e| *e += freq) .or_insert(freq); self.char_sum += freq; } pub(crate) fn add_bigram(&mut self, bigram: [char; 2], freq: f64) { self.bigrams .entry(SmartString::from_iter(bigram)) .and_modify(|e| *e += freq) .or_insert(freq); self.bigram_sum += freq; } pub(crate) fn add_skipgram(&mut self, skipgram: [char; 2], freq: f64) { self.skipgrams .entry(SmartString::from_iter(skipgram)) .and_modify(|e| *e += freq) .or_insert(freq); self.skipgram_sum += freq; } pub(crate) fn add_skipgram2(&mut self, skipgram: [char; 2], freq: f64) { self.skipgrams2 .entry(SmartString::from_iter(skipgram)) .and_modify(|e| *e += freq) .or_insert(freq); self.skipgram2_sum += freq; } pub(crate) fn add_skipgram3(&mut self, skipgram: [char; 2], freq: f64) { self.skipgrams3 .entry(SmartString::from_iter(skipgram)) .and_modify(|e| *e += freq) .or_insert(freq); self.skipgram3_sum += freq; } pub(crate) fn add_trigram(&mut self, trigram: [char; 3], freq: f64) { self.trigrams .entry(SmartString::from_iter(trigram)) .and_modify(|e| *e += freq) .or_insert(freq); self.trigram_sum += freq; } fn save(&self, pass: bool) -> Result<()> { use std::fs::OpenOptions; use std::io::Write; let buf = Vec::new(); let formatter = serde_json::ser::PrettyFormatter::with_indent(b"\t"); let mut ser = serde_json::Serializer::with_formatter(buf, formatter); self.serialize(&mut ser).unwrap(); let data_dir_str = format!("static/language_data{}", if pass { "_raw" } else { "" }); let data_dir = &PathBuf::from(data_dir_str); if let Ok(true) = data_dir.try_exists() { std::fs::create_dir_all(data_dir)?; } let mut file = OpenOptions::new() .write(true) .create(true) .truncate(true) .open(format!( "{}/{}.json", data_dir .to_str() .expect("the provided path should be valid utf8"), self.language ))?; file.write_all(ser.into_inner().as_slice())?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::{utility::ApproxEq, *}; #[test] fn from_textngrams() { let mut ngrams = TextNgrams::<5>::default(); ngrams.ngrams.insert("Amogu", 1); ngrams.ngrams.insert("mogus", 1); ngrams.ngrams.insert("ogus ", 1); ngrams.ngrams.insert("gus ", 1); ngrams.ngrams.insert("us ", 1); ngrams.ngrams.insert("s ", 1); let translator = Translator::new().letters_to_lowercase("amogus").build(); let data = TextData::from((ngrams, "among", translator)); assert_eq!(data.char_sum, 6.0,); assert_eq!(data.bigram_sum, 5.0,); assert_eq!(data.skipgram_sum, 4.0,); assert_eq!(data.skipgram2_sum, 3.0,); assert_eq!(data.skipgram3_sum, 2.0,); assert_eq!(data.trigram_sum, data.skipgram_sum); for (_, f) in data.characters { assert!(f.approx_eq_dbg(1.0 / 6.0, 15)); } for (_, f) in data.bigrams { assert!(f.approx_eq_dbg(1.0 / 5.0, 15)); } for (_, f) in data.skipgrams { assert!(f.approx_eq_dbg(1.0 / 4.0, 15)); } for (_, f) in data.skipgrams2 { assert!(f.approx_eq_dbg(1.0 / 3.0, 15)); } for (_, f) in data.skipgrams3 { assert!(f.approx_eq_dbg(1.0 / 2.0, 15)); } for (_, f) in data.trigrams { assert!(f.approx_eq_dbg(1.0 / 4.0, 15)); } } #[test] fn load_language_data() { use language_data::*; load_default("test"); let data = LanguageData::from_file("static/language_data", "test") .expect("'test.json' in static/language_data/ was not created"); assert!(data.language == "test"); let total_c = data .characters .iter() .filter(|f| f > &&0.0) .copied() .reduce(f64::min) .unwrap(); let total_c = (1.0 / total_c).round(); assert_eq!(total_c, 8.0); assert_eq!( data.characters .get(data.convert_u8.to_single_lossy('e') as usize), Some(&(2.0 / total_c)) ); assert_eq!( data.characters .get(data.convert_u8.to_single_lossy('\'') as usize), Some(&(1.0 / total_c)) ); let total_b = 1.0 / data .bigrams .iter() .copied() .filter(|f| f > &0.0) .reduce(f64::min) .unwrap(); let len = data.characters.len(); assert_eq!( data.bigrams .get(data.convert_u8.to_bigram_lossy(['\'', '*'], len)), Some(&(1.0 / total_b)) ); assert_eq!( data.bigrams .get(data.convert_u8.to_bigram_lossy(['1', ':'], len)), None ); let total_s = 1.0 / data .skipgrams .iter() .copied() .filter(|f| f > &0.0) .reduce(f64::min) .unwrap(); assert_eq!( data.skipgrams .get(data.convert_u8.to_bigram_lossy([';', 'd'], len)), Some(&(1.0 / total_s)) ); assert_eq!( data.skipgrams .get(data.convert_u8.to_bigram_lossy(['*', 'e'], len)), Some(&(1.0 / total_s)) ); assert_eq!( data.skipgrams .get(data.convert_u8.to_bigram_lossy(['t', 'e'], len)), Some(&(1.0 / total_s)) ); assert_eq!( data.skipgrams .get(data.convert_u8.to_bigram_lossy(['\'', 't'], len)), Some(&0.0) ); } #[test] fn get_generator() { let a = generate::LayoutGeneration::new("test", "static", None); assert!(a.is_ok()); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/lib.rs
oxeylyzer-core/src/lib.rs
pub mod generate; pub mod language_data; pub mod languages_cfg; pub mod layout; pub mod load_text; pub mod translation; pub mod trigram_patterns; pub mod utility; pub mod weights; pub use rayon; pub use serde;
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/translation.rs
oxeylyzer-core/src/translation.rs
use ahash::AHashMap as HashMap; use anyhow::Result; use smartstring::{Compact, LazyCompact, SmartString}; #[derive(Clone)] pub struct Translator { pub table: HashMap<char, SmartString<Compact>>, pub is_raw: bool, pub(crate) is_empty: bool, } impl Default for Translator { fn default() -> Self { let mut translator = Translator::new(); translator.default_formatting().build() } } impl std::ops::Add for Translator { type Output = Self; ///the table of the FIRST translator takes priority over the SECOND. fn add(mut self, rhs: Self) -> Self::Output { self.is_raw |= rhs.is_raw; self.is_empty &= rhs.is_empty; if !self.is_empty { let base = &SmartString::<Compact>::from(" "); for (from, to) in rhs.table { let original = self.table.get(&from); if original.is_none() || original == Some(base) { self.table.insert(from, to); } } self } else { self.table = rhs.table; self } } } impl Translator { #[allow(clippy::new_ret_no_self)] pub fn new() -> TranslatorBuilder { TranslatorBuilder { table: HashMap::default(), is_raw: false, } } #[allow(dead_code)] pub(crate) fn language(language: &str) -> Result<Self> { Ok(Self::new().language(language)?.build()) } #[allow(dead_code)] pub(crate) fn language_or_default(language: &str) -> Self { Self::language(language).unwrap_or_default() } #[allow(dead_code)] pub(crate) fn language_or_raw(language: &str) -> Self { Self::language(language).unwrap_or_else(|_| Self::raw(true)) } pub fn raw(unshift_chars: bool) -> Self { Translator::new().raw(unshift_chars).build() } pub fn translate(&self, s: &str) -> SmartString<LazyCompact> { let mut res = SmartString::<LazyCompact>::new(); for c in s.chars() { if let Some(replacement) = self.table.get(&c) { res.push_str(replacement); } else { res.push(' '); } } res } pub fn translate_arr(&self, arr: &[char]) -> SmartString<LazyCompact> { let mut res = SmartString::<LazyCompact>::new(); for c in arr.iter() { if let Some(replacement) = self.table.get(c) { res.push_str(replacement); } else { res.push(' '); } } res } } pub struct TranslatorBuilder { table: HashMap<char, SmartString<Compact>>, is_raw: bool, } impl TranslatorBuilder { pub fn to_nothing(&mut self, to_nothing: &str) -> &mut Self { for c in to_nothing.chars() { self.table.insert(c, SmartString::<Compact>::from("")); } self } pub fn to_space(&mut self, to_string: &str) -> &mut Self { for c in to_string.chars() { self.table.insert(c, SmartString::<Compact>::from(" ")); } self } pub fn many_different_to_one(&mut self, from: &str, to: char) -> &mut Self { for c in from.chars() { self.table.insert(c, SmartString::<Compact>::from(to)); } self } pub fn keep_one(&mut self, keep: char) -> &mut Self { self.table.insert(keep, SmartString::<Compact>::from(keep)); self } pub fn keep(&mut self, keep: &str) -> &mut Self { for c in keep.chars() { self.table.insert(c, SmartString::<Compact>::from(c)); } self } pub fn one_to_one(&mut self, from: &str, to: &str) -> &mut Self { assert_eq!(from.chars().count(), to.chars().count()); for (f, t) in from.chars().zip(to.chars()) { self.table.insert(f, SmartString::<Compact>::from(t)); } self } pub fn one_multiple(&mut self, from: char, to: &str) -> &mut Self { self.table.insert(from, SmartString::<Compact>::from(to)); self } #[inline(always)] fn one_multiple_smartstr(&mut self, from: char, to: SmartString<Compact>) -> &mut Self { self.table.insert(from, to); self } pub fn to_multiple(&mut self, trans: Vec<(char, &str)>) -> &mut Self { for (f, t) in trans { self.table.insert(f, SmartString::<Compact>::from(t)); } self } pub fn to_multiple_string(&mut self, trans: &Vec<(char, String)>) -> &mut Self { for (f, t) in trans { self.table.insert(*f, SmartString::<Compact>::from(t)); } self } pub fn letter_to_lowercase(&mut self, letter: char) -> &mut Self { self.table .insert(letter, SmartString::<Compact>::from(letter)); let mut upper_string = letter.to_uppercase(); if upper_string.clone().count() == 1 { let uppercase_letter = upper_string.next().unwrap(); let shifted = SmartString::<Compact>::from_iter([' ', letter]); self.one_multiple_smartstr(uppercase_letter, shifted); } self } pub fn letters_to_lowercase(&mut self, letters: &str) -> &mut Self { for letter in letters.chars() { self.letter_to_lowercase(letter); } self } pub fn raw(&mut self, unshift_chars: bool) -> &mut Self { self.is_raw = true; self.normalize_punct(); if unshift_chars { for i in 128u32..75_000 { if let Some(c) = char::from_u32(i) { if c.is_alphabetic() { if c.is_lowercase() { self.letter_to_lowercase(c); } else { self.keep_one(c); } } else if !c.is_control() { self.keep_one(c); } } } self.ascii_lower() } else { for i in 0u32..75_000 { match char::from_u32(i) { Some(c) if !c.is_control() => { self.keep_one(c); } _ => {} } } self } } pub fn custom_unshift(&mut self, upper_version: &str, lower_version: &str) -> &mut Self { for (upper, lower) in upper_version.chars().zip(lower_version.chars()) { let shifted = SmartString::<Compact>::from_iter([' ', lower]); self.one_multiple_smartstr(upper, shifted); } self.keep(lower_version) } pub(crate) fn punct_lower(&mut self) -> &mut Self { for (upper, lower) in "{}?+_|\"<>:~".chars().zip("[]/=-\\',.;`".chars()) { let shifted = String::from_iter([' ', lower]); self.one_multiple(upper, shifted.as_str()); } self.keep("[]/=-\\',.;`") } pub(crate) fn alphabet_lower(&mut self) -> &mut Self { self.letters_to_lowercase("abcdefghijklmnopqrstuvwxyz") } pub(crate) fn ascii_lower(&mut self) -> &mut Self { self.punct_lower().alphabet_lower() } pub(crate) fn normalize_punct(&mut self) -> &mut Self { self.one_to_one("«´»÷‘“”’–ʹ͵", "'''/''''-''") .one_multiple('…', "...") } pub(crate) fn default_formatting(&mut self) -> &mut Self { self.ascii_lower().normalize_punct() } pub(crate) fn language(&mut self, language: &str) -> Result<&mut Self> { self.default_formatting(); match language.to_lowercase().as_str() { "akl" | "english" | "english2" | "toki_pona" | "indonesian" | "reddit" => Ok(self), "albanian" => Ok(self.letters_to_lowercase("çë")), "bokmal" | "nynorsk" | "danish" => Ok(self.letters_to_lowercase("åøæ")), "czech" => Ok(self .to_multiple(vec![ ('č', "*c"), ('ď', "*d"), ('é', "*x"), ('ň', "*n"), ('ó', "*o"), ('ř', "*r"), ('š', "*s"), ('ť', "*t"), ('ů', "*u"), ('ú', "*b"), ('ý', "*y"), ('ž', "*z"), ('Č', "*c"), ('Ď', "*d"), ('É', "*x"), ('Ň', "*n"), ('Ó', "*o"), ('Ř', "*r"), ('Š', "*s"), ('Ť', "*t"), ('Ů', "*u"), ('Ú', "*b"), ('Ý', "*y"), ('Ž', "*z"), ]) .letters_to_lowercase("áíě")), "dan-en70-30" => Ok(self.letters_to_lowercase("åøæ")), "dan-en70-30a" => Ok(self.to_multiple(vec![('å', "*a"), ('ø', "*o"), ('æ', "*e")])), "dutch" => Ok(self.letters_to_lowercase("áèéçëíîó")), "dutch_repeat" => Ok(self.letters_to_lowercase("áèéçëíîó@")), "english_repeat" => Ok(self.keep("@")), "english_th" => Ok(self.letters_to_lowercase("þ")), "esperanto" => Ok(self.letters_to_lowercase("ŝĝĉŭĵĥ")), "finnish" => Ok(self.letters_to_lowercase("åäö")), "finnish_repeat" => Ok(self.letters_to_lowercase("åäö@")), "french" | "french_qu" | "test" => Ok(self .to_multiple(vec![ ('ç', "*c"), ('Ç', "*c"), ('œ', "oe"), ('á', "* a"), ('â', "* a"), ('è', "* e"), ('ê', "* e"), ('ì', "* i"), ('í', "* i"), ('î', "* i"), ('ò', "* o"), ('ó', "* o"), ('ô', "* o"), ('ù', "* u"), ('ú', "* u"), ('û', "* u"), ('Á', "* a"), ('Â', "* a"), ('È', "* e"), ('Ê', "* e"), ('Ì', "* i"), ('Í', "* i"), ('Î', "* i"), ('Ò', "* o"), ('Ó', "* o"), ('Ô', "* o"), ('Ù', "* u"), ('Ú', "* u"), ('Û', "* u"), ('ä', "* a"), ('ë', "* e"), ('ï', "* i"), ('ö', "* o"), ('ü', "* u"), ('Ä', "* a"), ('Ë', "* e"), ('Ï', "* i"), ('Ö', "* o"), ('Ü', "* u"), ]) .letters_to_lowercase("éà")), "german" => Ok(self.letters_to_lowercase("äöüß")), "hungarian" => Ok(self .to_multiple(vec![ ('í', "*i"), ('ü', "*u"), ('ú', "* u"), ('ű', "* u"), ('Í', "*i"), ('Ü', "*u"), ('Ú', "* u"), ('Ű', "* u"), ]) .letters_to_lowercase("áéöóő")), "italian" => Ok(self.to_multiple(vec![ ('à', "*a"), ('è', "*e"), ('ì', "*i"), ('ò', "*o"), ('ù', "*u"), ('À', "*a"), ('È', "*e"), ('Ì', "*i"), ('Ò', "*o"), ('Ù', "*u"), ])), "korean" => Ok(self .to_space("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") .keep("ㅣㅡㅜㅏㅊㅈㅅㅂㅁㄹㄷㄴㄱㅇㅋㅌㅍㅐㅑㅓㅕㅗㅎㅔㅛㅠ") .one_to_one("ㄲㄸㅆㅃㅉㅒㅖ", "ㄱㄷㅅㅂㅈㅐㅔ") .to_multiple(vec![ ('ㄳ', "ㄱㅅ"), ('ㅥ', "ㄴㄴ"), ('ㅦ', "ㄴㄷ"), ('ㅧ', "ㄴㅅ"), ('ㄵ', "ㄴㅈ"), ('ㄶ', "ㄴㅎ"), ('ㄺ', "ㄹㄱ"), ('ㅩ', "ㄹㄱㅅ"), ('ㅪ', "ㄹㄷ"), ('ㄻ', "ㄹㅁ"), ('ㄼ', "ㄹㅂ"), ('ㅫ', "ㄹㅂㅅ"), ('ㄽ', "ㄹㅅ"), ('ㄾ', "ㄹㅌ"), ('ㄿ', "ㄹㅍ"), ('ㅀ', "ㄹㅎ"), ('ㅮ', "ㅁㅂ"), ('ㅯ', "ㅁㅅ"), ('ㅲ', "ㅂㄱ"), ('ㅳ', "ㅂㄷ"), ('ㅄ', "ㅂㅅ"), ('ㅴ', "ㅂㅅㄱ"), ('ㅵ', "ㅂㅅㄷ"), ('ㅶ', "ㅂㅈ"), ('ㅷ', "ㅂㅌ"), ('ㅹ', "ㅂㅂ"), ('ㅺ', "ㅅㄱ"), ('ㅻ', "ㅅㄴ"), ('ㅼ', "ㅅㄷ"), ('ㅽ', "ㅅㅂ"), ('ㅾ', "ㅅㅈ"), ('ㆀ', "ㅇㅇ"), ('ㆄ', "ㅍ"), ('ㆅ', "ㅎㅎ"), ('ㅘ', "ㅗㅏ"), ('ㅙ', "ㅗㅐ"), ('ㅚ', "ㅗㅣ"), ('ㆇ', "ㅛㅑ"), ('ㆈ', "ㅛㅐ"), ('ㆉ', "ㅛㅣ"), ('ㅝ', "ㅜㅓ"), ('ㅞ', "ㅜㅔ"), ('ㅟ', "ㅜㅣ"), ('ㆊ', "ㅠㅖ"), ('ㆋ', "ㅠㅖ"), ('ㆌ', "ㅠㅣ"), ('ㅢ', "ㅡㅣ"), ('ㅸ', "ㅂ"), ('ㅱ', "ㅁ"), ])), "luxembourgish" => Ok(self.to_multiple(vec![ ('œ', " "), ('e', " ´"), ('u', " ¨"), ('i', " ˆ"), ('s', " ß"), ('d', " ∂"), ('c', " ç"), ])), "polish" => Ok(self .to_multiple(vec![ ('ą', "*a"), ('ó', "*o"), ('ź', "*z"), ('ś', "*s"), ('ć', "*c"), ('ń', "*n"), ]) .letters_to_lowercase("łęż")), "russian" => Ok(self .letters_to_lowercase("абвгдеёжзийклмнопрстуфхцчшщъыьэюя") .to_space("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")), "spanish" => Ok(self.to_multiple(vec![ ('á', "*a"), ('é', "*e"), ('í', "*i"), ('ó', "*o"), ('ú', "*u"), ('ü', "*y"), ('Á', "*a"), ('É', "*e"), ('Í', "*i"), ('Ó', "*o"), ('Ú', "*u"), ('Ü', "*y"), ('ñ', "*n"), ('Ñ', "*n"), ])), "swedish" => Ok(self.letters_to_lowercase("äåö")), "welsh" => Ok(self .to_multiple(vec![ ('â', "*a"), ('ê', "*e"), ('î', "*i"), ('ô', "*o"), ('û', "*u"), ('ŵ', "*w"), ('ŷ', "*y"), ('Â', "*a"), ('Ê', "*e"), ('Î', "*i"), ('Ô', "*o"), ('Û', "*u"), ('Ŵ', "*w"), ('Ŷ', "*y"), ]) .letters_to_lowercase("ΔⳐ")), "welsh_pure" => Ok(self.to_multiple(vec![ ('â', "*a"), ('ê', "*e"), ('î', "*i"), ('ô', "*o"), ('û', "*u"), ('ŵ', "*w"), ('ŷ', "*y"), ('Â', "*a"), ('Ê', "*e"), ('Î', "*i"), ('Ô', "*o"), ('Û', "*u"), ('Ŵ', "*w"), ('Ŷ', "*y"), ])), _ => Err(anyhow::format_err!( "This language is not available. You'll have to make your own formatter, sorry!" )), } } pub fn build(&mut self) -> Translator { Translator { is_empty: self.table.is_empty(), table: std::mem::take(&mut self.table), is_raw: self.is_raw, } } } #[cfg(test)] mod tests { use super::*; const ALPHABET: &str = "abcdefghijklmnopqrstuvwxyz"; const ALPHABET_UPPER: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const ALPHABET_SHIFTED: &str = " a b c d e f g h i j k l m n o p q r s t u v w x y z"; const NUMS: &str = "1234567890"; const NUMS_UPPER: &str = "!@#$%^&*()"; const SYMBOLS: &str = " ` [ ] / = - \\ ' , . ;"; const SYMBOLS_SHIFTED: &str = "~{}?+_|\"<>:"; #[test] fn test_translate_default() { let translator = Translator::default(); assert_eq!(translator.translate(ALPHABET), ALPHABET); assert_eq!( translator.translate(ALPHABET_SHIFTED), translator.translate(ALPHABET_UPPER) ); assert_eq!(translator.translate(NUMS), " "); assert_eq!(translator.translate(NUMS_UPPER), " "); assert_eq!( translator.translate(SYMBOLS), translator.translate(SYMBOLS_SHIFTED) ); assert_eq!(translator.translate("žø"), " "); assert_eq!(translator.translate("…"), "..."); assert_eq!(translator.translate("«´»÷‘“”’–ʹ͵"), "'''/''''-''"); } #[test] fn test_keep_all() { let translator = Translator::new().raw(false).build(); assert_eq!(translator.translate("ŽAamong us"), "ŽAamong us"); assert_eq!(translator.translate(NUMS), NUMS); } #[test] fn test_multiple() { let translator = Translator::new() .to_multiple(vec![('Ž', "* z")]) .letters_to_lowercase("aď") .build(); assert_eq!(translator.translate("ŽAaØ ď"), "* z aa ď"); } #[test] fn add_translators_together() { let t1 = Translator::new() .one_multiple('a', "abc") .one_to_one("b", "_") .build(); let t2 = Translator::new() .one_multiple('c', "cba") .one_to_one("b", "-") .build(); let t3 = t1.clone() + t2.clone(); let t4 = t2 + t1.clone(); assert_eq!(t3.translate("abcd"), "abc_cba "); assert_eq!(t4.translate("abcd"), "abc-cba "); let t_empty = Translator::new().build(); let t5 = t1.clone() + t_empty.clone(); let t6 = t_empty + t1; assert_eq!(t5.translate("abcd"), "abc_ "); assert_eq!(t5.translate("abcd"), t6.translate("abcd")); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/languages_cfg.rs
oxeylyzer-core/src/languages_cfg.rs
use ahash::AHashMap as HashMap; use std::io::Read; pub fn read_cfg() -> HashMap<String, String> { let mut res = HashMap::default(); if let Ok(mut f) = std::fs::File::open("languages_default.cfg") { let mut file_contents = String::new(); f.read_to_string(&mut file_contents).unwrap(); for line in file_contents.lines() { match parse_line(line) { Ok(parsed) => { for lang in parsed.languages { res.insert(lang, parsed.chars.clone()); } } Err(error_msg) => { if !error_msg.is_empty() { println!("{error_msg}") } } } } } else { println!( "No cfg file found! Make sure to have a 'languages_default.cfg' in your root folder" ); } res } struct LangsChars { languages: Vec<String>, chars: String, } fn parse_line(line: &str) -> Result<LangsChars, String> { let line_content = line.split('#').collect::<Vec<&str>>(); if !line_content.is_empty() && !line_content[0].is_empty() { let split_langs_chars = line_content[0].split(':').collect::<Vec<&str>>(); if split_langs_chars.len() == 2 { let langs = split_langs_chars[0] .trim() .split(',') .map(|s| s.trim().to_owned()) .collect::<Vec<String>>(); let chars = split_langs_chars[1].trim(); if !langs.is_empty() { let cc = chars.chars().count(); if cc == 30 { Ok(LangsChars { languages: langs, chars: chars.to_string(), }) } else { Err(format!( "You specified {cc} characters instead of the required 30 for {langs:?}" )) } } else { Err("No specified language".to_owned()) } } else { Err("Either the characters or language is missing".to_owned()) } } else { Err("".to_owned()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cfg() { let map = read_cfg(); println!("{map:#?}"); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/layout.rs
oxeylyzer-core/src/layout.rs
use crate::trigram_patterns::{TrigramPattern, TRIGRAM_COMBINATIONS}; use crate::utility::*; pub type CharToFinger = [usize; 60]; pub type Matrix<T> = [T; 30]; pub(crate) trait LayoutInternal<T: Copy + Default> { unsafe fn cu(&self, i: usize) -> T; unsafe fn swap_xy_no_bounds(&mut self, i1: usize, i2: usize); unsafe fn swap_no_bounds(&mut self, pair: &PosPair); unsafe fn swap_cols_no_bounds(&mut self, col1: usize, col2: usize); } pub trait Layout<T: Copy + Default> { fn new() -> Self; fn random(available_chars: [T; 30]) -> Self; fn random_pins(layout_chars: [T; 30], pins: &[usize]) -> Self; fn c(&self, i: usize) -> T; fn char(&self, x: usize, y: usize) -> T; fn swap(&mut self, i1: usize, i2: usize) -> Option<()>; fn swap_pair(&mut self, pair: &PosPair) -> Option<()>; fn swap_indexes(&mut self); fn get_index(&self, index: usize) -> [T; 6]; fn get_trigram_pattern(&self, trigram: &[T; 3]) -> TrigramPattern; } #[derive(Debug, Clone, PartialEq)] pub struct FastLayout { pub matrix: Matrix<u8>, pub char_to_finger: CharToFinger, pub score: f64, } impl Default for FastLayout { fn default() -> Self { Self::new() } } impl From<[u8; 30]> for FastLayout { fn from(layout: [u8; 30]) -> Self { let mut new_layout = FastLayout::new(); for (i, byte) in layout.into_iter().enumerate() { new_layout.matrix[i] = byte; new_layout.char_to_finger[byte as usize] = I_TO_COL[i]; } new_layout } } impl TryFrom<&[u8]> for FastLayout { type Error = anyhow::Error; fn try_from(layout_bytes: &[u8]) -> Result<Self, Self::Error> { if layout_bytes.len() >= 30 { let mut new_layout = FastLayout::new(); for (i, &byte) in layout_bytes.iter().enumerate() { new_layout.matrix[i] = byte; new_layout.char_to_finger[byte as usize] = I_TO_COL[i]; } Ok(new_layout) } else { anyhow::bail!("you should provide at least 30 bytes to create a layout from.") } } } impl FastLayout { pub fn layout_str(&self, con: &ConvertU8) -> String { con.as_str(&self.matrix) } pub fn formatted_string(&self, con: &ConvertU8) -> String { let mut res = String::new(); for (i, u) in self.matrix.iter().enumerate() { let c = con.from_single(*u); if i % 10 == 0 && i > 0 { res.push('\n'); } if (i + 5) % 10 == 0 { res.push(' '); } res.push(c); res.push(' '); } res } } impl LayoutInternal<u8> for FastLayout { #[inline(always)] unsafe fn cu(&self, i: usize) -> u8 { *self.matrix.get_unchecked(i) } #[inline(always)] unsafe fn swap_xy_no_bounds(&mut self, i1: usize, i2: usize) { let char1 = self.cu(i1); let char2 = self.cu(i2); *self.matrix.get_unchecked_mut(i1) = char2; *self.matrix.get_unchecked_mut(i2) = char1; *self.char_to_finger.get_unchecked_mut(char1 as usize) = *I_TO_COL.get_unchecked(i2); *self.char_to_finger.get_unchecked_mut(char2 as usize) = *I_TO_COL.get_unchecked(i1); } #[inline(always)] unsafe fn swap_no_bounds(&mut self, pair: &PosPair) { self.swap_xy_no_bounds(pair.0, pair.1); } unsafe fn swap_cols_no_bounds(&mut self, col1: usize, col2: usize) { self.swap_xy_no_bounds(col1, col2); self.swap_xy_no_bounds(col1 + 10, col2 + 10); self.swap_xy_no_bounds(col1 + 20, col2 + 20); } } impl Layout<u8> for FastLayout { fn new() -> FastLayout { FastLayout { matrix: [u8::MAX; 30], char_to_finger: [usize::MAX; 60], score: 0.0, } } fn random(mut with_chars: [u8; 30]) -> FastLayout { shuffle_pins::<30, u8>(&mut with_chars, &[]); FastLayout::from(with_chars) } fn random_pins(mut layout_chars: [u8; 30], pins: &[usize]) -> FastLayout { shuffle_pins::<30, u8>(&mut layout_chars, pins); FastLayout::from(layout_chars) } #[inline(always)] fn c(&self, i: usize) -> u8 { self.matrix[i] } fn swap_indexes(&mut self) { unsafe { self.swap_cols_no_bounds(3, 6); self.swap_cols_no_bounds(4, 5); } } fn get_index(&self, index: usize) -> [u8; 6] { let mut new_index = [0; 6]; let start_pos = index * 2 + 3; for i in 0..2 { for j in 0..3 { new_index[2 * j + i] = self.matrix[start_pos + i + 10 * j]; } } new_index } #[inline] fn char(&self, x: usize, y: usize) -> u8 { assert!(x < 10 && y < 3); self.matrix[x + 10 * y] } fn swap(&mut self, i1: usize, i2: usize) -> Option<()> { if i1 < 30 && i2 < 30 { let char1 = self.matrix[i1]; let char2 = self.matrix[i2]; self.matrix[i1] = char2; self.matrix[i2] = char1; self.char_to_finger[char1 as usize] = I_TO_COL[i2]; self.char_to_finger[char2 as usize] = I_TO_COL[i1]; Some(()) } else { println!("Invalid coordinate, swap was cancelled"); None } } #[inline(always)] fn swap_pair(&mut self, pair: &PosPair) -> Option<()> { self.swap(pair.0, pair.1) } #[inline(always)] fn get_trigram_pattern(&self, &[t1, t2, t3]: &[u8; 3]) -> TrigramPattern { let a = match self.char_to_finger.get(t1 as usize) { Some(&v) if v != usize::MAX => v, _ => return TrigramPattern::Invalid, }; let b = match self.char_to_finger.get(t2 as usize) { Some(&v) if v != usize::MAX => v, _ => return TrigramPattern::Invalid, }; let c = match self.char_to_finger.get(t3 as usize) { Some(&v) if v != usize::MAX => v, _ => return TrigramPattern::Invalid, }; // a, b and c are numbers between 0 and 7. This means they fit in exactly 3 bits (7 == 0b111) let combination = (a << 6) | (b << 3) | c; TRIGRAM_COMBINATIONS[combination] } } #[cfg(test)] mod tests { use super::*; use once_cell::sync::Lazy; static CON: Lazy<ConvertU8> = Lazy::new(|| ConvertU8::with_chars("abcdefghijklmnopqrstuvwxyz'.,;/")); #[test] fn layout_str() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); println!("{qwerty_bytes:?}"); let qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); assert_eq!( CON.from(qwerty.matrix), vec![ 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/' ] ); assert_eq!( qwerty.layout_str(&CON), "qwertyuiopasdfghjkl;zxcvbnm,./".to_string() ); } #[test] fn swap() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); println!("{qwerty_bytes:?}"); let mut qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); qwerty.swap(10, 11); assert_eq!( qwerty.layout_str(&CON), "qwertyuiopsadfghjkl;zxcvbnm,./".to_owned() ); } #[test] fn swap_no_bounds() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let mut qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); unsafe { qwerty.swap_xy_no_bounds(9, 12) }; assert_eq!( qwerty.layout_str(&CON), "qwertyuiodaspfghjkl;zxcvbnm,./".to_string() ); } #[test] fn swap_cols_no_bounds() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let mut qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); unsafe { qwerty.swap_cols_no_bounds(1, 9) }; assert_eq!( qwerty.layout_str(&CON), "qpertyuiowa;dfghjklsz/cvbnm,.x".to_string() ); } #[test] fn swap_pair() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let mut qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); let new_swap = PosPair::new(0, 29); qwerty.swap_pair(&new_swap); assert_eq!( qwerty.layout_str(&CON), "/wertyuiopasdfghjkl;zxcvbnm,.q".to_string() ); } #[test] fn swap_pair_no_bounds() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let mut qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); let new_swap = PosPair::new(0, 29); unsafe { qwerty.swap_no_bounds(&new_swap) }; assert_eq!( qwerty.layout_str(&CON), "/wertyuiopasdfghjkl;zxcvbnm,.q".to_string() ); } #[test] fn char_to_finger() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('a') as usize), Some(&0usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('w') as usize), Some(&1usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('c') as usize), Some(&2usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('r') as usize), Some(&3usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('b') as usize), Some(&3usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('h') as usize), Some(&4usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('u') as usize), Some(&4usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('i') as usize), Some(&5usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy('.') as usize), Some(&6usize) ); assert_eq!( qwerty.char_to_finger.get(CON.to_single_lossy(';') as usize), Some(&7usize) ); } #[test] fn char() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); assert_eq!(qwerty.char(4, 1), CON.to_single_lossy('g')); assert_eq!(qwerty.char(9, 2), CON.to_single_lossy('/')); assert_eq!(qwerty.char(8, 1), CON.to_single_lossy('l')); } #[test] fn char_by_index() { let qwerty_bytes = CON.to_lossy("qwertyuiopasdfghjkl;zxcvbnm,./".chars()); let qwerty = FastLayout::try_from(qwerty_bytes.as_slice()).expect("couldn't create qwerty"); assert_eq!(qwerty.c(10), CON.to_single_lossy('a')); assert_eq!(qwerty.c(24), CON.to_single_lossy('b')); assert_eq!(qwerty.c(22), CON.to_single_lossy('c')); } // #[test] // fn random_layouts() { // use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; // use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle}; // use std::io::Write; // use crate::analyze::LayoutAnalysis; // let anal = LayoutAnalysis::new("english", None).unwrap(); // let available_chars = available_chars("english"); // let pb = ProgressBar::new(10_000_000); // pb.set_style(ProgressStyle::default_bar() // .template("[{elapsed_precise}] [{bar:40.white/white}] [eta: {eta}] - {per_sec:>4} {pos:>6}/{len}") // .progress_chars("=>-")); // let mut res = Vec::with_capacity(10_000_000); // let start = std::time::Instant::now(); // (0..10_000_000) // .into_par_iter() // .progress_with(pb) // .map(|_| -> f32 { // let r = FastLayout::random(available_chars); // anal.score(&r, 5_000) as f32 // }) // .collect_into_vec(&mut res); // let end = std::time::Instant::now(); // res.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap()); // println!("that took {}s.", (end - start).as_secs_f64()); // let mut f = std::fs::OpenOptions::new() // .write(true) // .create(true) // .truncate(true) // .open("10mil_scores") // .unwrap(); // let mut to_save_vec = Vec::new(); // res // .into_par_iter() // .map(|v| v.to_string()) // .collect_into_vec(&mut to_save_vec); // let to_save = to_save_vec.join("\n"); // f.write(to_save.as_bytes()).unwrap(); // } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/utility.rs
oxeylyzer-core/src/utility.rs
use std::collections::hash_map::Entry; use crate::languages_cfg::read_cfg; use ahash::AHashMap as HashMap; use arrayvec::ArrayVec; use nanorand::{tls_rng, Rng}; use serde::Deserialize; #[inline] pub fn shuffle_pins<const N: usize, T>(slice: &mut [T], pins: &[usize]) { let mapping: ArrayVec<_, N> = (0..slice.len()).filter(|x| !pins.contains(x)).collect(); let mut rng = tls_rng(); for (m, &swap1) in mapping.iter().enumerate() { let swap2 = rng.generate_range(m..mapping.len()); slice.swap(swap1, mapping[swap2]); } } #[rustfmt::skip] pub static I_TO_COL: [usize; 30] = [ 0, 1, 2, 3, 3, 4, 4, 5, 6, 7, 0, 1, 2, 3, 3, 4, 4, 5, 6, 7, 0, 1, 2, 3, 3, 4, 4, 5, 6, 7, ]; #[derive(Copy, Clone, Debug, PartialEq, Eq, Default)] pub struct PosPair(pub usize, pub usize); #[rustfmt::skip] const AFFECTS_SCISSOR: [bool; 30] = [ true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, true, true, true, true, true, false, true, false, false, true, true, true, ]; #[rustfmt::skip] const AFFECTS_LSB: [bool; 30] = [ false, false, true, false, true, true, false, true, false, false, false, false, true, false, true, true, false, true, false, false, false, false, true, false, true, true, false, true, false, false, ]; #[rustfmt::skip] const AFFECTS_PINKY_RING: [bool; 30] = [ true, true, false, false, false, false, false, false, true, true, true, true, false, false, false, false, false, false, true, true, true, true, false, false, false, false, false, false, true, true, ]; impl PosPair { pub const fn default() -> Self { Self(0, 0) } pub const fn new(x1: usize, x2: usize) -> Self { Self(x1, x2) } #[inline] pub fn affects_scissor(&self) -> bool { unsafe { *AFFECTS_SCISSOR.get_unchecked(self.0) || *AFFECTS_SCISSOR.get_unchecked(self.1) } } #[inline] pub fn affects_lsb(&self) -> bool { unsafe { *AFFECTS_LSB.get_unchecked(self.0) || *AFFECTS_LSB.get_unchecked(self.1) } } #[inline] pub fn affects_pinky_ring(&self) -> bool { unsafe { *AFFECTS_PINKY_RING.get_unchecked(self.0) || *AFFECTS_PINKY_RING.get_unchecked(self.1) } } } impl std::fmt::Display for PosPair { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "({}, {})", self.0, self.1) } } pub const POSSIBLE_SWAPS: [PosPair; 435] = get_possible_swaps(); const fn get_possible_swaps() -> [PosPair; 435] { let mut res = [PosPair::default(); 435]; let mut i = 0; let mut pos1 = 0; while pos1 < 30 { let mut pos2 = pos1 + 1; while pos2 < 30 { res[i] = PosPair(pos1, pos2); i += 1; pos2 += 1; } pos1 += 1; } res } #[derive(Clone, Debug, Default)] pub struct ConvertU8 { from: Vec<char>, to: HashMap<char, u8>, } impl ConvertU8 { pub fn new() -> Self { Self::default() } pub fn from_single(&self, c: u8) -> char { *self.from.get(c as usize).unwrap_or(&' ') } pub fn from<T>(&self, input: T) -> Vec<char> where T: IntoIterator<Item = u8>, { input.into_iter().map(|c| self.from_single(c)).collect() } pub fn to_single(&mut self, c: char) -> u8 { if let Some(u) = self.to.get(&c) { *u } else { let new = self.len(); self.from.push(c); self.to.insert(c, new); new } } pub fn to_bigram(&mut self, from: [char; 2]) -> [u8; 2] { [self.to_single(from[0]), self.to_single(from[1])] } pub fn to_trigram(&mut self, from: [char; 3]) -> [u8; 3] { [ self.to_single(from[0]), self.to_single(from[1]), self.to_single(from[2]), ] } pub fn to<T>(&mut self, input: T) -> Vec<u8> where T: IntoIterator<Item = char>, { input.into_iter().map(|c| self.to_single(c)).collect() } pub fn to_single_lossy(&self, c: char) -> u8 { if let Some(u) = self.to.get(&c) { *u } else { self.len() } } pub fn to_bigram_lossy(&self, from: [char; 2], char_count: usize) -> usize { let c1 = self.to_single_lossy(from[0]) as usize; let c2 = self.to_single_lossy(from[1]) as usize; if c1 < char_count && c2 < char_count { c1 * char_count + c2 } else { u8::MAX as usize } } pub fn to_trigram_lossy(&self, from: [char; 3]) -> [u8; 3] { [ self.to_single_lossy(from[0]), self.to_single_lossy(from[1]), self.to_single_lossy(from[2]), ] } pub fn to_lossy<T>(&self, input: T) -> Vec<u8> where T: IntoIterator<Item = char>, { input.into_iter().map(|c| self.to_single_lossy(c)).collect() } pub fn insert_single(&mut self, c: char) { let new = self.len(); if let Entry::Vacant(e) = self.to.entry(c) { self.from.push(c); e.insert(new); } } pub fn insert<T>(&mut self, input: T) where T: IntoIterator<Item = char>, { input.into_iter().for_each(|c| self.insert_single(c)); } pub fn with_chars(s: &str) -> Self { let mut res = Self::default(); res.insert(s.chars()); res } pub fn as_str(&self, input: &[u8]) -> String { input .iter() .map(|&c| self.from.get(c as usize).unwrap_or(&' ')) .collect() } pub fn len(&self) -> u8 { debug_assert_eq!(self.to.len(), self.from.len()); self.to.len() as u8 } pub fn is_empty(&self) -> bool { self.to.len() == 0 } } #[derive(Deserialize, Debug, Clone, Default)] pub enum KeyboardType { #[default] AnsiAngle, IsoAngle, RowstagDefault, Ortho, Colstag, } impl TryFrom<String> for KeyboardType { type Error = &'static str; fn try_from(value: String) -> Result<Self, &'static str> { let lower = value.to_lowercase(); let split = lower.split_whitespace().collect::<Vec<&str>>(); if split.len() == 1 { match split[0] { "ortho" => Ok(Self::Ortho), "colstag" => Ok(Self::Colstag), "rowstag" | "iso" | "ansi" | "jis" => Ok(Self::RowstagDefault), _ => Err("Couldn't parse keyboard type!"), } } else if split.len() == 2 { match (split[0], split[1]) { ("ansi", "angle") => Ok(Self::AnsiAngle), ("iso", "angle") => Ok(Self::IsoAngle), _ => Err("Couldn't parse keyboard type!"), } } else { Err("Couldn't parse keyboard type!") } } } pub fn get_effort_map(heatmap_weight: f64, ktype: KeyboardType) -> [f64; 30] { use KeyboardType::*; #[rustfmt::skip] let mut res = match ktype { IsoAngle => [ 3.0, 2.4, 2.0, 2.2, 2.4, 3.3, 2.2, 2.0, 2.4, 3.0, 1.8, 1.3, 1.1, 1.0, 2.6, 2.6, 1.0, 1.1, 1.3, 1.8, 3.3, 2.8, 2.4, 1.8, 2.2, 2.2, 1.8, 2.4, 2.8, 3.3, ], AnsiAngle => [ 3.0, 2.4, 2.0, 2.2, 2.4, 3.3, 2.2, 2.0, 2.4, 3.0, 1.8, 1.3, 1.1, 1.0, 2.6, 2.6, 1.0, 1.1, 1.3, 1.8, 3.7, 2.8, 2.4, 1.8, 2.2, 2.2, 1.8, 2.4, 2.8, 3.3, ], RowstagDefault => [ 3.0, 2.4, 2.0, 2.2, 2.4, 3.3, 2.2, 2.0, 2.4, 3.0, 1.8, 1.3, 1.1, 1.0, 2.6, 2.6, 1.0, 1.1, 1.3, 1.8, 3.5, 3.0, 2.7, 2.3, 3.7, 2.2, 1.8, 2.4, 2.8, 3.3, ], Ortho => [ 3.0, 2.4, 2.0, 2.2, 3.1, 3.1, 2.2, 2.0, 2.4, 3.0, 1.7, 1.3, 1.1, 1.0, 2.6, 2.6, 1.0, 1.1, 1.3, 1.7, 3.2, 2.6, 2.3, 1.6, 3.0, 3.0, 1.6, 2.3, 2.6, 3.2, ], Colstag => [ 3.0, 2.4, 2.0, 2.2, 3.1, 3.1, 2.2, 2.0, 2.4, 3.0, 1.7, 1.3, 1.1, 1.0, 2.6, 2.6, 1.0, 1.1, 1.3, 1.7, 3.4, 2.6, 2.2, 1.8, 3.2, 3.2, 1.8, 2.2, 2.6, 3.4, ], }; for r in &mut res { *r -= 0.2; *r /= 4.5; *r *= heatmap_weight; } res } pub fn get_fspeed(lat_multiplier: f64) -> [(PosPair, f64); 48] { let mut res = Vec::new(); for (b, dist) in get_sfb_indices().iter().zip(get_distances(lat_multiplier)) { res.push((*b, dist)); } res.try_into().unwrap() } pub fn get_distances(lat_multiplier: f64) -> [f64; 48] { let mut res = [0.0; 48]; let mut i = 0; let help = |f: f64, r: f64| f.powi(2).powf(0.65) * r; let fweights = [1.4, 3.6, 4.8, 4.8, 3.6, 1.4]; let mut fweight_i = 0; while fweight_i < 6 { let fweight = fweights[fweight_i]; let ratio = 5.5 / fweight; res[i] = help(1.0, ratio); res[i + 1] = help(2.0, ratio); res[i + 2] = help(1.0, ratio); fweight_i += 1; i += 3; } let mut c = 0; while c <= 2 { let index = [ ((0, 0), (0, 1)), ((0, 0), (0, 2)), ((0, 0), (1, 0)), ((0, 0), (1, 1)), ((0, 0), (1, 2)), ((0, 1), (0, 2)), ((0, 1), (1, 0)), ((0, 1), (1, 1)), ((0, 1), (1, 2)), ((0, 2), (1, 0)), ((0, 2), (1, 1)), ((0, 2), (1, 2)), ((1, 0), (1, 1)), ((1, 0), (1, 2)), ((1, 1), (1, 2)), ]; let mut pair_i = 0; while pair_i < 15 { let ((x1, y1), (x2, y2)) = index[pair_i]; let x_dist = (x1 - x2) as f64; let y_dist = (y1 - y2) as f64; let distance = (x_dist.powi(2) * lat_multiplier + y_dist.powi(2)).powf(0.65); res[i] = distance; i += 1; pair_i += 1; } c += 2; } res } pub const fn get_sfb_indices() -> [PosPair; 48] { let mut res = [PosPair::default(); 48]; let mut i = 0; let mut col_i = 0; let cols = [0, 1, 2, 7, 8, 9]; while col_i < cols.len() { let col = cols[col_i]; res[i] = PosPair(col, col + 10); res[i + 1] = PosPair(col, col + 20); res[i + 2] = PosPair(col + 10, col + 20); col_i += 1; i += 3; } let mut c = 0; while c <= 2 { let index = [ (3 + c, 13 + c), (3 + c, 23 + c), (3 + c, 4 + c), (3 + c, 14 + c), (3 + c, 24 + c), (13 + c, 23 + c), (13 + c, 4 + c), (13 + c, 14 + c), (13 + c, 24 + c), (23 + c, 4 + c), (23 + c, 14 + c), (23 + c, 24 + c), (4 + c, 14 + c), (4 + c, 24 + c), (14 + c, 24 + c), ]; let mut pair_i = 0; while pair_i < 15 { res[i] = PosPair(index[pair_i].0, index[pair_i].1); i += 1; pair_i += 1; } c += 2; } res } pub const fn get_lsb_indices() -> [PosPair; 16] { let mut res = [PosPair::default(); 16]; let left = [ (2, 4), (2, 14), (2, 24), (12, 4), (12, 14), (22, 4), (22, 14), (22, 24), ]; let right = [ (5, 7), (5, 17), (5, 27), (15, 7), (15, 17), (15, 27), (25, 17), (25, 27), ]; let mut i = 0; while i < left.len() { res[i] = PosPair(left[i].0, left[i].1); res[i + 8] = PosPair(right[i].0, right[i].1); i += 1; } res } pub const fn get_pinky_ring_indices() -> [PosPair; 18] { [ PosPair(0, 1), PosPair(0, 11), PosPair(0, 21), PosPair(11, 1), PosPair(11, 11), PosPair(11, 21), PosPair(21, 1), PosPair(21, 11), PosPair(21, 21), PosPair(8, 9), PosPair(8, 19), PosPair(8, 29), PosPair(18, 9), PosPair(18, 19), PosPair(18, 29), PosPair(28, 9), PosPair(28, 19), PosPair(28, 29), ] } pub const fn get_scissor_indices() -> [PosPair; 17] { let mut res = [PosPair::default(); 17]; //these add normal stretching between ajacent columns that stretch between 2 rows except for //qwerty mi and ce (assuming c is typed with index) // let mut i = 0; // let cols = [0, 1, 2, 6, 7, 8]; // while i < cols.len() { // let col_nr = cols[i]; // if col_nr != 2 { // res[i] = PosPair(col_nr, col_nr+21); // } // if col_nr != 6 { // res[i+6] = PosPair(col_nr+1, col_nr+20); // } // i += 1; // } res[0] = PosPair(0, 21); res[1] = PosPair(1, 22); res[2] = PosPair(6, 27); res[3] = PosPair(7, 28); res[4] = PosPair(8, 29); res[5] = PosPair(1, 20); res[6] = PosPair(2, 21); res[7] = PosPair(3, 22); res[8] = PosPair(8, 27); res[9] = PosPair(9, 28); //pinky->ring 1u stretches res[10] = PosPair(0, 11); res[11] = PosPair(9, 18); res[12] = PosPair(10, 21); res[13] = PosPair(19, 28); //inner index scissors (no qwerty `ni` because of stagger) res[14] = PosPair(2, 24); res[15] = PosPair(22, 4); res[16] = PosPair(5, 27); res } pub fn chars_for_generation(language: &str) -> [char; 30] { let languages_cfg_map = read_cfg(); if let Some(cfg) = languages_cfg_map.get(language) { cfg.chars().collect::<Vec<char>>().try_into().unwrap() } else { let default = languages_cfg_map.get(&String::from("default")).unwrap(); default.chars().collect::<Vec<char>>().try_into().unwrap() } } pub trait ApproxEq { fn approx_eq(self, other: f64, dec: u8) -> bool; fn approx_eq_dbg(self, other: f64, dec: u8) -> bool; } impl ApproxEq for f64 { fn approx_eq(self, other: f64, dec: u8) -> bool { let factor = 10.0f64.powi(dec as i32); let a = (self * factor).trunc(); let b = (other * factor).trunc(); a == b } fn approx_eq_dbg(self, other: f64, dec: u8) -> bool { let factor = 10.0f64.powi(dec as i32); let a = (self * factor).trunc(); let b = (other * factor).trunc(); if a != b { println!("approx not equal: {self} != {other}"); } a == b } } pub(crate) fn is_kb_file(entry: &std::fs::DirEntry) -> bool { if let Some(ext_os) = entry.path().extension() { if let Some(ext) = ext_os.to_str() { return ext == "kb"; } } false } pub(crate) fn layout_name(entry: &std::fs::DirEntry) -> Option<String> { if let Some(name_os) = entry.path().file_stem() { if let Some(name_str) = name_os.to_str() { return Some(name_str.to_string()); } } None } pub(crate) fn format_layout_str(layout_str: &str) -> String { layout_str .split('\n') .take(3) .map(|line| line.split_whitespace().take(10).collect::<String>()) .collect::<String>() } #[cfg(test)] mod tests { use super::*; use ahash::AHashSet as HashSet; #[test] fn affects_scissors() { let indices = get_scissor_indices() .into_iter() .flat_map(|PosPair(i1, i2)| [i1, i2]) .collect::<HashSet<_>>(); (0..30).for_each(|i| { if indices.contains(&i) { assert!(AFFECTS_SCISSOR[i], "failed on {i}"); } else { assert!(!AFFECTS_SCISSOR[i], "failed on {i}"); } }); } #[test] fn approx_eq() { assert!((0.123456789).approx_eq(0.0, 0)); assert!((0.123456789).approx_eq(0.1, 1)); assert!((0.123456789).approx_eq(0.12, 2)); assert!((0.123456789).approx_eq(0.123, 3)); assert!((0.123456789).approx_eq(0.1234, 4)); assert!((0.123456789).approx_eq(0.12345, 5)); assert!((0.123456789).approx_eq(0.123456, 6)); assert!((0.123456789).approx_eq(0.1234567, 7)); assert!((0.123456789).approx_eq(0.12345678, 8)); assert!((0.123456789).approx_eq(0.123456789, 9)); assert!(!(0.123456789).approx_eq(0.0, 3)); assert!(!(0.123456789).approx_eq(0.1, 4)); assert!((0.123456789).approx_eq_dbg(0.0, 0)); assert!((0.123456789).approx_eq_dbg(0.1, 1)); assert!((0.123456789).approx_eq_dbg(0.12, 2)); assert!((0.123456789).approx_eq_dbg(0.123, 3)); assert!((0.123456789).approx_eq_dbg(0.1234, 4)); assert!((0.123456789).approx_eq_dbg(0.12345, 5)); assert!((0.123456789).approx_eq_dbg(0.123456, 6)); assert!((0.123456789).approx_eq_dbg(0.1234567, 7)); assert!((0.123456789).approx_eq_dbg(0.12345678, 8)); assert!((0.123456789).approx_eq_dbg(0.123456789, 9)); assert!(!(0.123456789).approx_eq_dbg(0.0, 3)); assert!(!(0.123456789).approx_eq_dbg(0.1, 4)); } #[test] fn format_layout_string() { let str1 = "v m l c p q z u o , \ns t r d y f n e a i \nx k j g w b h ; ' ."; let str2 = "a b c d e f g h i \n j k l \n m n o p q \n r s t u v w x y z"; assert_eq!(format_layout_str(str1), "vmlcpqzuo,strdyfneaixkjgwbh;'."); assert_eq!(format_layout_str(str2), "abcdefghijklmnopq"); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/language_data.rs
oxeylyzer-core/src/language_data.rs
use anyhow::Result; use arrayvec::ArrayVec; // use fxhash::FxHashMap; use ahash::AHashMap as HashMap; use indexmap::IndexMap; use itertools::Itertools; use serde::Deserialize; use serde_json; use std::fs::File; use std::io::prelude::*; use std::path::Path; use crate::utility::ConvertU8; pub type CharacterData = ArrayVec<f64, 60>; pub type SlowBigramData = HashMap<[u8; 2], f64>; pub type BigramData = Vec<f64>; pub type TrigramData = Vec<([u8; 3], f64)>; #[derive(Deserialize)] struct LanguageDataInter { pub language: String, pub characters: HashMap<char, f64>, pub bigrams: HashMap<String, f64>, pub skipgrams: HashMap<String, f64>, pub skipgrams2: HashMap<String, f64>, pub skipgrams3: HashMap<String, f64>, pub trigrams: IndexMap<String, f64>, } fn get_char_data(data: HashMap<char, f64>, con: &mut ConvertU8) -> CharacterData { let mut res = CharacterData::new(); for (c, f) in data.into_iter() { con.insert_single(c); res.push(f); } res } fn get_bigram_data(data: HashMap<String, f64>, con: &mut ConvertU8) -> BigramData { (0..con.len()) .cartesian_product(0..con.len()) .map(|(c1, c2)| con.as_str(&[c1, c2])) .map(|bigram| *data.get(&bigram).unwrap_or(&0.0)) .collect::<BigramData>() } fn get_trigram_data(data: IndexMap<String, f64>, con: &mut ConvertU8) -> TrigramData { let mut res = TrigramData::new(); for (trigram, freq) in data { let tv = trigram.chars().collect::<Vec<char>>(); let tv_u8 = con.to(tv); if tv_u8[0] != tv_u8[1] && tv_u8[1] != tv_u8[2] { let new_trigram = [tv_u8[0], tv_u8[1], tv_u8[2]]; res.push((new_trigram, freq)); } } res } pub struct LanguageData { pub characters: CharacterData, pub bigrams: BigramData, pub skipgrams: BigramData, pub skipgrams2: BigramData, pub skipgrams3: BigramData, pub weighted_bigrams: BigramData, pub trigrams: TrigramData, pub language: String, pub convert_u8: ConvertU8, } impl From<LanguageDataInter> for LanguageData { fn from(mut inter: LanguageDataInter) -> Self { let mut convert_u8 = ConvertU8::new(); for c in ['\'', ',', '.', ';', '/', '~'] { inter.characters.entry(c).or_insert(0.0); } let characters = get_char_data(inter.characters, &mut convert_u8); let bigrams = get_bigram_data(inter.bigrams, &mut convert_u8); let skipgrams = get_bigram_data(inter.skipgrams, &mut convert_u8); let skipgrams2 = get_bigram_data(inter.skipgrams2, &mut convert_u8); let skipgrams3 = get_bigram_data(inter.skipgrams3, &mut convert_u8); let weighted_bigrams = BigramData::new(); let trigrams = get_trigram_data(inter.trigrams, &mut convert_u8); Self { characters, bigrams, skipgrams, skipgrams2, skipgrams3, trigrams, weighted_bigrams, language: inter.language, convert_u8, } } } impl LanguageData { pub fn new(text: &str) -> Result<LanguageData> { let data: LanguageDataInter = serde_json::from_str(text)?; Ok(LanguageData::from(data)) } pub fn from_file<P>(base_path: P, language: &str) -> Result<LanguageData> where P: AsRef<Path>, { let file_path = base_path.as_ref().join(language.to_lowercase() + ".json"); let mut file = File::open(file_path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let data: LanguageDataInter = serde_json::from_str(contents.as_str())?; let res = LanguageData::from(data); Ok(res) } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/generate.rs
oxeylyzer-core/src/generate.rs
use std::hint::unreachable_unchecked; use std::path::Path; use anyhow::Result; // use fxhash::FxHashMap; use ahash::AHashMap as HashMap; use indexmap::IndexMap; use itertools::Itertools; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use crate::language_data::{BigramData, LanguageData, TrigramData}; use crate::layout::*; use crate::trigram_patterns::TrigramPattern; use crate::utility::*; use crate::weights::{Config, Weights}; const SMALLEST_SCORE: f64 = f64::MIN / 2.0; #[cfg(test)] static ANALYZED_COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); #[derive(Clone, Default)] pub struct TrigramStats { pub alternates: f64, pub alternates_sfs: f64, pub inrolls: f64, pub outrolls: f64, pub onehands: f64, pub redirects: f64, pub redirects_sfs: f64, pub bad_redirects: f64, pub bad_redirects_sfs: f64, pub sfbs: f64, pub bad_sfbs: f64, pub sfts: f64, pub other: f64, pub invalid: f64, } impl std::fmt::Display for TrigramStats { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Inrolls: {:.3}%\n\ Outrolls: {:.3}%\n\ Total Rolls: {:.3}%\n\ Onehands: {:.3}%\n\n\ Alternates: {:.3}%\n\ Alternates (sfs): {:.3}%\n\ Total Alternates: {:.3}%\n\n\ Redirects: {:.3}%\n\ Redirects Sfs: {:.3}%\n\ Bad Redirects: {:.3}%\n\ Bad Redirects Sfs: {:.3}%\n\ Total Redirects: {:.3}%\n\n\ Bad Sfbs: {:.3}%\n\ Sft: {:.3}%\n", self.inrolls * 100.0, self.outrolls * 100.0, (self.inrolls + self.outrolls) * 100.0, self.onehands * 100.0, self.alternates * 100.0, self.alternates_sfs * 100.0, (self.alternates + self.alternates_sfs) * 100.0, self.redirects * 100.0, self.redirects_sfs * 100.0, self.bad_redirects * 100.0, self.bad_redirects_sfs * 100.0, (self.redirects + self.redirects_sfs + self.bad_redirects + self.bad_redirects_sfs) * 100.0, self.bad_sfbs * 100.0, self.sfts * 100.0 ) } } impl std::fmt::Debug for TrigramStats { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Inrolls: {:.3}%\n Outrolls: {:.3}%\n Total Rolls: {:.3}%\n Onehands: {:.3}%\n\n\ Alternates: {:.3}%\n Alternates Sfs: {:.3}%\n Total Alternates: {:.3}%\n\n Redirects: {:.3}%\n\ Redirects Sfs: {:.3}%\n\ Bad Redirects: {:.3}%\n Bad Redirects Sfs: {:.3}%\n\ Total Redirects: {:.3}%\n\n Bad Sfbs: {:.3}%\n Sft: {:.3}%\n\n Other: {:.3}%\n Invalid: {:.3}%", self.inrolls * 100.0, self.outrolls * 100.0, (self.inrolls + self.outrolls) * 100.0, self.onehands * 100.0, self.alternates * 100.0, self.alternates_sfs * 100.0, (self.alternates + self.alternates_sfs) * 100.0, self.redirects * 100.0, self.redirects_sfs * 100.0, self.bad_redirects * 100.0, self.bad_redirects_sfs * 100.0, (self.redirects + self.redirects_sfs + self.bad_redirects + self.bad_redirects_sfs) * 100.0, self.bad_sfbs * 100.0, self.sfts * 100.0, self.other * 100.0, self.invalid * 100.0 ) } } fn format_fspeed(finger_speed: &[f64]) -> String { let mut finger_speed_str: Vec<String> = Vec::new(); for v in finger_speed { finger_speed_str.push(format!("{:.3}", v * 10.0)) } finger_speed_str.join(", ") } #[derive(Clone)] pub struct LayoutStats { pub sfb: f64, pub dsfb: f64, pub dsfb2: f64, pub dsfb3: f64, pub scissors: f64, pub lsbs: f64, pub pinky_ring: f64, pub trigram_stats: TrigramStats, pub fspeed: f64, pub finger_speed: [f64; 8], } impl std::fmt::Display for LayoutStats { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, concat!( "Sfb: {:.3}%\nDsfb: {:.3}%\nFinger Speed: {:.3}\n", " [{}]\nScissors: {:.3}%\nLsbs: {:.3}%\nPinky Ring Bigrams: {:.3}%\n\n{}" ), self.sfb * 100.0, self.dsfb * 100.0, self.fspeed * 10.0, format_fspeed(&self.finger_speed), self.scissors * 100.0, self.lsbs * 100.0, self.pinky_ring * 100.0, self.trigram_stats ) } } #[derive(Default, Debug)] pub struct LayoutCache { effort: [f64; 30], effort_total: f64, scissors: f64, lsbs: f64, pinky_ring: f64, usage: [f64; 8], usage_total: f64, fspeed: [f64; 8], fspeed_total: f64, // trigrams: HashMap<(char, Option<char>), f64>, trigrams_total: f64, total_score: f64, } impl LayoutCache { pub fn total_score(&self) -> f64 { self.trigrams_total - self.scissors - self.lsbs - self.pinky_ring - self.effort_total - self.usage_total - self.fspeed_total } } type PerCharTrigrams = HashMap<[u8; 2], TrigramData>; static COLS: [usize; 6] = [0, 1, 2, 7, 8, 9]; pub(crate) fn pinned_swaps(pins: &[usize]) -> Vec<PosPair> { let mut map = [true; 30]; for (i, m) in map.iter_mut().enumerate() { if pins.contains(&i) { *m = false; } } let mut res = Vec::new(); for ps in POSSIBLE_SWAPS { if map[ps.0] && map[ps.1] { res.push(ps); } } res } pub struct LayoutGeneration { pub language: String, pub data: LanguageData, pub convert_u8: ConvertU8, pub repeat_key: usize, pub chars_for_generation: [u8; 30], pub trigram_precision: usize, fspeed_vals: [(PosPair, f64); 48], effort_map: [f64; 30], scissor_indices: [PosPair; 17], lsb_indices: [PosPair; 16], pinky_ring_indices: [PosPair; 18], weighted_bigrams: BigramData, per_char_trigrams: PerCharTrigrams, pub weights: Weights, pub layouts: IndexMap<String, FastLayout>, } impl LayoutGeneration { pub fn new<P>(language: &str, base_path: P, config: Option<Config>) -> Result<Self> where P: AsRef<Path>, { let config = config.unwrap_or_else(Config::with_loaded_weights); if let Ok(mut data) = LanguageData::from_file(base_path.as_ref().join("language_data"), language) { let chars_fg = data.convert_u8.to(chars_for_generation(language)); let mut chars_for_generation: [u8; 30] = chars_fg.try_into().unwrap(); chars_for_generation.sort_by(|&a, &b| { let a = data.characters.get(a as usize).unwrap_or(&0.0); let b = data.characters.get(b as usize).unwrap_or(&0.0); b.partial_cmp(a).unwrap() }); Ok(Self { language: language.to_string(), chars_for_generation, weighted_bigrams: Self::weighted_bigrams(&data, &config.weights), per_char_trigrams: Self::per_char_trigrams( &data.trigrams, data.characters.len() as u8, config.trigram_precision(), ), convert_u8: data.convert_u8.clone(), repeat_key: data.convert_u8.to_single('@') as usize, trigram_precision: config.trigram_precision(), data, fspeed_vals: get_fspeed(config.weights.lateral_penalty), effort_map: get_effort_map(config.weights.heatmap, config.defaults.keyboard_type), scissor_indices: get_scissor_indices(), lsb_indices: get_lsb_indices(), pinky_ring_indices: get_pinky_ring_indices(), weights: config.weights, layouts: IndexMap::default(), }) } else { anyhow::bail!("Getting language data failed") } } pub fn load_layouts<P>( &mut self, base_directory: P, language: &str, ) -> Result<IndexMap<String, FastLayout>> where P: AsRef<Path>, { let mut res: IndexMap<String, FastLayout> = IndexMap::new(); let language_dir_path = base_directory.as_ref().join(language); if let Ok(paths) = std::fs::read_dir(&language_dir_path) { let valid = paths.flatten().filter(is_kb_file).collect::<Vec<_>>(); // let stats_dir = base_directory.as_ref().join("stats").join(language); // if let Ok(false) = std::fs::try_exists(stats_dir) { // std::fs::create_dir_all(&stats_dir)?; // } for entry in valid { if let Some(name) = layout_name(&entry) { let content = std::fs::read_to_string(entry.path())?; let layout_str = format_layout_str(&content); let layout_bytes = self.convert_u8.to(layout_str.chars()); if let Ok(mut layout) = FastLayout::try_from(layout_bytes.as_slice()) { layout.score = self.score(&layout); res.insert(name, layout); // self.get_layout_stats(&layout); } else { println!("layout {} is not formatted correctly", name); } } } res.sort_by(|_, a, _, b| a.score.partial_cmp(&b.score).unwrap()); } else { std::fs::create_dir(language_dir_path)?; } Ok(res) } pub fn get_layout_stats(&self, layout: &FastLayout) -> LayoutStats { let sfb = self.bigram_percent(layout, "sfbs"); let dsfb = self.bigram_percent(layout, "skipgrams"); let dsfb2 = self.bigram_percent(layout, "skipgrams2"); let dsfb3 = self.bigram_percent(layout, "skipgrams3"); let cache = self.initialize_cache(layout); let fspeed = cache.fspeed_total; let finger_speed = cache.fspeed; let scissors = self.scissor_score(layout) / self.weights.scissors; let lsbs = self.lsb_score(layout) / self.weights.lsbs; let pinky_ring = self.pinky_ring_score(layout) / self.weights.pinky_ring_bigrams; let trigram_stats = self.trigram_stats(layout, usize::MAX); LayoutStats { sfb, dsfb, dsfb2, dsfb3, fspeed, finger_speed, scissors, lsbs, pinky_ring, trigram_stats, } } pub fn bigram_percent(&self, layout: &FastLayout, bigram_type: &str) -> f64 { let data = match bigram_type { "bigram" | "bigrams" | "sfb" | "sfbs" => &self.data.bigrams, "skipgram" | "skipgrams" | "dsfb" | "dsfbs" => &self.data.skipgrams, "skipgram2" | "skipgrams2" | "dsfb2" | "dsfbs2" => &self.data.skipgrams2, "skipgram3" | "skipgrams3" | "dsfb3" | "dsfbs3" => &self.data.skipgrams3, _ => panic!("bigram type {bigram_type} does not exist!"), }; let mut res = 0.0; let len = self.data.characters.len(); for (PosPair(i1, i2), _) in self.fspeed_vals { let c1 = unsafe { layout.cu(i1) } as usize; let c2 = unsafe { layout.cu(i2) } as usize; // if c1 != self.repeat_key && c2 != self.repeat_key { // res += data.get(c1 * len + c2).unwrap_or(&0.0); // res += data.get(c2 * len + c1).unwrap_or(&0.0); // } else { // res += data.get(c1 * len + c2).unwrap_or(&0.0); // res += data.get(c2 * len + c1).unwrap_or(&0.0); // } res += data.get(c1 * len + c2).unwrap_or(&0.0); res += data.get(c2 * len + c1).unwrap_or(&0.0); } res } pub fn sfbs(&self, layout: &FastLayout, top_n: usize) -> Vec<(String, f64)> { self.fspeed_vals .iter() .flat_map(|(p, _)| { let u1 = layout.c(p.0); let u2 = layout.c(p.1); let bigram = self.convert_u8.as_str(&[u1, u2]); let bigram2 = self.convert_u8.as_str(&[u2, u1]); let i = (u1 as usize) * self.data.characters.len() + (u2 as usize); let i2 = (u2 as usize) * self.data.characters.len() + (u1 as usize); let freq = self.data.bigrams[i]; let freq2 = self.data.bigrams[i2]; [(bigram, freq), (bigram2, freq2)] }) .sorted_by(|(_, a), (_, b)| b.partial_cmp(a).unwrap()) .take(top_n) .collect::<Vec<_>>() } pub fn trigram_stats(&self, layout: &FastLayout, trigram_precision: usize) -> TrigramStats { use TrigramPattern::*; let mut freqs = TrigramStats::default(); for (trigram, freq) in self.data.trigrams.iter().take(trigram_precision) { match layout.get_trigram_pattern(trigram) { Alternate => freqs.alternates += freq, AlternateSfs => freqs.alternates_sfs += freq, Inroll => freqs.inrolls += freq, Outroll => freqs.outrolls += freq, Onehand => freqs.onehands += freq, Redirect => freqs.redirects += freq, RedirectSfs => freqs.redirects_sfs += freq, BadRedirect => freqs.bad_redirects += freq, BadRedirectSfs => freqs.bad_redirects_sfs += freq, Sfb => freqs.sfbs += freq, BadSfb => freqs.bad_sfbs += freq, Sft => freqs.sfts += freq, Other => freqs.other += freq, Invalid => freqs.invalid += freq, } } freqs } pub fn score(&self, layout: &FastLayout) -> f64 { let effort = (0..layout.matrix.len()) .map(|i| self.char_effort(layout, i)) .sum::<f64>(); let fspeed_usage = (0..8) .map(|col| self.col_usage(layout, col) + self.col_fspeed(layout, col)) .sum::<f64>(); let scissors = self.scissor_score(layout); let lsbs = self.lsb_score(layout); let pinky_ring = self.pinky_ring_score(layout); let trigram_score = self.trigram_score_iter(layout, &self.data.trigrams); trigram_score - effort - fspeed_usage - scissors - lsbs - pinky_ring } fn weighted_bigrams(data: &LanguageData, weights: &Weights) -> BigramData { let len = data.characters.len(); let chars = 0..len; chars .clone() .cartesian_product(chars) .map(|(c1, c2)| { let bigram = c1 * len + c2; let sfb = data.bigrams.get(bigram).unwrap_or(&0.0); let dsfb = data.skipgrams.get(bigram).unwrap_or(&0.0) * weights.dsfb_ratio; let dsfb2 = data.skipgrams2.get(bigram).unwrap_or(&0.0) * weights.dsfb_ratio2; let dsfb3 = data.skipgrams3.get(bigram).unwrap_or(&0.0) * weights.dsfb_ratio3; (sfb + dsfb + dsfb2 + dsfb3) * weights.fspeed }) .collect() } fn per_char_trigrams( trigrams: &TrigramData, highest: u8, trigram_precision: usize, ) -> PerCharTrigrams { let mut n_trigrams = trigrams.clone(); n_trigrams.truncate(trigram_precision); let thingy: Vec<([u8; 2], TrigramData)> = (0..highest) .cartesian_product(0..highest) .map(|(c1, c2)| { let v1 = n_trigrams .iter() .map(|(t, f)| (*t, *f)) .filter(|(t, _)| t.contains(&c1)) .collect::<Vec<_>>(); let v2 = n_trigrams .iter() .map(|(t, f)| (*t, *f)) .filter(|(t, _)| t.contains(&c2)) .collect::<Vec<_>>(); let (big, small, c) = if v1.len() >= v2.len() { (v1, v2, &c1) } else { (v2, v1, &c2) }; let per_char = big .into_iter() .chain(small.into_iter().filter(|(t, _)| !t.contains(c))) .collect::<Vec<_>>(); ([c1, c2], per_char) }) .collect(); PerCharTrigrams::from_iter(thingy) } #[inline] fn trigram_score_iter<'a, T>(&self, layout: &FastLayout, trigrams: T) -> f64 where T: IntoIterator<Item = &'a ([u8; 3], f64)>, { use TrigramPattern::*; let mut freqs = TrigramStats::default(); for (trigram, freq) in trigrams { match layout.get_trigram_pattern(trigram) { Alternate => freqs.alternates += freq, AlternateSfs => freqs.alternates_sfs += freq, Inroll => freqs.inrolls += freq, Outroll => freqs.outrolls += freq, Onehand => freqs.onehands += freq, Redirect => freqs.redirects += freq, RedirectSfs => freqs.redirects += freq, BadRedirect => freqs.bad_redirects += freq, BadRedirectSfs => freqs.bad_redirects += freq, _ => {} } } let mut score = 0.0; score += self.weights.inrolls * freqs.inrolls; score += self.weights.outrolls * freqs.outrolls; score += self.weights.onehands * freqs.onehands; score += self.weights.alternates * freqs.alternates; score += self.weights.alternates_sfs * freqs.alternates_sfs; score -= self.weights.redirects * freqs.redirects; score -= self.weights.redirects_sfs * freqs.redirects_sfs; score -= self.weights.bad_redirects * freqs.bad_redirects; score -= self.weights.bad_redirects_sfs * freqs.bad_redirects_sfs; score } fn trigram_char_score(&self, layout: &FastLayout, pos: &PosPair) -> f64 { let c1 = unsafe { layout.cu(pos.0) }; let c2 = unsafe { layout.cu(pos.1) }; if let Some(t_vec) = self.per_char_trigrams.get(&[c1, c2]) { self.trigram_score_iter(layout, t_vec) } else { 0.0 } } #[inline] fn scissor_score(&self, layout: &FastLayout) -> f64 { let mut res = 0.0; let len = self.data.characters.len(); for PosPair(i1, i2) in self.scissor_indices { let c1 = unsafe { layout.cu(i1) } as usize; let c2 = unsafe { layout.cu(i2) } as usize; res += self.data.bigrams.get(c1 * len + c2).unwrap_or(&0.0); res += self.data.bigrams.get(c2 * len + c1).unwrap_or(&0.0); } res * self.weights.scissors } #[inline] fn lsb_score(&self, layout: &FastLayout) -> f64 { let mut res = 0.0; let len = self.data.characters.len(); for PosPair(i1, i2) in self.lsb_indices { let c1 = unsafe { layout.cu(i1) } as usize; let c2 = unsafe { layout.cu(i2) } as usize; res += self.data.bigrams.get(c1 * len + c2).unwrap_or(&0.0); res += self.data.bigrams.get(c2 * len + c1).unwrap_or(&0.0); } res * self.weights.lsbs } fn pinky_ring_score(&self, layout: &FastLayout) -> f64 { let mut res = 0.0; let len = self.data.characters.len(); for PosPair(i1, i2) in self.pinky_ring_indices { let c1 = unsafe { layout.cu(i1) } as usize; let c2 = unsafe { layout.cu(i2) } as usize; res += self.data.bigrams.get(c1 * len + c2).unwrap_or(&0.0); res += self.data.bigrams.get(c2 * len + c1).unwrap_or(&0.0); } res * self.weights.pinky_ring_bigrams } fn col_usage(&self, layout: &FastLayout, col: usize) -> f64 { let mut res = 0.0; match col { 0..=2 => { for c in unsafe { [layout.cu(col), layout.cu(col + 10), layout.cu(col + 20)] } { if let Some(v) = self.data.characters.get(c as usize) { res += v; } } } 3 | 4 => { let col = (col - 3) * 2 + 3; for c in unsafe { [ layout.cu(col), layout.cu(col + 10), layout.cu(col + 20), layout.cu(col + 1), layout.cu(col + 11), layout.cu(col + 21), ] } { if let Some(v) = self.data.characters.get(c as usize) { res += v; } } } 5..=7 => { let col = col + 2; for c in unsafe { [layout.cu(col), layout.cu(col + 10), layout.cu(col + 20)] } { if let Some(v) = self.data.characters.get(c as usize) { res += v; } } } _ => unsafe { unreachable_unchecked() }, }; self.weights.max_finger_use.penalty * match col { 0 | 7 => (res - self.weights.max_finger_use.pinky).max(0.0), 1 | 6 => (res - self.weights.max_finger_use.ring).max(0.0), 2 | 5 => (res - self.weights.max_finger_use.middle).max(0.0), 3 | 4 => (res - self.weights.max_finger_use.index).max(0.0), _ => unsafe { unreachable_unchecked() }, } } #[inline] fn pair_fspeed(&self, layout: &FastLayout, pair: &PosPair, dist: f64) -> f64 { let c1 = unsafe { layout.cu(pair.0) } as usize; let c2 = unsafe { layout.cu(pair.1) } as usize; // if c1 != self.repeat_key && c1 != self.repeat_key { // let mut res = 0.0; // let len = self.data.characters.len(); // res += self.weighted_bigrams.get(c1 * len + c2).unwrap_or(&0.0) * dist; // res += self.weighted_bigrams.get(c2 * len + c1).unwrap_or(&0.0) * dist; // res // } else { // let mut res = 0.0; // let len = self.data.characters.len(); // res += self.weighted_bigrams.get(c1 * len + c2).unwrap_or(&0.0) * dist * 0.5; // res += self.weighted_bigrams.get(c2 * len + c1).unwrap_or(&0.0) * dist * 0.5; // res // } let mut res = 0.0; let len = self.data.characters.len(); res += self.weighted_bigrams.get(c1 * len + c2).unwrap_or(&0.0) * dist; res += self.weighted_bigrams.get(c2 * len + c1).unwrap_or(&0.0) * dist; res } #[inline(always)] unsafe fn col_to_start_len(col: usize) -> (usize, usize) { *[ (0, 3), (3, 3), (6, 3), (18, 15), (33, 15), (9, 3), (12, 3), (15, 3), ] .get_unchecked(col) } #[inline] fn col_fspeed(&self, layout: &FastLayout, col: usize) -> f64 { let (start, len) = unsafe { Self::col_to_start_len(col) }; let mut res = 0.0; for i in start..(start + len) { let (pair, dist) = unsafe { self.fspeed_vals.get_unchecked(i) }; res += self.pair_fspeed(layout, pair, *dist); } res } #[inline] fn char_effort(&self, layout: &FastLayout, i: usize) -> f64 { let c = unsafe { layout.cu(i) }; match self.data.characters.get(c as usize) { Some(&v) => v * unsafe { self.effort_map.get_unchecked(i) }, None => 0.0, } } pub fn initialize_cache(&self, layout: &FastLayout) -> LayoutCache { #[cfg(test)] ANALYZED_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); let mut res = LayoutCache::default(); for i in 0..layout.matrix.len() { res.effort[i] = self.char_effort(layout, i); } res.effort_total = res.effort.iter().sum(); for col in 0..8 { res.usage[col] = self.col_usage(layout, col); res.fspeed[col] = self.col_fspeed(layout, col) } res.usage_total = res.usage.iter().sum(); res.fspeed_total = res.fspeed.iter().sum(); res.scissors = self.scissor_score(layout); res.lsbs = self.lsb_score(layout); res.pinky_ring = self.pinky_ring_score(layout); res.trigrams_total = self.trigram_score_iter( layout, self.data.trigrams.iter().take(self.trigram_precision), ); res.total_score = res.total_score(); res } pub fn score_swap_cached( &self, layout: &mut FastLayout, swap: &PosPair, cache: &LayoutCache, ) -> Option<f64> { let PosPair(i1, i2) = *swap; if layout.c(i1) == layout.c(i2) || (self.data.characters[i1] == 0.0 && self.data.characters[i2] == 0.0) { return None; } unsafe { layout.swap_no_bounds(swap) }; let col1 = I_TO_COL[i1]; let col2 = I_TO_COL[i2]; let fspeed_score = if col1 == col2 { let fspeed = self.col_fspeed(layout, col1); cache.fspeed_total - cache.fspeed[col1] + fspeed } else { let fspeed1 = self.col_fspeed(layout, col1); let fspeed2 = self.col_fspeed(layout, col2); cache.fspeed_total - cache.fspeed[col1] - cache.fspeed[col2] + fspeed1 + fspeed2 }; let usage_score = if col1 == col2 { let usage = self.col_usage(layout, col1); cache.usage_total - cache.usage[col1] + usage } else { let usage1 = self.col_usage(layout, col1); let usage2 = self.col_usage(layout, col2); cache.usage_total - cache.usage[col1] - cache.usage[col2] + usage1 + usage2 }; let effort1 = self.char_effort(layout, i1); let effort2 = self.char_effort(layout, i2); let effort_score = cache.effort_total - cache.effort[i1] - cache.effort[i2] + effort1 + effort2; let scissors_score = if swap.affects_scissor() { self.scissor_score(layout) } else { cache.scissors }; let lsbs_score = if swap.affects_lsb() { self.lsb_score(layout) } else { cache.lsbs }; let pinky_ring_score = if swap.affects_pinky_ring() { self.pinky_ring_score(layout) } else { cache.pinky_ring }; let trigrams_score = { let trigrams_end = self.trigram_char_score(layout, swap); unsafe { layout.swap_no_bounds(swap) }; let trigrams_start = self.trigram_char_score(layout, swap); cache.trigrams_total - trigrams_start + trigrams_end }; Some( trigrams_score - scissors_score - lsbs_score - pinky_ring_score - effort_score - usage_score - fspeed_score, ) } pub fn accept_swap(&self, layout: &mut FastLayout, swap: &PosPair, cache: &mut LayoutCache) { let PosPair(i1, i2) = *swap; if layout.c(i1) == layout.c(i2) || (self.data.characters[i1] == 0.0 && self.data.characters[i2] == 0.0) { return; } let trigrams_start = self.trigram_char_score(layout, swap); unsafe { layout.swap_no_bounds(swap) }; let col1 = I_TO_COL[i1]; let col2 = I_TO_COL[i2]; cache.fspeed_total = if col1 == col2 { let fspeed = self.col_fspeed(layout, col1); let total = cache.fspeed_total - cache.fspeed[col1] + fspeed; cache.fspeed[col1] = fspeed; total } else { let fspeed1 = self.col_fspeed(layout, col1); let fspeed2 = self.col_fspeed(layout, col2); let total = cache.fspeed_total - cache.fspeed[col1] - cache.fspeed[col2] + fspeed1 + fspeed2; cache.fspeed[col1] = fspeed1; cache.fspeed[col2] = fspeed2; total }; cache.usage_total = if col1 == col2 { let usage = self.col_usage(layout, col1); let total = cache.usage_total - cache.usage[col1] + usage; cache.usage[col1] = usage; total } else { let usage1 = self.col_usage(layout, col1); let usage2 = self.col_usage(layout, col2); let total = cache.usage_total - cache.usage[col1] - cache.usage[col2] + usage1 + usage2; cache.usage[col1] = usage1; cache.usage[col2] = usage2; total }; let effort1 = self.char_effort(layout, i1); let effort2 = self.char_effort(layout, i2); cache.effort_total = cache.effort_total - cache.effort[i1] - cache.effort[i2] + effort1 + effort2; cache.effort[i1] = effort1; cache.effort[i2] = effort2; let trigrams_end = self.trigram_char_score(layout, swap); cache.trigrams_total = cache.trigrams_total - trigrams_start + trigrams_end; if swap.affects_scissor() { cache.scissors = self.scissor_score(layout); } if swap.affects_lsb() { cache.lsbs = self.lsb_score(layout); } if swap.affects_pinky_ring() { cache.pinky_ring = self.pinky_ring_score(layout); } cache.total_score = cache.total_score(); } pub fn best_swap_cached( &self, layout: &mut FastLayout, cache: &LayoutCache, current_best_score: Option<f64>, possible_swaps: &[PosPair], ) -> (Option<PosPair>, f64) { let mut best_score = current_best_score.unwrap_or(SMALLEST_SCORE); let mut best_swap: Option<PosPair> = None; for swap in possible_swaps { if let Some(score) = self.score_swap_cached(layout, swap, cache) { if score > best_score { best_score = score; best_swap = Some(*swap); } } } (best_swap, best_score) } fn optimize_cached( &self, layout: &mut FastLayout, cache: &mut LayoutCache, possible_swaps: &[PosPair], ) -> f64 { let mut max_swaps = 200; // too high, but makes the system cut off after a while let mut current_best_score = SMALLEST_SCORE; while let (Some(best_swap), new_score) = self.best_swap_cached(layout, cache, Some(current_best_score), possible_swaps) { current_best_score = new_score; self.accept_swap(layout, &best_swap, cache); max_swaps -= 1; if max_swaps == 0 { return current_best_score; } } current_best_score } fn optimize_cols(&self, layout: &mut FastLayout, cache: &mut LayoutCache, score: Option<f64>) { let mut best_score = score.unwrap_or(cache.total_score); let mut best = layout.clone(); self.col_perms(layout, &mut best, cache, &mut best_score, 6); layout.swap_indexes(); self.col_perms(layout, &mut best, cache, &mut best_score, 6); *layout = best; layout.score = best_score; } fn col_perms( &self, layout: &mut FastLayout, best: &mut FastLayout, cache: &mut LayoutCache, best_score: &mut f64, k: usize, ) { if k == 1 { let new_score = cache.total_score; if new_score > *best_score { *best_score = new_score; *best = layout.clone(); } return; } (0..k).for_each(|i| { self.col_perms(layout, best, cache, best_score, k - 1); if k % 2 == 0 { self.accept_swap(layout, &PosPair(COLS[i], COLS[k - 1]), cache); } else { self.accept_swap(layout, &PosPair(COLS[0], COLS[k - 1]), cache); } }); } pub fn generate(&self) -> FastLayout { let layout = FastLayout::random(self.chars_for_generation); let mut cache = self.initialize_cache(&layout); let mut layout = self.optimize(layout, &mut cache, &POSSIBLE_SWAPS);
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
true
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/weights.rs
oxeylyzer-core/src/weights.rs
use crate::utility::KeyboardType; use serde::Deserialize; use std::fs::File; use std::io::Read; #[derive(Deserialize, Debug)] pub struct WeightDefaultsLoad { pub language: String, pub keyboard_type: String, pub trigram_precision: usize, pub max_cores: usize, } #[derive(Deserialize, Debug, Clone, Default)] pub struct WeightDefaults { pub language: String, pub keyboard_type: KeyboardType, pub trigram_precision: usize, pub max_cores: usize, } #[derive(Deserialize, Clone, Debug, Default)] pub struct MaxFingerUse { pub penalty: f64, pub pinky: f64, pub ring: f64, pub middle: f64, pub index: f64, } #[derive(Deserialize, Clone, Debug, Default)] pub struct Weights { pub heatmap: f64, pub lateral_penalty: f64, pub fspeed: f64, pub dsfb_ratio: f64, #[serde(default)] pub dsfb_ratio2: f64, #[serde(default)] pub dsfb_ratio3: f64, pub scissors: f64, pub lsbs: f64, pub pinky_ring_bigrams: f64, pub inrolls: f64, pub outrolls: f64, pub onehands: f64, pub alternates: f64, pub alternates_sfs: f64, pub redirects: f64, pub redirects_sfs: f64, pub bad_redirects: f64, pub bad_redirects_sfs: f64, pub max_finger_use: MaxFingerUse, } #[derive(Deserialize)] struct ConfigLoad { pub pins: String, pub defaults: WeightDefaultsLoad, pub weights: Weights, } impl ConfigLoad { pub fn load() -> Self { let mut f = File::open("config.toml").expect("The config.toml is missing! Help!"); let mut buf = String::new(); f.read_to_string(&mut buf) .expect("Failed to read config.toml for some reason"); let mut res: Self = toml::from_str(&buf).expect("Failed to parse config.toml. Values might be missing."); res.pins = res.pins.trim().replace([' ', '\n'], ""); res } } #[derive(Debug, Clone, Default)] pub struct Config { pub pins: Vec<usize>, pub defaults: WeightDefaults, pub weights: Weights, } impl Config { pub fn with_loaded_weights() -> Self { let mut load = ConfigLoad::load(); load.weights.max_finger_use = MaxFingerUse { penalty: load.weights.max_finger_use.penalty, pinky: load.weights.max_finger_use.pinky / 100.0, ring: load.weights.max_finger_use.ring / 100.0, middle: load.weights.max_finger_use.middle / 100.0, index: load.weights.max_finger_use.index / 100.0, }; let mut pins = Vec::new(); for (i, c) in load.pins.chars().enumerate() { if c == 'x' { pins.push(i); } } load.weights.dsfb_ratio2 = load.weights.dsfb_ratio.powi(2); load.weights.dsfb_ratio3 = load.weights.dsfb_ratio.powi(3); Self { pins, defaults: WeightDefaults { language: load.defaults.language, keyboard_type: KeyboardType::try_from(load.defaults.keyboard_type) .unwrap_or(KeyboardType::AnsiAngle), trigram_precision: load.defaults.trigram_precision, max_cores: load.defaults.max_cores, }, weights: load.weights, } } pub fn with_defaults() -> Self { Self { defaults: WeightDefaults { language: "english".to_string(), keyboard_type: KeyboardType::AnsiAngle, trigram_precision: 100000, max_cores: 128, }, weights: Weights { heatmap: 0.85, lateral_penalty: 1.3, fspeed: 8.0, dsfb_ratio: 0.12, dsfb_ratio2: (0.10 * 6.0f64).powi(2), dsfb_ratio3: (0.08 * 6.0f64).powi(3), scissors: 5.0, lsbs: 2.0, pinky_ring_bigrams: 0.0, inrolls: 1.6, outrolls: 1.3, onehands: 0.8, alternates: 0.7, alternates_sfs: 0.35, redirects: 1.5, redirects_sfs: 2.75, bad_redirects: 4.0, bad_redirects_sfs: 6.0, max_finger_use: MaxFingerUse { penalty: 2.5, pinky: 9.0, ring: 16.0, middle: 19.5, index: 18.0, }, }, pins: Vec::new(), } } pub fn trigram_precision(&self) -> usize { self.defaults.trigram_precision } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/trigram_patterns.rs
oxeylyzer-core/src/trigram_patterns.rs
#[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum TrigramPattern { Alternate, AlternateSfs, Inroll, Outroll, Onehand, Redirect, RedirectSfs, BadRedirect, BadRedirectSfs, Sfb, BadSfb, Sft, Other, Invalid, } #[repr(u8)] #[derive(Copy, Clone, Debug)] enum Hand { Left, Right, } use Hand::*; impl std::ops::Not for Hand { type Output = Self; fn not(self) -> Self::Output { match self { Left => Right, Right => Left, } } } impl From<Finger> for Hand { fn from(value: Finger) -> Self { value.hand() } } #[repr(u8)] #[derive(Copy, Clone, Debug)] pub enum Finger { LP, LR, LM, LI, RI, RM, RR, RP, LT, RT, } use Finger::*; impl std::fmt::Display for Finger { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let to_write = match self { LP => "left pinky", LR => "left ring", LM => "left middle", LI => "left index", RI => "right index", RM => "right middle", RR => "right ring", RP => "right pinky", LT => "left thumb", RT => "right thumb", }; write!(f, "{}", to_write) } } impl Finger { pub const fn eq(self, other: Self) -> bool { self as u8 == other as u8 } pub const fn gt(self, other: Self) -> bool { self as u8 > other as u8 } pub const fn lt(self, other: Self) -> bool { (self as u8) < (other as u8) } const fn hand(&self) -> Hand { match self { LP | LR | LM | LI | LT => Left, _ => Right, } } const fn is_bad(&self) -> bool { matches!(self, LP | LR | LM | RM | RR | RP) } pub const fn from_usize(value: usize) -> Self { match value { 0 => LP, 1 => LR, 2 => LM, 3 => LI, 4 => RI, 5 => RM, 6 => RR, 7 => RP, 8 => LT, 9 => RT, _ => unreachable!(), } } } #[derive(Debug)] pub(crate) struct Trigram { f1: Finger, f2: Finger, f3: Finger, h1: Hand, h2: Hand, h3: Hand, } impl std::fmt::Display for Trigram { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}, {}, {}", self.f1, self.f2, self.f3) } } impl Trigram { const fn new(f1: Finger, f2: Finger, f3: Finger) -> Self { Trigram { f1, f2, f3, h1: f1.hand(), h2: f2.hand(), h3: f3.hand(), } } const fn is_alt(&self) -> bool { matches!( (self.h1, self.h2, self.h3), (Left, Right, Left) | (Right, Left, Right) ) } const fn is_sfs(&self) -> bool { self.f1.eq(self.f3) } const fn get_alternate(&self) -> TrigramPattern { use TrigramPattern::*; match self.is_sfs() { true => AlternateSfs, false => Alternate, } } const fn is_roll(&self) -> bool { #[allow(clippy::match_like_matches_macro)] match (self.h1, self.h2, self.h3) { (Left, Left, Right) => true, (Right, Left, Left) => true, (Right, Right, Left) => true, (Left, Right, Right) => true, _ => false, } } const fn is_inroll(&self) -> bool { match (self.h1, self.h2, self.h3) { (Left, Left, Right) => self.f1.lt(self.f2), (Right, Left, Left) => self.f2.lt(self.f3), (Right, Right, Left) => self.f1.gt(self.f2), (Left, Right, Right) => self.f2.gt(self.f3), _ => unreachable!(), } } const fn get_roll(&self) -> TrigramPattern { use TrigramPattern::*; match self.is_inroll() { true => Inroll, false => Outroll, } } const fn on_one_hand(&self) -> bool { matches!( (self.h1, self.h2, self.h3), (Left, Left, Left) | (Right, Right, Right) ) } const fn is_redir(&self) -> bool { (self.f1.lt(self.f2) == self.f2.gt(self.f3)) && self.on_one_hand() } const fn is_bad_redir(&self) -> bool { self.is_redir() && self.f1.is_bad() && self.f2.is_bad() && self.f3.is_bad() } const fn has_sfb(&self) -> bool { self.f1.eq(self.f2) || self.f2.eq(self.f3) } const fn is_sft(&self) -> bool { self.f1.eq(self.f2) && self.f2.eq(self.f3) } const fn get_one_hand(&self) -> TrigramPattern { use TrigramPattern::*; if self.is_sft() { Sft } else if self.has_sfb() { BadSfb } else if self.is_redir() { match (self.is_sfs(), self.is_bad_redir()) { (false, false) => Redirect, (false, true) => BadRedirect, (true, false) => RedirectSfs, (true, true) => BadRedirectSfs, } } else { Onehand } } const fn get_trigram_pattern(&self) -> TrigramPattern { if self.is_alt() { self.get_alternate() } else if self.on_one_hand() { self.get_one_hand() } else if self.has_sfb() { TrigramPattern::Sfb } else if self.is_roll() { self.get_roll() } else { TrigramPattern::Other } } } const fn get_trigram_combinations() -> [TrigramPattern; 512] { let mut combinations: [TrigramPattern; 512] = [TrigramPattern::Other; 512]; let mut c3 = 0; while c3 < 8 { let mut c2 = 0; while c2 < 8 { let mut c1 = 0; while c1 < 8 { let index = c3 * 64 + c2 * 8 + c1; let trigram = Trigram::new( Finger::from_usize(c3), Finger::from_usize(c2), Finger::from_usize(c1), ); combinations[index] = trigram.get_trigram_pattern(); c1 += 1; } c2 += 1; } c3 += 1; } combinations } pub static TRIGRAM_COMBINATIONS: [TrigramPattern; 512] = get_trigram_combinations(); #[cfg(test)] mod tests { use super::{TrigramPattern::*, *}; use crate::*; use layout::{FastLayout, Layout}; use once_cell::sync::Lazy; use utility::ConvertU8; static CON: Lazy<ConvertU8> = Lazy::new(|| ConvertU8::with_chars("abcdefghijklmnopqrstuvwxyz',.;")); #[test] fn is_alt() { let t1 = Trigram::new(LR, LM, LI); let t2 = Trigram::new(LR, RP, LI); let t3 = Trigram::new(RM, LM, RM); assert!(!t1.is_alt()); assert!(t2.is_alt()); assert!(t3.is_alt()); } #[test] fn rolls() { let t1 = Trigram::new(LR, LM, RR); let t2 = Trigram::new(RR, LR, LM); let t3 = Trigram::new(LM, LR, RR); let t4 = Trigram::new(RR, LM, LR); let t5 = Trigram::new(LP, RI, RM); assert!(!(t1.on_one_hand() || t1.is_alt() || t1.has_sfb())); assert!(!(t2.on_one_hand() || t2.is_alt() || t2.has_sfb())); assert!(!(t3.on_one_hand() || t3.is_alt() || t3.has_sfb())); assert!(!(t4.on_one_hand() || t4.is_alt() || t4.has_sfb())); assert!(!(t5.on_one_hand() || t5.is_alt() || t5.has_sfb())); assert!(t1.is_roll()); assert!(t2.is_roll()); assert!(t3.is_roll()); assert!(t4.is_roll()); assert!(t5.is_roll()); assert!(t1.is_inroll()); assert!(t2.is_inroll()); assert!(!t3.is_inroll()); assert!(!t4.is_inroll()); assert!(!t5.is_inroll()); assert_eq!(t1.get_roll(), Inroll); assert_eq!(t2.get_roll(), Inroll); assert_eq!(t3.get_roll(), Outroll); assert_eq!(t4.get_roll(), Outroll); assert_eq!(t5.get_roll(), Outroll); } #[test] fn redirs() { let t1 = Trigram::new(LR, LI, LM); let t2 = Trigram::new(LM, LI, LR); let t3 = Trigram::new(RR, RI, RM); let t4 = Trigram::new(RM, RI, RR); assert!(t1.is_redir()); assert!(t2.is_redir()); assert!(t3.is_redir()); assert!(t4.is_redir()); assert!(!t1.is_sfs()); assert!(!t2.is_sfs()); assert!(!t3.is_sfs()); assert!(!t4.is_sfs()); assert!(!t1.is_bad_redir()); assert!(!t2.is_bad_redir()); assert!(!t3.is_bad_redir()); assert!(!t4.is_bad_redir()); let t1 = Trigram::new(LP, LI, LP); let t2 = Trigram::new(LI, LP, LI); let t3 = Trigram::new(RI, RR, RI); let t4 = Trigram::new(RR, RI, RR); assert!(t1.is_redir()); assert!(t2.is_redir()); assert!(t3.is_redir()); assert!(t4.is_redir()); assert!(t1.is_sfs()); assert!(t2.is_sfs()); assert!(t3.is_sfs()); assert!(t4.is_sfs()); assert!(!t1.is_bad_redir()); assert!(!t2.is_bad_redir()); assert!(!t3.is_bad_redir()); assert!(!t4.is_bad_redir()); let t1 = Trigram::new(LR, LP, LM); let t2 = Trigram::new(LM, LP, LR); let t3 = Trigram::new(RR, RP, RM); let t4 = Trigram::new(RM, RP, RR); assert!(t1.is_redir()); assert!(t2.is_redir()); assert!(t3.is_redir()); assert!(t4.is_redir()); assert!(!t1.is_sfs()); assert!(!t2.is_sfs()); assert!(!t3.is_sfs()); assert!(!t4.is_sfs()); assert!(t1.is_bad_redir()); assert!(t2.is_bad_redir()); assert!(t3.is_bad_redir()); assert!(t4.is_bad_redir()); let t1 = Trigram::new(LP, LR, LP); let t2 = Trigram::new(LR, LP, LR); let t3 = Trigram::new(RM, RR, RM); let t4 = Trigram::new(RR, RM, RR); assert!(t1.is_redir()); assert!(t2.is_redir()); assert!(t3.is_redir()); assert!(t4.is_redir()); assert!(t1.is_sfs()); assert!(t2.is_sfs()); assert!(t3.is_sfs()); assert!(t4.is_sfs()); assert!(t1.is_bad_redir()); assert!(t2.is_bad_redir()); assert!(t3.is_bad_redir()); assert!(t4.is_bad_redir()); } #[test] fn trigram_combinations() { let dvorak_bytes = CON.to_lossy("',.pyfgcrlaoeuidhtns;qjkxbmwvz".chars()); let dvorak = FastLayout::try_from(dvorak_bytes.as_slice()).expect("couldn't create dvorak"); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['h', 'o', 't'])), Alternate ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['l', 'o', 'w'])), Alternate ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['l', 'a', 'z'])), AlternateSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['i', 'r', 'k'])), AlternateSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['a', 'b', 'c'])), Outroll ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['u', '\'', 'v'])), Outroll ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['t', 'h', 'e'])), Inroll ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['o', 'u', 't'])), Inroll ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['r', 't', 'h'])), Onehand ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['h', 't', 'r'])), Onehand ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['o', 'e', 'u'])), Onehand ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy([';', '.', 'x'])), Onehand ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['r', 'd', 's'])), Redirect ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['f', 'n', 'w'])), Redirect ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['c', 'b', 't'])), RedirectSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['t', 'b', 'c'])), RedirectSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['d', 's', 'f'])), RedirectSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['r', 't', 's'])), BadRedirect ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['s', 't', 'r'])), BadRedirect ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['a', 'j', 'a'])), BadRedirectSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['j', 'a', 'j'])), BadRedirectSfs ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['g', 'h', 't'])), BadSfb ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['u', 'p', '.'])), BadSfb ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['p', 'u', 'k'])), Sft ); assert_eq!( dvorak.get_trigram_pattern(&CON.to_trigram_lossy(['n', 'v', 'r'])), Sft ); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/generate/michaelll.rs
oxeylyzer-core/src/generate/michaelll.rs
use crate::{ generate::LayoutGeneration, utility::*, layout::* }; const ALGORITHM_ROUNDS: usize = 16; const CHANCE_TO_USE_PREVIOUS_LAYOUT: f64 = 0.2; const RUNS_BEFORE_CHANCE_INC: usize = 1; const RUNS_BEFORE_SWAPS_INC: usize = 1; const RUNS_BEFORE_GTB_ROUNDS_INC: usize = 4; const GTB_ROUNDS: usize = 1; const MAX_RUNS: usize = usize::MAX; const CHANCE_EXPONENTIATOR: f64 = 0.9; struct ThreadArg { bestk: FastLayout, num_rounds: usize, chance_to_use_previous_layout: f64, number_of_swaps: usize, num_threads: usize, is_finished: bool } impl ThreadArg { pub fn new(available_chars: [char; 30]) -> Self { ThreadArg { bestk: FastLayout::random(available_chars), num_rounds: ALGORITHM_ROUNDS, chance_to_use_previous_layout: CHANCE_TO_USE_PREVIOUS_LAYOUT, number_of_swaps: available_chars.len() / 15, num_threads: 0, is_finished: false } } } impl LayoutGeneration { pub fn optimize_dickens(&self, possible_swaps: &[PosPair]) { } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/generate/obsolete.rs
oxeylyzer-core/src/generate/obsolete.rs
use crate::{generate::LayoutGeneration, layout::*, utility::*}; impl LayoutGeneration { #[allow(dead_code)] pub(crate) fn score_with_precision( &self, layout: &FastLayout, trigram_precision: usize, ) -> f64 { let effort = (0..layout.matrix.len()) .map(|i| self.char_effort(layout, i)) .sum::<f64>(); let fspeed_usage = (0..8) .map(|col| self.col_usage(layout, col) + self.col_fspeed(layout, col)) .sum::<f64>(); let scissors = self.scissor_score(layout); let lsbs = self.lsb_score(layout); let pinky_ring = self.pinky_ring_score(layout); let trigram_iter = self.data.trigrams.iter().take(trigram_precision); let trigram_score = self.trigram_score_iter(layout, trigram_iter); trigram_score - effort - fspeed_usage - scissors - lsbs - pinky_ring } #[allow(dead_code)] fn col_fspeed_before(&self, layout: &FastLayout, col: usize) -> f64 { let (start, len) = unsafe { Self::col_to_start_len(col) }; let mut res = 0.0; let dsfb_ratio = self.weights.dsfb_ratio; let dsfb_ratio2 = self.weights.dsfb_ratio2; let dsfb_ratio3 = self.weights.dsfb_ratio3; for i in start..(start + len) { let (PosPair(i1, i2), dist) = self.fspeed_vals[i]; let c1 = unsafe { layout.cu(i1) } as usize; let c2 = unsafe { layout.cu(i2) } as usize; let (pair, rev) = (c1 * len + c2, c2 * len + c1); res += self.data.bigrams.get(pair).unwrap_or(&0.0) * dist; res += self.data.bigrams.get(rev).unwrap_or(&0.0) * dist; res += self.data.skipgrams.get(pair).unwrap_or(&0.0) * dist * dsfb_ratio; res += self.data.skipgrams.get(rev).unwrap_or(&0.0) * dist * dsfb_ratio; res += self.data.skipgrams2.get(pair).unwrap_or(&0.0) * dist * dsfb_ratio2; res += self.data.skipgrams2.get(rev).unwrap_or(&0.0) * dist * dsfb_ratio2; res += self.data.skipgrams3.get(pair).unwrap_or(&0.0) * dist * dsfb_ratio3; res += self.data.skipgrams3.get(rev).unwrap_or(&0.0) * dist * dsfb_ratio3; } res * self.weights.fspeed } #[allow(dead_code)] pub(crate) fn score_swap(&self, layout: &mut FastLayout, swap: &PosPair) -> f64 { unsafe { layout.swap_no_bounds(swap) }; let score = self.score_with_precision(layout, self.trigram_precision); unsafe { layout.swap_no_bounds(swap) }; score } #[allow(dead_code)] pub(crate) fn best_swap( &self, layout: &mut FastLayout, current_best_score: Option<f64>, possible_swaps: &[PosPair], ) -> (Option<PosPair>, f64) { let mut best_score = current_best_score.unwrap_or(f64::MIN / 2.0); let mut best_swap = None; for swap in possible_swaps.iter() { let current = self.score_swap(layout, swap); if current > best_score { best_score = current; best_swap = Some(*swap); } } (best_swap, best_score) } #[allow(dead_code)] pub(crate) fn optimize_normal_no_cols( &self, mut layout: FastLayout, possible_swaps: &[PosPair], ) -> FastLayout { let mut current_best_score = f64::MIN / 2.0; while let (Some(best_swap), new_score) = self.best_swap(&mut layout, Some(current_best_score), possible_swaps) { current_best_score = new_score; unsafe { layout.swap_no_bounds(&best_swap) }; } layout } #[allow(dead_code)] pub(crate) fn effort_score(&self, layout: &FastLayout) -> f64 { (0..layout.matrix.len()) .map(|i| self.char_effort(layout, i)) .sum() } #[allow(dead_code)] pub(crate) fn usage_score(&self, layout: &FastLayout) -> f64 { (0..8).map(|i| self.col_usage(layout, i)).sum() } #[allow(dead_code)] pub(crate) fn fspeed_score(&self, layout: &FastLayout) -> f64 { (0..8).map(|i| self.col_fspeed(layout, i)).sum() } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/generate/iterative.rs
oxeylyzer-core/src/generate/iterative.rs
use crate::{ utility::*, generate::{LayoutGeneration, pinned_swaps}, layout::{FastLayout, Layout} }; use rayon::iter::{ParallelIterator, IntoParallelIterator}; impl LayoutGeneration { pub fn gen_iteratively(&self) { let mut pins = Vec::<usize>::with_capacity(30); let mut best = FastLayout::random(self.chars_for_generation); for i in 0..30 { println!("step: {}/30, pinned: '{}'", i+1, pins.iter().map(|i| best.c(*i)).collect::<String>()); println!("indexes pinned: {pins:?}"); println!("updated best:\n{best}\nscore: {}\n", best.score); let possible_swaps = pinned_swaps(&pins); let layouts = (0..250) .into_par_iter() .map(|_| { let l = FastLayout::random_pins(best.matrix, &pins); let mut cache = self.initialize_cache(&l); self.optimize(l, &mut cache, &possible_swaps) }) .collect::<Vec<_>>(); best = layouts.into_iter().max_by(|a, b| a.score.partial_cmp(&b.score).unwrap_or(std::cmp::Ordering::Less) ).unwrap(); let new_pin = best.matrix.iter() .position(|&c| c == self.chars_for_generation[i]) .unwrap(); pins.push(new_pin); } println!("best:\n{best}\nscore: {}", best.score); } } #[cfg(test)] mod tests { use crate::generate::LayoutGeneration; #[test] fn iterative() { let gen = LayoutGeneration::new("english", "static", None).unwrap(); gen.gen_iteratively(); } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
o-x-e-y/oxeylyzer
https://github.com/o-x-e-y/oxeylyzer/blob/d6b1fa0cb80cfa21f1bafd736d783107aacca0bf/oxeylyzer-core/src/generate/desshaw.rs
oxeylyzer-core/src/generate/desshaw.rs
use crate::{ utility::*, generate::LayoutGeneration, layout::FastLayout }; use arrayvec::ArrayVec; use ahash::AHashMap as HashMap; trait LayoutHeuristic { fn evaluate(incomplete: IncompleteLayout); } #[derive(Default)] struct IncompleteLayout { layout: FastLayout, chars_to_place: [char; 30], optimal_positions: [usize; 30], best_scores: [f64; 30], chars_placed: usize } impl IncompleteLayout { pub fn new(layout: FastLayout, chars_to_use: [char; 30]) -> Self { Self { layout, chars_to_place: chars_to_use, chars_placed: 0, ..Default::default() } } pub fn add_char(&mut self, i: usize) { let c = self.chars_to_place[self.chars_placed]; self.chars_placed += 1; self.layout.matrix[i] = c; self.layout.char_to_finger.insert(c, I_TO_COL[i]); } pub fn remove_char(&mut self, c: char) { let i = *self.layout.char_to_finger.get(&c).unwrap(); self.layout.matrix[i] = ' '; self.chars_placed -= 1; } } impl LayoutGeneration { pub fn desshaw(&self, smie: &mut IncompleteLayout) { for i in 0..30 { smie.add_char(i); if smie.chars_placed == 1 { let score = self.char_effort(&smie.layout, i); if score < 0.0 {} } } } }
rust
Apache-2.0
d6b1fa0cb80cfa21f1bafd736d783107aacca0bf
2026-01-04T20:23:49.059116Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/consts.rs
arkworks4/src/consts.rs
use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_p1, blst_p2}; use crate::kzg_types::{ArkG1, ArkG2}; /** The G1 identity/infinity */ #[rustfmt::skip] pub const G1_IDENTITY: ArkG1 = ArkG1::from_blst_p1( blst_p1 { x: blst_fp { l: [0, 0, 0, 0, 0, 0], }, y: blst_fp { l: [0, 0, 0, 0, 0, 0], }, z: blst_fp { l: [0, 0, 0, 0, 0, 0], }, }); pub const SCALE_FACTOR: u64 = 5; pub const NUM_ROOTS: usize = 32; #[rustfmt::skip] pub const SCALE2_ROOT_OF_UNITY: [[u64; 4]; 32] = [ [0x0000000000000001, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000], [0xffffffff00000000, 0x53bda402fffe5bfe, 0x3339d80809a1d805, 0x73eda753299d7d48], [0x0001000000000000, 0xec03000276030000, 0x8d51ccce760304d0, 0x0000000000000000], [0x7228fd3397743f7a, 0xb38b21c28713b700, 0x8c0625cd70d77ce2, 0x345766f603fa66e7], [0x53ea61d87742bcce, 0x17beb312f20b6f76, 0xdd1c0af834cec32c, 0x20b1ce9140267af9], [0x360c60997369df4e, 0xbf6e88fb4c38fb8a, 0xb4bcd40e22f55448, 0x50e0903a157988ba], [0x8140d032f0a9ee53, 0x2d967f4be2f95155, 0x14a1e27164d8fdbd, 0x45af6345ec055e4d], [0x5130c2c1660125be, 0x98d0caac87f5713c, 0xb7c68b4d7fdd60d0, 0x6898111413588742], [0x4935bd2f817f694b, 0x0a0865a899e8deff, 0x6b368121ac0cf4ad, 0x4f9b4098e2e9f12e], [0x4541b8ff2ee0434e, 0xd697168a3a6000fe, 0x39feec240d80689f, 0x095166525526a654], [0x3c28d666a5c2d854, 0xea437f9626fc085e, 0x8f4de02c0f776af3, 0x325db5c3debf77a1], [0x4a838b5d59cd79e5, 0x55ea6811be9c622d, 0x09f1ca610a08f166, 0x6d031f1b5c49c834], [0xe206da11a5d36306, 0x0ad1347b378fbf96, 0xfc3e8acfe0f8245f, 0x564c0a11a0f704f4], [0x6fdd00bfc78c8967, 0x146b58bc434906ac, 0x2ccddea2972e89ed, 0x485d512737b1da3d], [0x034d2ff22a5ad9e1, 0xae4622f6a9152435, 0xdc86b01c0d477fa6, 0x56624634b500a166], [0xfbd047e11279bb6e, 0xc8d5f51db3f32699, 0x483405417a0cbe39, 0x3291357ee558b50d], [0xd7118f85cd96b8ad, 0x67a665ae1fcadc91, 0x88f39a78f1aeb578, 0x2155379d12180caa], [0x08692405f3b70f10, 0xcd7f2bd6d0711b7d, 0x473a2eef772c33d6, 0x224262332d8acbf4], [0x6f421a7d8ef674fb, 0xbb97a3bf30ce40fd, 0x652f717ae1c34bb0, 0x2d3056a530794f01], [0x194e8c62ecb38d9d, 0xad8e16e84419c750, 0xdf625e80d0adef90, 0x520e587a724a6955], [0xfece7e0e39898d4b, 0x2f69e02d265e09d9, 0xa57a6e07cb98de4a, 0x03e1c54bcb947035], [0xcd3979122d3ea03a, 0x46b3105f04db5844, 0xc70d0874b0691d4e, 0x47c8b5817018af4f], [0xc6e7a6ffb08e3363, 0xe08fec7c86389bee, 0xf2d38f10fbb8d1bb, 0x0abe6a5e5abcaa32], [0x5616c57de0ec9eae, 0xc631ffb2585a72db, 0x5121af06a3b51e3c, 0x73560252aa0655b2], [0x92cf4deb77bd779c, 0x72cf6a8029b7d7bc, 0x6e0bcd91ee762730, 0x291cf6d68823e687], [0xce32ef844e11a51e, 0xc0ba12bb3da64ca5, 0x0454dc1edc61a1a3, 0x019fe632fd328739], [0x531a11a0d2d75182, 0x02c8118402867ddc, 0x116168bffbedc11d, 0x0a0a77a3b1980c0d], [0xe2d0a7869f0319ed, 0xb94f1101b1d7a628, 0xece8ea224f31d25d, 0x23397a9300f8f98b], [0xd7b688830a4f2089, 0x6558e9e3f6ac7b41, 0x99e276b571905a7d, 0x52dd465e2f094256], [0x474650359d8e211b, 0x84d37b826214abc6, 0x8da40c1ef2bb4598, 0x0c83ea7744bf1bee], [0x694341f608c9dd56, 0xed3a181fabb30adc, 0x1339a815da8b398f, 0x2c6d4e4511657e1e], [0x63e7cb4906ffc93f, 0xf070bb00e28a193d, 0xad1715b02e5713b5, 0x4b5371495990693f], ]; /** The G1 generator */ pub const G1_GENERATOR: ArkG1 = ArkG1::from_blst_p1(blst_p1 { x: blst_fp { l: [ 0x5cb38790fd530c16, 0x7817fc679976fff5, 0x154f95c7143ba1c1, 0xf0ae6acdf3d0e747, 0xedce6ecc21dbf440, 0x120177419e0bfb75, ], }, y: blst_fp { l: [ 0xbaac93d50ce72271, 0x8c22631a7918fd8e, 0xdd595f13570725ce, 0x51ac582950405194, 0x0e1c8c3fad0059c0, 0x0bbc3efc5008a26a, ], }, z: blst_fp { l: [ 0x760900000002fffd, 0xebf4000bc40c0002, 0x5f48985753c758ba, 0x77ce585370525745, 0x5c071a97a256ec6d, 0x15f65ec3fa80e493, ], }, }); pub const G1_NEGATIVE_GENERATOR: ArkG1 = ArkG1::from_blst_p1(blst_p1 { x: blst_fp { l: [ 0x5cb38790fd530c16, 0x7817fc679976fff5, 0x154f95c7143ba1c1, 0xf0ae6acdf3d0e747, 0xedce6ecc21dbf440, 0x120177419e0bfb75, ], }, y: blst_fp { l: [ 0xff526c2af318883a, 0x92899ce4383b0270, 0x89d7738d9fa9d055, 0x12caf35ba344c12a, 0x3cff1b76964b5317, 0x0e44d2ede9774430, ], }, z: blst_fp { l: [ 0x760900000002fffd, 0xebf4000bc40c0002, 0x5f48985753c758ba, 0x77ce585370525745, 0x5c071a97a256ec6d, 0x15f65ec3fa80e493, ], }, }); pub const G2_GENERATOR: ArkG2 = ArkG2::from_blst_p2(blst_p2 { x: blst_fp2 { fp: [ blst_fp { l: [ 0xf5f28fa202940a10, 0xb3f5fb2687b4961a, 0xa1a893b53e2ae580, 0x9894999d1a3caee9, 0x6f67b7631863366b, 0x058191924350bcd7, ], }, blst_fp { l: [ 0xa5a9c0759e23f606, 0xaaa0c59dbccd60c3, 0x3bb17e18e2867806, 0x1b1ab6cc8541b367, 0xc2b6ed0ef2158547, 0x11922a097360edf3, ], }, ], }, y: blst_fp2 { fp: [ blst_fp { l: [ 0x4c730af860494c4a, 0x597cfa1f5e369c5a, 0xe7e6856caa0a635a, 0xbbefb5e96e0d495f, 0x07d3a975f0ef25a2, 0x0083fd8e7e80dae5, ], }, blst_fp { l: [ 0xadc0fc92df64b05d, 0x18aa270a2b1461dc, 0x86adac6a3be4eba0, 0x79495c4ec93da33a, 0xe7175850a43ccaed, 0x0b2bc2a163de1bf2, ], }, ], }, z: blst_fp2 { fp: [ blst_fp { l: [ 0x760900000002fffd, 0xebf4000bc40c0002, 0x5f48985753c758ba, 0x77ce585370525745, 0x5c071a97a256ec6d, 0x15f65ec3fa80e493, ], }, blst_fp { l: [ 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, ], }, ], }, }); pub const G2_NEGATIVE_GENERATOR: ArkG2 = ArkG2::from_blst_p2(blst_p2 { x: blst_fp2 { fp: [ blst_fp { l: [ 0xf5f28fa202940a10, 0xb3f5fb2687b4961a, 0xa1a893b53e2ae580, 0x9894999d1a3caee9, 0x6f67b7631863366b, 0x058191924350bcd7, ], }, blst_fp { l: [ 0xa5a9c0759e23f606, 0xaaa0c59dbccd60c3, 0x3bb17e18e2867806, 0x1b1ab6cc8541b367, 0xc2b6ed0ef2158547, 0x11922a097360edf3, ], }, ], }, y: blst_fp2 { fp: [ blst_fp { l: [ 0x6d8bf5079fb65e61, 0xc52f05df531d63a5, 0x7f4a4d344ca692c9, 0xa887959b8577c95f, 0x4347fe40525c8734, 0x197d145bbaff0bb5, ], }, blst_fp { l: [ 0x0c3e036d209afa4e, 0x0601d8f4863f9e23, 0xe0832636bacc0a84, 0xeb2def362a476f84, 0x64044f659f0ee1e9, 0x0ed54f48d5a1caa7, ], }, ], }, z: blst_fp2 { fp: [ blst_fp { l: [ 0x760900000002fffd, 0xebf4000bc40c0002, 0x5f48985753c758ba, 0x77ce585370525745, 0x5c071a97a256ec6d, 0x15f65ec3fa80e493, ], }, blst_fp { l: [ 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000, ], }, ], }, });
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/das.rs
arkworks4/src/das.rs
use crate::kzg_proofs::FFTSettings; use crate::kzg_types::ArkFr as BlstFr; use kzg::{DASExtension, Fr}; use std::cmp::Ordering; impl FFTSettings { fn das_fft_extension_stride(&self, ab: &mut [BlstFr], stride: usize) { match ab.len().cmp(&2_usize) { Ordering::Less => {} Ordering::Greater => { let half = ab.len(); let halfhalf = half / 2; for i in 0..halfhalf { let tmp1 = ab[i].add(&ab[halfhalf + i]); let tmp2 = ab[i].sub(&ab[halfhalf + i]); ab[halfhalf + i] = tmp2.mul(&self.reverse_roots_of_unity[i * 2 * stride]); ab[i] = tmp1; } #[cfg(feature = "parallel")] { if ab.len() > 32 { let (lo, hi) = ab.split_at_mut(halfhalf); rayon::join( || self.das_fft_extension_stride(hi, stride * 2), || self.das_fft_extension_stride(lo, stride * 2), ); } else { self.das_fft_extension_stride(&mut ab[..halfhalf], stride * 2); self.das_fft_extension_stride(&mut ab[halfhalf..], stride * 2); } } #[cfg(not(feature = "parallel"))] { self.das_fft_extension_stride(&mut ab[..halfhalf], stride * 2); self.das_fft_extension_stride(&mut ab[halfhalf..], stride * 2); } for i in 0..halfhalf { let x = ab[i]; let y = ab[halfhalf + i]; let y_times_root = y.mul(&self.roots_of_unity[(1 + 2 * i) * stride]); ab[i] = x.add(&y_times_root); ab[halfhalf + i] = x.sub(&y_times_root); } } Ordering::Equal => { let x = ab[0].add(&ab[1]); let y = ab[0].sub(&ab[1]); let tmp = y.mul(&self.roots_of_unity[stride]); ab[0] = x.add(&tmp); ab[1] = x.sub(&tmp); } } } } impl DASExtension<BlstFr> for FFTSettings { fn das_fft_extension(&self, vals: &[BlstFr]) -> Result<Vec<BlstFr>, String> { if vals.is_empty() { return Err(String::from("vals can not be empty")); } if !vals.len().is_power_of_two() { return Err(String::from("vals lenght has to be power of 2")); } if vals.len() * 2 > self.max_width { return Err(String::from( "vals lenght * 2 has to equal or less than FFTSetings max width", )); } let mut vals = vals.to_vec(); let stride = self.max_width / (vals.len() * 2); self.das_fft_extension_stride(&mut vals, stride); let invlen = BlstFr::from_u64(vals.len() as u64); let invlen = invlen.inverse(); for val in &mut vals { val.fr *= invlen.fr } Ok(vals) } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/lib.rs
arkworks4/src/lib.rs
pub mod consts; pub mod das; pub mod eip_4844; pub mod eip_7594; pub mod fft; pub mod fft_g1; pub mod fk20_proofs; pub mod kzg_proofs; pub mod kzg_types; pub mod poly; pub mod recover; pub mod utils; pub mod zero_poly;
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/eip_4844.rs
arkworks4/src/eip_4844.rs
extern crate alloc; use crate::kzg_proofs::KZGSettings as LKZGSettings; #[cfg(feature = "c_bindings")] use crate::utils::PRECOMPUTATION_TABLES; #[cfg(feature = "c_bindings")] use kzg::{ eth::{ self, c_bindings::{Blob, Bytes32, Bytes48, CKZGSettings, CKzgRet, KZGCommitment, KZGProof}, }, Fr, G1, }; #[cfg(feature = "c_bindings")] use core::ptr; #[cfg(all(feature = "std", feature = "c_bindings"))] use libc::FILE; #[cfg(feature = "std")] use std::fs::File; #[cfg(feature = "std")] use std::io::Read; #[cfg(feature = "std")] use kzg::eip_4844::load_trusted_setup_string; #[cfg(feature = "std")] pub fn load_trusted_setup_filename_rust( filepath: &str, ) -> Result<LKZGSettings, alloc::string::String> { use kzg::eip_4844::load_trusted_setup_rust; let mut file = File::open(filepath).map_err(|_| "Unable to open file".to_string())?; let mut contents = String::new(); file.read_to_string(&mut contents) .map_err(|_| "Unable to read file".to_string())?; let (g1_monomial_bytes, g1_lagrange_bytes, g2_monomial_bytes) = load_trusted_setup_string(&contents)?; load_trusted_setup_rust(&g1_monomial_bytes, &g1_lagrange_bytes, &g2_monomial_bytes) } #[cfg(feature = "c_bindings")] pub(crate) fn kzg_settings_to_c(rust_settings: &LKZGSettings) -> CKZGSettings { CKZGSettings { roots_of_unity: Box::leak( rust_settings .fs .roots_of_unity .iter() .map(|r| r.to_blst_fr()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), brp_roots_of_unity: Box::leak( rust_settings .fs .brp_roots_of_unity .iter() .map(|r| r.to_blst_fr()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), reverse_roots_of_unity: Box::leak( rust_settings .fs .reverse_roots_of_unity .iter() .map(|r| r.to_blst_fr()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), g1_values_monomial: Box::leak( rust_settings .g1_values_monomial .iter() .map(|r| r.to_blst_p1()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), g1_values_lagrange_brp: Box::leak( rust_settings .g1_values_lagrange_brp .iter() .map(|r| r.to_blst_p1()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), g2_values_monomial: Box::leak( rust_settings .g2_values_monomial .iter() .map(|r| r.to_blst_p2()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), x_ext_fft_columns: Box::leak( rust_settings .x_ext_fft_columns .iter() .map(|r| { Box::leak( r.iter() .map(|it| it.to_blst_p1()) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr() }) .collect::<Vec<_>>() .into_boxed_slice(), ) .as_mut_ptr(), tables: core::ptr::null_mut(), wbits: 0, scratch_size: 0, } } #[cfg(feature = "c_bindings")] macro_rules! handle_ckzg_badargs { ($x: expr) => { match $x { Ok(value) => value, Err(_) => return CKzgRet::BadArgs, } }; } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn blob_to_kzg_commitment( out: *mut KZGCommitment, blob: *const Blob, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::{ blob_to_kzg_commitment_raw, FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G1_POINTS, }; if TRUSTED_SETUP_NUM_G1_POINTS == 0 { // FIXME: load_trusted_setup should set this value, but if not, it fails TRUSTED_SETUP_NUM_G1_POINTS = FIELD_ELEMENTS_PER_BLOB }; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let tmp = handle_ckzg_badargs!(blob_to_kzg_commitment_raw((*blob).bytes, &settings)); (*out).bytes = tmp.to_bytes(); CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn load_trusted_setup( out: *mut CKZGSettings, g1_monomial_bytes: *const u8, num_g1_monomial_bytes: u64, g1_lagrange_bytes: *const u8, num_g1_lagrange_bytes: u64, g2_monomial_bytes: *const u8, num_g2_monomial_bytes: u64, _precompute: u64, ) -> CKzgRet { use kzg::eip_4844::{load_trusted_setup_rust, BYTES_PER_G1, TRUSTED_SETUP_NUM_G1_POINTS}; *out = CKZGSettings { brp_roots_of_unity: ptr::null_mut(), roots_of_unity: ptr::null_mut(), reverse_roots_of_unity: ptr::null_mut(), g1_values_monomial: ptr::null_mut(), g1_values_lagrange_brp: ptr::null_mut(), g2_values_monomial: ptr::null_mut(), x_ext_fft_columns: ptr::null_mut(), tables: ptr::null_mut(), wbits: 0, scratch_size: 0, }; let g1_monomial_bytes = core::slice::from_raw_parts(g1_monomial_bytes, num_g1_monomial_bytes as usize); let g1_lagrange_bytes = core::slice::from_raw_parts(g1_lagrange_bytes, num_g1_lagrange_bytes as usize); let g2_monomial_bytes = core::slice::from_raw_parts(g2_monomial_bytes, num_g2_monomial_bytes as usize); TRUSTED_SETUP_NUM_G1_POINTS = num_g1_monomial_bytes as usize / BYTES_PER_G1; let mut settings = handle_ckzg_badargs!(load_trusted_setup_rust( g1_monomial_bytes, g1_lagrange_bytes, g2_monomial_bytes )); let c_settings = kzg_settings_to_c(&settings); PRECOMPUTATION_TABLES.save_precomputation(settings.precomputation.take(), &c_settings); *out = c_settings; CKzgRet::Ok } /// # Safety #[cfg(all(feature = "std", feature = "c_bindings"))] #[no_mangle] pub unsafe extern "C" fn load_trusted_setup_file( out: *mut CKZGSettings, in_: *mut FILE, ) -> CKzgRet { use kzg::eip_4844::{ load_trusted_setup_rust, BYTES_PER_G1, FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G1_POINTS, }; *out = CKZGSettings { brp_roots_of_unity: ptr::null_mut(), roots_of_unity: ptr::null_mut(), reverse_roots_of_unity: ptr::null_mut(), g1_values_monomial: ptr::null_mut(), g1_values_lagrange_brp: ptr::null_mut(), g2_values_monomial: ptr::null_mut(), x_ext_fft_columns: ptr::null_mut(), tables: ptr::null_mut(), wbits: 0, scratch_size: 0, }; let mut buf = vec![0u8; 1024 * 1024]; let len: usize = libc::fread(buf.as_mut_ptr() as *mut libc::c_void, 1, buf.len(), in_); let s = handle_ckzg_badargs!(String::from_utf8(buf[..len].to_vec())); let (g1_monomial_bytes, g1_lagrange_bytes, g2_monomial_bytes) = handle_ckzg_badargs!(load_trusted_setup_string(&s)); TRUSTED_SETUP_NUM_G1_POINTS = g1_monomial_bytes.len() / BYTES_PER_G1; if TRUSTED_SETUP_NUM_G1_POINTS != FIELD_ELEMENTS_PER_BLOB { // Helps pass the Java test "shouldThrowExceptionOnIncorrectTrustedSetupFromFile", // as well as 5 others that pass only if this one passes (likely because Java doesn't // deallocate its KZGSettings pointer when no exception is thrown). return CKzgRet::BadArgs; } let mut settings = handle_ckzg_badargs!(load_trusted_setup_rust( &g1_monomial_bytes, &g1_lagrange_bytes, &g2_monomial_bytes )); let c_settings = kzg_settings_to_c(&settings); PRECOMPUTATION_TABLES.save_precomputation(settings.precomputation.take(), &c_settings); *out = c_settings; CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn free_trusted_setup(s: *mut CKZGSettings) { use kzg::eip_4844::{FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G2_POINTS}; if s.is_null() { return; } PRECOMPUTATION_TABLES.remove_precomputation(&*s); if !(*s).roots_of_unity.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1, )); drop(v); (*s).roots_of_unity = ptr::null_mut(); } if !(*s).brp_roots_of_unity.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).brp_roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB, )); drop(v); (*s).brp_roots_of_unity = ptr::null_mut(); } if !(*s).reverse_roots_of_unity.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).reverse_roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1, )); drop(v); (*s).reverse_roots_of_unity = ptr::null_mut(); } if !(*s).g1_values_monomial.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).g1_values_monomial, FIELD_ELEMENTS_PER_BLOB, )); drop(v); (*s).g1_values_monomial = ptr::null_mut(); } if !(*s).g1_values_lagrange_brp.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).g1_values_lagrange_brp, FIELD_ELEMENTS_PER_BLOB, )); drop(v); (*s).g1_values_lagrange_brp = ptr::null_mut(); } if !(*s).g2_values_monomial.is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( (*s).g2_values_monomial, TRUSTED_SETUP_NUM_G2_POINTS, )); drop(v); (*s).g2_values_monomial = ptr::null_mut(); } if !(*s).x_ext_fft_columns.is_null() { let x_ext_fft_columns = core::slice::from_raw_parts_mut( (*s).x_ext_fft_columns, 2 * ((eth::FIELD_ELEMENTS_PER_EXT_BLOB / 2) / eth::FIELD_ELEMENTS_PER_CELL), ); for column in x_ext_fft_columns.iter_mut() { if !(*column).is_null() { let v = Box::from_raw(core::slice::from_raw_parts_mut( *column, eth::FIELD_ELEMENTS_PER_CELL, )); drop(v); *column = ptr::null_mut(); } } let v = Box::from_raw(x_ext_fft_columns); drop(v); (*s).x_ext_fft_columns = ptr::null_mut(); } } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn verify_kzg_proof( ok: *mut bool, commitment_bytes: *const Bytes48, z_bytes: *const Bytes32, y_bytes: *const Bytes32, proof_bytes: *const Bytes48, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::verify_kzg_proof_raw; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let result = handle_ckzg_badargs!(verify_kzg_proof_raw( (*commitment_bytes).bytes, (*z_bytes).bytes, (*y_bytes).bytes, (*proof_bytes).bytes, &settings )); *ok = result; CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn verify_blob_kzg_proof( ok: *mut bool, blob: *const Blob, commitment_bytes: *const Bytes48, proof_bytes: *const Bytes48, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::verify_blob_kzg_proof_raw; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let result = handle_ckzg_badargs!(verify_blob_kzg_proof_raw( (*blob).bytes, (*commitment_bytes).bytes, (*proof_bytes).bytes, &settings, )); *ok = result; CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn verify_blob_kzg_proof_batch( ok: *mut bool, blobs: *const Blob, commitments_bytes: *const Bytes48, proofs_bytes: *const Bytes48, n: usize, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::verify_blob_kzg_proof_batch_raw; let blobs = core::slice::from_raw_parts(blobs, n) .iter() .map(|v| v.bytes) .collect::<Vec<_>>(); let commitments = core::slice::from_raw_parts(commitments_bytes, n) .iter() .map(|v| v.bytes) .collect::<Vec<_>>(); let proofs = core::slice::from_raw_parts(proofs_bytes, n) .iter() .map(|v| v.bytes) .collect::<Vec<_>>(); *ok = false; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let result = handle_ckzg_badargs!(verify_blob_kzg_proof_batch_raw( &blobs, &commitments, &proofs, &settings )); *ok = result; CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn compute_blob_kzg_proof( out: *mut KZGProof, blob: *const Blob, commitment_bytes: *const Bytes48, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::compute_blob_kzg_proof_raw; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let proof = handle_ckzg_badargs!(compute_blob_kzg_proof_raw( (*blob).bytes, (*commitment_bytes).bytes, &settings )); (*out).bytes = proof.to_bytes(); CKzgRet::Ok } /// # Safety #[cfg(feature = "c_bindings")] #[no_mangle] pub unsafe extern "C" fn compute_kzg_proof( proof_out: *mut KZGProof, y_out: *mut Bytes32, blob: *const Blob, z_bytes: *const Bytes32, s: &CKZGSettings, ) -> CKzgRet { use kzg::eip_4844::compute_kzg_proof_raw; let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into()); let (proof_out_tmp, fry_tmp) = handle_ckzg_badargs!(compute_kzg_proof_raw( (*blob).bytes, (*z_bytes).bytes, &settings )); (*proof_out).bytes = proof_out_tmp.to_bytes(); (*y_out).bytes = fry_tmp.to_bytes(); CKzgRet::Ok }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/kzg_proofs.rs
arkworks4/src/kzg_proofs.rs
#![allow(non_camel_case_types)] extern crate alloc; use super::utils::{blst_poly_into_pc_poly, PolyData}; use crate::kzg_types::{ArkFp, ArkFr, ArkG1Affine, ArkG1ProjAddAffine}; use crate::kzg_types::{ArkFr as BlstFr, ArkG1, ArkG2}; use alloc::sync::Arc; use ark_bls12_381::Bls12_381; use ark_ec::pairing::Pairing; use ark_ec::CurveGroup; use ark_poly::Polynomial; use ark_std::{vec, One}; use kzg::common_utils::log2_pow2; use kzg::eip_4844::hash_to_bls_field; use kzg::msm::precompute::PrecomputationTable; use kzg::{FFTSettings as _, Fr as FrTrait, FFTG1, G1, G2}; use kzg::{G1Mul, G2Mul}; use std::ops::Neg; #[derive(Debug, Clone)] pub struct FFTSettings { pub max_width: usize, pub root_of_unity: BlstFr, pub reverse_roots_of_unity: Vec<BlstFr>, pub roots_of_unity: Vec<BlstFr>, pub brp_roots_of_unity: Vec<BlstFr>, } pub fn expand_root_of_unity(root: &BlstFr, width: usize) -> Result<Vec<BlstFr>, String> { let mut generated_powers = vec![BlstFr::one(), *root]; while !(generated_powers.last().unwrap().is_one()) { if generated_powers.len() > width { return Err(String::from("Root of unity multiplied for too long")); } generated_powers.push(generated_powers.last().unwrap().mul(root)); } if generated_powers.len() != width + 1 { return Err(String::from("Root of unity has invalid scale")); } Ok(generated_powers) } #[derive(Debug, Clone, Default)] #[allow(clippy::type_complexity)] pub struct KZGSettings { pub fs: FFTSettings, pub g1_values_monomial: Vec<ArkG1>, pub g1_values_lagrange_brp: Vec<ArkG1>, pub g2_values_monomial: Vec<ArkG2>, pub precomputation: Option<Arc<PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>>>, pub x_ext_fft_columns: Vec<Vec<ArkG1>>, pub cell_size: usize, } pub fn generate_trusted_setup( len: usize, secret: [u8; 32usize], ) -> (Vec<ArkG1>, Vec<ArkG1>, Vec<ArkG2>) { let s = hash_to_bls_field(&secret); let mut s_pow = ArkFr::one(); let mut g1_monomial_values = Vec::with_capacity(len); let mut g2_monomial_values = Vec::with_capacity(len); for _ in 0..len { g1_monomial_values.push(ArkG1::generator().mul(&s_pow)); g2_monomial_values.push(ArkG2::generator().mul(&s_pow)); s_pow = s_pow.mul(&s); } let s = FFTSettings::new(log2_pow2(len)).unwrap(); let g1_lagrange_values = s.fft_g1(&g1_monomial_values, true).unwrap(); (g1_monomial_values, g1_lagrange_values, g2_monomial_values) } pub fn eval_poly(p: &PolyData, x: &BlstFr) -> BlstFr { let poly = blst_poly_into_pc_poly(&p.coeffs); BlstFr { fr: poly.evaluate(&x.fr), } } pub fn pairings_verify(a1: &ArkG1, a2: &ArkG2, b1: &ArkG1, b2: &ArkG2) -> bool { let ark_a1_neg = a1.0.neg().into_affine(); let ark_b1 = b1.0.into_affine(); let ark_a2 = a2.0.into_affine(); let ark_b2 = b2.0.into_affine(); Bls12_381::multi_pairing([ark_a1_neg, ark_b1], [ark_a2, ark_b2]) .0 .is_one() }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/eip_7594.rs
arkworks4/src/eip_7594.rs
extern crate alloc; use kzg::EcBackend; use crate::kzg_proofs::FFTSettings; use crate::kzg_proofs::KZGSettings; use crate::kzg_types::ArkFp; use crate::kzg_types::ArkFr; use crate::kzg_types::ArkG1; use crate::kzg_types::ArkG1Affine; use crate::kzg_types::ArkG1ProjAddAffine; use crate::kzg_types::ArkG2; use crate::utils::PolyData; pub struct ArkBackend; impl EcBackend for ArkBackend { type Fr = ArkFr; type G1Fp = ArkFp; type G1Affine = ArkG1Affine; type G1ProjAddAffine = ArkG1ProjAddAffine; type G1 = ArkG1; type G2 = ArkG2; type Poly = PolyData; type FFTSettings = FFTSettings; type KZGSettings = KZGSettings; } #[cfg(feature = "c_bindings")] kzg::c_bindings_eip7594!(ArkBackend);
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/poly.rs
arkworks4/src/poly.rs
use super::kzg_proofs::FFTSettings; use super::utils::{blst_poly_into_pc_poly, PolyData}; use crate::kzg_types::ArkFr as BlstFr; use crate::utils::pc_poly_into_blst_poly; use crate::zero_poly::pad_poly; use ark_bls12_381::Fr; use ark_poly::univariate::DensePolynomial; use ark_poly::DenseUVPolynomial; use ark_std::{log2, Zero}; use kzg::common_utils::{log2_pow2, next_pow_of_2}; use kzg::{FFTFr, FFTSettings as FFTSettingsT, Fr as FrTrait, Poly}; use std::cmp::min; pub fn poly_inverse(b: &PolyData, output_len: usize) -> Result<PolyData, String> { if b.coeffs.is_empty() { return Err(String::from("b.coeffs is empty")); } if BlstFr::is_zero(&b.coeffs[0]) { return Err(String::from("b.coeffs[0] is zero")); } let mut output = PolyData { coeffs: vec![BlstFr::zero(); output_len], }; if b.coeffs.len() == 1 { output.coeffs[0] = b.coeffs[0].inverse(); for i in 1..output_len { output.coeffs[i] = BlstFr::zero(); } return Ok(output); } let maxd = output_len - 1; let scale = next_pow_of_2(log2_pow2(2 * output_len - 1)); let fs = FFTSettings::new(scale).unwrap(); let mut tmp0: PolyData; let mut tmp1: PolyData; output.coeffs[0] = b.coeffs[0].inverse(); let mut d: usize = 0; let mut mask: usize = 1 << log2(maxd); while mask != 0 { d = 2 * d + usize::from((maxd & mask) != 0); mask >>= 1; let len_temp: usize = min(d + 1, b.coeffs.len() + output.coeffs.len() - 1); tmp0 = poly_mul(b, &output, Some(&fs), len_temp).unwrap(); for i in 0..len_temp { tmp0.coeffs[i] = tmp0.coeffs[i].negate(); } let fr_two = BlstFr { fr: Fr::from(2) }; tmp0.coeffs[0] = tmp0.coeffs[0].add(&fr_two); let len_temp2: usize = d + 1; tmp1 = poly_mul(&output, &tmp0, Some(&fs), len_temp2).unwrap(); if tmp1.coeffs.len() > output_len { tmp1.coeffs = tmp1.coeffs[..output_len].to_vec(); } for i in 0..tmp1.coeffs.len() { output.coeffs[i] = tmp1.coeffs[i]; } } if d + 1 != output_len { return Err(String::from("d + 1 is not equals to output_len")); } Ok(output) } pub fn poly_mul_direct(p1: &PolyData, p2: &PolyData, len: usize) -> Result<PolyData, String> { let p1 = blst_poly_into_pc_poly(&p1.coeffs); let p2 = blst_poly_into_pc_poly(&p2.coeffs); if p1.is_zero() || p2.is_zero() { Ok(pc_poly_into_blst_poly(DensePolynomial::zero())) } else { let mut result = vec![Fr::zero(); len]; for (i, self_coeff) in p1.coeffs.iter().enumerate() { for (j, other_coeff) in p2.coeffs.iter().enumerate() { if i + j >= len { break; } result[i + j] += &(*self_coeff * other_coeff); } } let p = pc_poly_into_blst_poly(DensePolynomial::from_coefficients_vec(result)); Ok(PolyData { coeffs: pad_poly(&p, len).unwrap(), }) } } pub fn poly_long_div(p1: &PolyData, p2: &PolyData) -> Result<PolyData, String> { Ok(pc_poly_into_blst_poly( &blst_poly_into_pc_poly(&p1.coeffs) / &blst_poly_into_pc_poly(&p2.coeffs), )) } pub fn poly_mul( a: &PolyData, b: &PolyData, fs: Option<&FFTSettings>, len: usize, ) -> Result<PolyData, String> { if a.coeffs.len() < 64 || b.coeffs.len() < 64 || len < 128 { poly_mul_direct(a, b, len) } else { poly_mul_fft(a, b, fs, len) } } pub fn poly_mul_fft( a: &PolyData, b: &PolyData, fs: Option<&FFTSettings>, len: usize, ) -> Result<PolyData, String> { // Truncate a and b so as not to do excess work for the number of coefficients required. let a_len = min(a.len(), len); let b_len = min(b.len(), len); let length = next_pow_of_2(a_len + b_len - 1); // If the FFT settings are NULL then make a local set, otherwise use the ones passed in. let fs_p = if let Some(x) = fs { x.clone() } else { let scale = log2_pow2(length); FFTSettings::new(scale).unwrap() }; if length > fs_p.max_width { return Err(String::from( "length should be equals or less than FFTSettings max width", )); } let a = PolyData { coeffs: a.coeffs[..a_len].to_vec(), }; let b = PolyData { coeffs: b.coeffs[..b_len].to_vec(), }; let a_pad = PolyData { coeffs: pad_poly(&a, length).unwrap(), }; let b_pad = PolyData { coeffs: pad_poly(&b, length).unwrap(), }; let a_fft; let b_fft; #[cfg(feature = "parallel")] { if length > 1024 { let mut a_fft_temp = vec![]; let mut b_fft_temp = vec![]; rayon::join( || a_fft_temp = fs_p.fft_fr(&a_pad.coeffs, false).unwrap(), || b_fft_temp = fs_p.fft_fr(&b_pad.coeffs, false).unwrap(), ); a_fft = a_fft_temp; b_fft = b_fft_temp; } else { a_fft = fs_p.fft_fr(&a_pad.coeffs, false).unwrap(); b_fft = fs_p.fft_fr(&b_pad.coeffs, false).unwrap(); } } #[cfg(not(feature = "parallel"))] { a_fft = fs_p.fft_fr(&a_pad.coeffs, false).unwrap(); b_fft = fs_p.fft_fr(&b_pad.coeffs, false).unwrap(); } let mut ab_fft = a_pad; let mut ab = b_pad; for i in 0..length { ab_fft.coeffs[i] = a_fft[i].mul(&b_fft[i]); } ab.coeffs = fs_p.fft_fr(&ab_fft.coeffs, true).unwrap(); let data_len = min(len, length); let mut out = PolyData::new(len); for i in 0..data_len { out.coeffs[i] = ab.coeffs[i]; } for i in data_len..len { out.coeffs[i] = BlstFr::zero(); } Ok(out) } pub fn poly_fast_div(dividend: &PolyData, divisor: &PolyData) -> Result<PolyData, String> { if divisor.coeffs.is_empty() { return Err(String::from("divisor coeffs are empty")); } if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() { return Err(String::from("divisor coeffs last member is zero")); } let m = dividend.coeffs.len() - 1; let n = divisor.coeffs.len() - 1; if n > m { return Ok(PolyData::new(0)); } if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() { return Err(String::from("divisor coeffs last member is zero")); } let mut out = PolyData::new(0); if divisor.len() == 1 { for i in 0..dividend.len() { out.coeffs .push(dividend.coeffs[i].div(&divisor.coeffs[0]).unwrap()); } return Ok(out); } let a_flip = poly_flip(dividend).unwrap(); let b_flip = poly_flip(divisor).unwrap(); let inv_b_flip = poly_inverse(&b_flip, m - n + 1).unwrap(); let q_flip = poly_mul(&a_flip, &inv_b_flip, None, m - n + 1).unwrap(); out = poly_flip(&q_flip).unwrap(); Ok(PolyData { coeffs: out.coeffs[..m - n + 1].to_vec(), }) } pub fn poly_flip(input: &PolyData) -> Result<PolyData, String> { let mut output = PolyData::new(0); for i in 0..input.len() { output.coeffs.push(input.coeffs[input.coeffs.len() - i - 1]); } Ok(output) }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/kzg_types.rs
arkworks4/src/kzg_types.rs
use crate::consts::{ G1_GENERATOR, G1_IDENTITY, G1_NEGATIVE_GENERATOR, G2_GENERATOR, G2_NEGATIVE_GENERATOR, SCALE2_ROOT_OF_UNITY, }; use crate::fft_g1::g1_linear_combination; use crate::kzg_proofs::{ eval_poly, expand_root_of_unity, pairings_verify, FFTSettings as LFFTSettings, KZGSettings as LKZGSettings, }; use crate::poly::{poly_fast_div, poly_inverse, poly_long_div, poly_mul_direct, poly_mul_fft}; use crate::recover::{scale_poly, unscale_poly}; use crate::utils::{ blst_fp_into_pc_fq, blst_fr_into_pc_fr, blst_p1_into_pc_g1projective, blst_p2_into_pc_g2projective, fft_settings_to_rust, pc_fr_into_blst_fr, pc_g1projective_into_blst_p1, pc_g2projective_into_blst_p2, PolyData, PRECOMPUTATION_TABLES, }; use arbitrary::Arbitrary; use ark_bls12_381::{g1, g2, Fr, G1Affine, G2Affine}; use ark_ec::{models::short_weierstrass::Projective, AffineRepr, Group}; use ark_ec::{CurveConfig, CurveGroup}; use ark_ff::{biginteger::BigInteger256, BigInteger, Field}; use ark_serialize::{CanonicalDeserialize, CanonicalSerialize}; use ark_std::{One, Zero}; #[cfg(feature = "rand")] use ark_std::UniformRand; use kzg::eth::c_bindings::{blst_fp, blst_fr, blst_p1, blst_p2, CKZGSettings}; use crate::fft_g1::fft_g1_fast; use kzg::common_utils::reverse_bit_order; use kzg::msm::precompute::{precompute, PrecomputationTable}; use kzg::{ eth, FFTFr, FFTSettings, FFTSettingsPoly, Fr as KzgFr, G1Affine as G1AffineTrait, G1Fp, G1GetFp, G1LinComb, G1Mul, G1ProjAddAffine, G2Mul, KZGSettings, PairingVerify, Poly, Scalar256, G1, G2, }; use std::ops::{AddAssign, Mul, Neg, Sub}; use kzg::eip_4844::{BYTES_PER_FIELD_ELEMENT, BYTES_PER_G1, BYTES_PER_G2}; extern crate alloc; use alloc::sync::Arc; fn bytes_be_to_uint64(inp: &[u8]) -> u64 { u64::from_be_bytes(inp.try_into().expect("Input wasn't 8 elements...")) } const BLS12_381_MOD_256: [u64; 4] = [ 0xffffffff00000001, 0x53bda402fffe5bfe, 0x3339d80809a1d805, 0x73eda753299d7d48, ]; #[derive(Debug, Clone, Copy, Eq, PartialEq, Default)] pub struct ArkFr { pub fr: Fr, } impl<'a> Arbitrary<'a> for ArkFr { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { let val: [u8; 32] = u.arbitrary()?; Ok(Self::from_bytes_unchecked(&val).unwrap()) } } impl ArkFr { pub fn from_blst_fr(fr: blst_fr) -> Self { Self { fr: blst_fr_into_pc_fr(fr), } } pub fn to_blst_fr(&self) -> blst_fr { pc_fr_into_blst_fr(self.fr) } } fn bigint_check_mod_256(a: &[u64; 4]) -> bool { let (_, overflow) = a[0].overflowing_sub(BLS12_381_MOD_256[0]); let (_, overflow) = a[1].overflowing_sub(BLS12_381_MOD_256[1] + overflow as u64); let (_, overflow) = a[2].overflowing_sub(BLS12_381_MOD_256[2] + overflow as u64); let (_, overflow) = a[3].overflowing_sub(BLS12_381_MOD_256[3] + overflow as u64); overflow } impl KzgFr for ArkFr { fn null() -> Self { Self { fr: Fr::new_unchecked(BigInteger256::new([u64::MAX; 4])), } } fn zero() -> Self { // Self::from_u64(0) Self { fr: Fr::zero() } } fn one() -> Self { let one = Fr::one(); // assert_eq!(one.0.0, [0, 1, 1, 1], "must be eq"); Self { fr: one } // Self::from_u64(1) } #[cfg(feature = "rand")] fn rand() -> Self { let mut rng = rand::thread_rng(); Self { fr: Fr::rand(&mut rng), } } fn from_bytes(bytes: &[u8]) -> Result<Self, String> { bytes .try_into() .map_err(|_| { format!( "Invalid byte length. Expected {}, got {}", BYTES_PER_FIELD_ELEMENT, bytes.len() ) }) .and_then(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| { let storage: [u64; 4] = [ bytes_be_to_uint64(&bytes[24..32]), bytes_be_to_uint64(&bytes[16..24]), bytes_be_to_uint64(&bytes[8..16]), bytes_be_to_uint64(&bytes[0..8]), ]; let big_int = BigInteger256::new(storage); if !big_int.is_zero() && !bigint_check_mod_256(&big_int.0) { return Err("Invalid scalar".to_string()); } Ok(Self { fr: Fr::new(big_int), }) }) } fn from_bytes_unchecked(bytes: &[u8]) -> Result<Self, String> { bytes .try_into() .map_err(|_| { format!( "Invalid byte length. Expected {}, got {}", BYTES_PER_FIELD_ELEMENT, bytes.len() ) }) .map(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| { let storage: [u64; 4] = [ bytes_be_to_uint64(&bytes[24..32]), bytes_be_to_uint64(&bytes[16..24]), bytes_be_to_uint64(&bytes[8..16]), bytes_be_to_uint64(&bytes[0..8]), ]; let big_int = BigInteger256::new(storage); Self { fr: Fr::new(big_int), } }) } fn from_hex(hex: &str) -> Result<Self, String> { let bytes = hex::decode(&hex[2..]).unwrap(); Self::from_bytes(&bytes) } fn from_u64_arr(u: &[u64; 4]) -> Self { Self { fr: Fr::new(BigInteger256::new(*u)), } } fn from_u64(val: u64) -> Self { Self::from_u64_arr(&[val, 0, 0, 0]) } fn to_bytes(&self) -> [u8; 32] { let big_int_256: BigInteger256 = Fr::into(self.fr); <[u8; 32]>::try_from(big_int_256.to_bytes_be()).unwrap() } fn to_u64_arr(&self) -> [u64; 4] { let b: BigInteger256 = Fr::into(self.fr); b.0 } fn is_one(&self) -> bool { self.fr.is_one() } fn is_zero(&self) -> bool { self.fr.is_zero() } fn is_null(&self) -> bool { self.equals(&ArkFr::null()) } fn sqr(&self) -> Self { Self { fr: self.fr.square(), } } fn mul(&self, b: &Self) -> Self { Self { fr: self.fr * b.fr } } fn add(&self, b: &Self) -> Self { Self { fr: self.fr + b.fr } } fn sub(&self, b: &Self) -> Self { Self { fr: self.fr - b.fr } } fn eucl_inverse(&self) -> Self { // Inverse and eucl inverse work the same way Self { fr: self.fr.inverse().unwrap(), } } fn negate(&self) -> Self { Self { fr: self.fr.neg() } } fn inverse(&self) -> Self { Self { fr: self.fr.inverse().unwrap(), } } fn pow(&self, n: usize) -> Self { Self { fr: self.fr.pow([n as u64]), } } fn div(&self, b: &Self) -> Result<Self, String> { let div = self.fr / b.fr; if div.0 .0.is_empty() { Ok(Self { fr: Fr::zero() }) } else { Ok(Self { fr: div }) } } fn equals(&self, b: &Self) -> bool { self.fr == b.fr } fn to_scalar(&self) -> Scalar256 { Scalar256::from_u64(BigInteger256::from(self.fr).0) } } #[repr(C)] #[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash)] pub struct ArkG1(pub Projective<g1::Config>); impl ArkG1 { pub const fn from_blst_p1(p1: blst_p1) -> Self { Self(blst_p1_into_pc_g1projective(&p1)) } pub const fn to_blst_p1(&self) -> blst_p1 { pc_g1projective_into_blst_p1(self.0) } } impl From<blst_p1> for ArkG1 { fn from(p1: blst_p1) -> Self { Self(blst_p1_into_pc_g1projective(&p1)) } } impl G1 for ArkG1 { fn identity() -> Self { G1_IDENTITY } fn generator() -> Self { G1_GENERATOR } fn negative_generator() -> Self { G1_NEGATIVE_GENERATOR } #[cfg(feature = "rand")] fn rand() -> Self { let mut rng = rand::thread_rng(); Self(Projective::rand(&mut rng)) } #[allow(clippy::bind_instead_of_map)] fn from_bytes(bytes: &[u8]) -> Result<Self, String> { bytes .try_into() .map_err(|_| { format!( "Invalid byte length. Expected {}, got {}", BYTES_PER_G1, bytes.len() ) }) .and_then(|bytes: &[u8; BYTES_PER_G1]| { let affine = G1Affine::deserialize_compressed(bytes.as_slice()); match affine { Err(x) => Err("Failed to deserialize G1: ".to_owned() + &(x.to_string())), Ok(x) => Ok(Self(x.into_group())), } }) } fn from_hex(hex: &str) -> Result<Self, String> { let bytes = hex::decode(&hex[2..]).unwrap(); Self::from_bytes(&bytes) } fn to_bytes(&self) -> [u8; 48] { let mut buff = [0u8; BYTES_PER_G1]; self.0.serialize_compressed(&mut &mut buff[..]).unwrap(); buff } fn add_or_dbl(&self, b: &Self) -> Self { Self(self.0 + b.0) } fn is_inf(&self) -> bool { let temp = &self.0; temp.z.is_zero() } fn is_valid(&self) -> bool { true } fn dbl(&self) -> Self { Self(self.0.double()) } fn add(&self, b: &Self) -> Self { Self(self.0 + b.0) } fn sub(&self, b: &Self) -> Self { Self(self.0.sub(&b.0)) } fn equals(&self, b: &Self) -> bool { self.0.eq(&b.0) } fn zero() -> ArkG1 { ArkG1::from_blst_p1(blst_p1 { x: blst_fp { l: [ 8505329371266088957, 17002214543764226050, 6865905132761471162, 8632934651105793861, 6631298214892334189, 1582556514881692819, ], }, y: blst_fp { l: [ 8505329371266088957, 17002214543764226050, 6865905132761471162, 8632934651105793861, 6631298214892334189, 1582556514881692819, ], }, z: blst_fp { l: [0, 0, 0, 0, 0, 0], }, }) } fn add_or_dbl_assign(&mut self, b: &Self) { self.0 += b.0; } fn add_assign(&mut self, b: &Self) { self.0.add_assign(b.0); } fn dbl_assign(&mut self) { self.0.double_in_place(); } } impl G1Mul<ArkFr> for ArkG1 { fn mul(&self, b: &ArkFr) -> Self { Self(self.0.mul(b.fr)) } } impl G1LinComb<ArkFr, ArkFp, ArkG1Affine, ArkG1ProjAddAffine> for ArkG1 { fn g1_lincomb( points: &[Self], scalars: &[ArkFr], len: usize, precomputation: Option< &PrecomputationTable<ArkFr, Self, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>, >, ) -> Self { let mut out = Self::default(); g1_linear_combination(&mut out, points, scalars, len, precomputation); out } } impl PairingVerify<ArkG1, ArkG2> for ArkG1 { fn verify(a1: &ArkG1, a2: &ArkG2, b1: &ArkG1, b2: &ArkG2) -> bool { pairings_verify(a1, a2, b1, b2) } } #[repr(C)] #[derive(Debug, Default, PartialEq, Eq, Clone)] pub struct ArkG2(pub Projective<g2::Config>); impl ArkG2 { pub const fn from_blst_p2(p2: blst_p2) -> Self { Self(blst_p2_into_pc_g2projective(&p2)) } pub const fn to_blst_p2(&self) -> blst_p2 { pc_g2projective_into_blst_p2(self.0) } } impl G2 for ArkG2 { fn generator() -> Self { G2_GENERATOR } fn negative_generator() -> Self { G2_NEGATIVE_GENERATOR } #[allow(clippy::bind_instead_of_map)] fn from_bytes(bytes: &[u8]) -> Result<Self, String> { bytes .try_into() .map_err(|_| { format!( "Invalid byte length. Expected {}, got {}", BYTES_PER_G2, bytes.len() ) }) .and_then(|bytes: &[u8; BYTES_PER_G2]| { let affine = G2Affine::deserialize_compressed(bytes.as_slice()); match affine { Err(x) => Err("Failed to deserialize G2: ".to_owned() + &(x.to_string())), Ok(x) => Ok(Self(x.into_group())), } }) } fn to_bytes(&self) -> [u8; 96] { let mut buff = [0u8; BYTES_PER_G2]; self.0.serialize_compressed(&mut &mut buff[..]).unwrap(); buff } fn add_or_dbl(&mut self, b: &Self) -> Self { Self(self.0 + b.0) } fn dbl(&self) -> Self { Self(self.0.double()) } fn sub(&self, b: &Self) -> Self { Self(self.0 - b.0) } fn equals(&self, b: &Self) -> bool { self.0.eq(&b.0) } } impl G2Mul<ArkFr> for ArkG2 { fn mul(&self, b: &ArkFr) -> Self { Self(self.0.mul(&b.fr)) } } impl Poly<ArkFr> for PolyData { fn new(size: usize) -> PolyData { Self { coeffs: vec![ArkFr::default(); size], } } fn get_coeff_at(&self, i: usize) -> ArkFr { self.coeffs[i] } fn set_coeff_at(&mut self, i: usize, x: &ArkFr) { self.coeffs[i] = *x; } fn get_coeffs(&self) -> &[ArkFr] { &self.coeffs } fn len(&self) -> usize { self.coeffs.len() } fn eval(&self, x: &ArkFr) -> ArkFr { eval_poly(self, x) } fn scale(&mut self) { scale_poly(self); } fn unscale(&mut self) { unscale_poly(self); } fn inverse(&mut self, new_len: usize) -> Result<Self, String> { poly_inverse(self, new_len) } fn div(&mut self, x: &Self) -> Result<Self, String> { if x.len() >= self.len() || x.len() < 128 { poly_long_div(self, x) } else { poly_fast_div(self, x) } } fn long_div(&mut self, x: &Self) -> Result<Self, String> { poly_long_div(self, x) } fn fast_div(&mut self, x: &Self) -> Result<Self, String> { poly_fast_div(self, x) } fn mul_direct(&mut self, x: &Self, len: usize) -> Result<Self, String> { poly_mul_direct(self, x, len) } } impl FFTSettingsPoly<ArkFr, PolyData, LFFTSettings> for LFFTSettings { fn poly_mul_fft( a: &PolyData, x: &PolyData, len: usize, fs: Option<&LFFTSettings>, ) -> Result<PolyData, String> { poly_mul_fft(a, x, fs, len) } } impl Default for LFFTSettings { fn default() -> Self { Self { max_width: 0, root_of_unity: ArkFr::zero(), reverse_roots_of_unity: Vec::new(), roots_of_unity: Vec::new(), brp_roots_of_unity: Vec::new(), } } } impl FFTSettings<ArkFr> for LFFTSettings { fn new(scale: usize) -> Result<LFFTSettings, String> { if scale >= SCALE2_ROOT_OF_UNITY.len() { return Err(String::from( "Scale is expected to be within root of unity matrix row size", )); } let max_width: usize = 1 << scale; let root_of_unity = ArkFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[scale]); let roots_of_unity = expand_root_of_unity(&root_of_unity, max_width)?; let mut brp_roots_of_unity = roots_of_unity.clone(); brp_roots_of_unity.pop(); reverse_bit_order(&mut brp_roots_of_unity)?; let mut reverse_roots_of_unity = roots_of_unity.clone(); reverse_roots_of_unity.reverse(); Ok(LFFTSettings { max_width, root_of_unity, reverse_roots_of_unity, roots_of_unity, brp_roots_of_unity, }) } fn get_max_width(&self) -> usize { self.max_width } fn get_reverse_roots_of_unity_at(&self, i: usize) -> ArkFr { self.reverse_roots_of_unity[i] } fn get_reversed_roots_of_unity(&self) -> &[ArkFr] { &self.reverse_roots_of_unity } fn get_roots_of_unity_at(&self, i: usize) -> ArkFr { self.roots_of_unity[i] } fn get_roots_of_unity(&self) -> &[ArkFr] { &self.roots_of_unity } fn get_brp_roots_of_unity(&self) -> &[ArkFr] { &self.brp_roots_of_unity } fn get_brp_roots_of_unity_at(&self, i: usize) -> ArkFr { self.brp_roots_of_unity[i] } } fn toeplitz_part_1( field_elements_per_ext_blob: usize, output: &mut [ArkG1], x: &[ArkG1], s: &LFFTSettings, ) -> Result<(), String> { let n = x.len(); let n2 = n * 2; let mut x_ext = vec![ArkG1::identity(); n2]; x_ext[..n].copy_from_slice(x); let x_ext = &x_ext[..]; /* Ensure the length is valid */ if x_ext.len() > field_elements_per_ext_blob || !x_ext.len().is_power_of_two() { return Err("Invalid input size".to_string()); } let roots_stride = field_elements_per_ext_blob / x_ext.len(); fft_g1_fast(output, x_ext, 1, &s.roots_of_unity, roots_stride); Ok(()) } impl KZGSettings<ArkFr, ArkG1, ArkG2, LFFTSettings, PolyData, ArkFp, ArkG1Affine, ArkG1ProjAddAffine> for LKZGSettings { fn new( g1_monomial: &[ArkG1], g1_lagrange_brp: &[ArkG1], g2_monomial: &[ArkG2], fft_settings: &LFFTSettings, cell_size: usize, ) -> Result<LKZGSettings, String> { if g1_monomial.len() != g1_lagrange_brp.len() { return Err("G1 point length mismatch".to_string()); } let field_elements_per_blob = g1_monomial.len(); let field_elements_per_ext_blob = field_elements_per_blob * 2; let n = field_elements_per_ext_blob / 2; let k = n / cell_size; let k2 = 2 * k; let mut points = vec![ArkG1::default(); k2]; let mut x = vec![ArkG1::default(); k]; let mut x_ext_fft_columns = vec![vec![ArkG1::default(); cell_size]; k2]; for offset in 0..cell_size { let start = n - cell_size - 1 - offset; for (i, p) in x.iter_mut().enumerate().take(k - 1) { let j = start - i * cell_size; *p = g1_monomial[j]; } x[k - 1] = ArkG1::identity(); toeplitz_part_1(field_elements_per_ext_blob, &mut points, &x, fft_settings)?; for row in 0..k2 { x_ext_fft_columns[row][offset] = points[row]; } } Ok(Self { g1_values_monomial: g1_monomial.to_vec(), g1_values_lagrange_brp: g1_lagrange_brp.to_vec(), g2_values_monomial: g2_monomial.to_vec(), fs: fft_settings.clone(), precomputation: precompute(g1_lagrange_brp, &x_ext_fft_columns) .ok() .flatten() .map(Arc::new), x_ext_fft_columns, cell_size, }) } fn commit_to_poly(&self, p: &PolyData) -> Result<ArkG1, String> { if p.coeffs.len() > self.g1_values_monomial.len() { return Err(String::from("Polynomial is longer than secret g1")); } let mut out = ArkG1::default(); g1_linear_combination( &mut out, &self.g1_values_monomial, &p.coeffs, p.coeffs.len(), None, ); Ok(out) } fn compute_proof_single(&self, p: &PolyData, x: &ArkFr) -> Result<ArkG1, String> { if p.coeffs.is_empty() { return Err(String::from("Polynomial must not be empty")); } // `-(x0^n)`, where `n` is `1` let divisor_0 = x.negate(); // Calculate `q = p / (x^n - x0^n)` for our reduced case (see `compute_proof_multi` for // generic implementation) let mut out_coeffs = Vec::from(&p.coeffs[1..]); for i in (1..out_coeffs.len()).rev() { let tmp = out_coeffs[i].mul(&divisor_0); out_coeffs[i - 1] = out_coeffs[i - 1].sub(&tmp); } let q = PolyData { coeffs: out_coeffs }; let ret = self.commit_to_poly(&q)?; Ok(ret) // Ok(compute_single(p, x, self)) } fn check_proof_single( &self, com: &ArkG1, proof: &ArkG1, x: &ArkFr, y: &ArkFr, ) -> Result<bool, String> { let x_g2: ArkG2 = G2_GENERATOR.mul(x); let s_minus_x: ArkG2 = self.g2_values_monomial[1].sub(&x_g2); let y_g1 = G1_GENERATOR.mul(y); let commitment_minus_y: ArkG1 = com.sub(&y_g1); Ok(pairings_verify( &commitment_minus_y, &G2_GENERATOR, proof, &s_minus_x, )) } fn compute_proof_multi(&self, p: &PolyData, x: &ArkFr, n: usize) -> Result<ArkG1, String> { if p.coeffs.is_empty() { return Err(String::from("Polynomial must not be empty")); } if !n.is_power_of_two() { return Err(String::from("n must be a power of two")); } // Construct x^n - x0^n = (x - x0.w^0)(x - x0.w^1)...(x - x0.w^(n-1)) let mut divisor = PolyData { coeffs: Vec::with_capacity(n + 1), }; // -(x0^n) let x_pow_n = x.pow(n); divisor.coeffs.push(x_pow_n.negate()); // Zeros for _ in 1..n { divisor.coeffs.push(ArkFr { fr: Fr::zero() }); } // x^n divisor.coeffs.push(ArkFr { fr: Fr::one() }); let mut new_polina = p.clone(); // Calculate q = p / (x^n - x0^n) // let q = p.div(&divisor).unwrap(); let q = new_polina.div(&divisor)?; let ret = self.commit_to_poly(&q)?; Ok(ret) } fn check_proof_multi( &self, com: &ArkG1, proof: &ArkG1, x: &ArkFr, ys: &[ArkFr], n: usize, ) -> Result<bool, String> { if !n.is_power_of_two() { return Err(String::from("n is not a power of two")); } // Interpolate at a coset. let mut interp = PolyData { coeffs: self.fs.fft_fr(ys, true)?, }; let inv_x = x.inverse(); // Not euclidean? let mut inv_x_pow = inv_x; for i in 1..n { interp.coeffs[i] = interp.coeffs[i].mul(&inv_x_pow); inv_x_pow = inv_x_pow.mul(&inv_x); } // [x^n]_2 let x_pow = inv_x_pow.inverse(); let xn2 = G2_GENERATOR.mul(&x_pow); // [s^n - x^n]_2 let xn_minus_yn = self.g2_values_monomial[n].sub(&xn2); // [interpolation_polynomial(s)]_1 let is1 = self.commit_to_poly(&interp).unwrap(); // [commitment - interpolation_polynomial(s)]_1 = [commit]_1 - [interpolation_polynomial(s)]_1 let commit_minus_interp = com.sub(&is1); let ret = pairings_verify(&commit_minus_interp, &G2_GENERATOR, proof, &xn_minus_yn); Ok(ret) } fn get_roots_of_unity_at(&self, i: usize) -> ArkFr { self.fs.get_roots_of_unity_at(i) } fn get_fft_settings(&self) -> &LFFTSettings { &self.fs } fn get_g1_lagrange_brp(&self) -> &[ArkG1] { &self.g1_values_lagrange_brp } fn get_g1_monomial(&self) -> &[ArkG1] { &self.g1_values_monomial } fn get_g2_monomial(&self) -> &[ArkG2] { &self.g2_values_monomial } fn get_precomputation( &self, ) -> Option<&PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>> { self.precomputation.as_ref().map(|v| v.as_ref()) } fn get_x_ext_fft_columns(&self) -> &[Vec<ArkG1>] { &self.x_ext_fft_columns } fn get_cell_size(&self) -> usize { self.cell_size } } impl<'a> TryFrom<&'a CKZGSettings> for LKZGSettings { type Error = String; fn try_from(c_settings: &'a CKZGSettings) -> Result<Self, Self::Error> { Ok(LKZGSettings { fs: fft_settings_to_rust(c_settings)?, g1_values_monomial: unsafe { core::slice::from_raw_parts( c_settings.g1_values_monomial, eth::FIELD_ELEMENTS_PER_BLOB, ) } .iter() .map(|r| ArkG1::from_blst_p1(*r)) .collect::<Vec<_>>(), g1_values_lagrange_brp: unsafe { core::slice::from_raw_parts( c_settings.g1_values_lagrange_brp, eth::FIELD_ELEMENTS_PER_BLOB, ) } .iter() .map(|r| ArkG1::from_blst_p1(*r)) .collect::<Vec<_>>(), g2_values_monomial: unsafe { core::slice::from_raw_parts( c_settings.g2_values_monomial, eth::TRUSTED_SETUP_NUM_G2_POINTS, ) } .iter() .map(|r| ArkG2::from_blst_p2(*r)) .collect::<Vec<_>>(), x_ext_fft_columns: unsafe { core::slice::from_raw_parts( c_settings.x_ext_fft_columns, 2 * ((eth::FIELD_ELEMENTS_PER_EXT_BLOB / 2) / eth::FIELD_ELEMENTS_PER_CELL), ) } .iter() .map(|it| { unsafe { core::slice::from_raw_parts(*it, eth::FIELD_ELEMENTS_PER_CELL) } .iter() .map(|it| ArkG1::from_blst_p1(*it)) .collect::<Vec<_>>() }) .collect::<Vec<_>>(), #[allow(static_mut_refs)] precomputation: unsafe { PRECOMPUTATION_TABLES.get_precomputation(c_settings) }, cell_size: eth::FIELD_ELEMENTS_PER_CELL, }) } } type ArkFpInt = <ark_bls12_381::g1::Config as CurveConfig>::BaseField; #[repr(C)] #[derive(Debug, Default, Clone, Copy, Eq, PartialEq)] pub struct ArkFp(pub ArkFpInt); impl G1Fp for ArkFp { fn is_zero(&self) -> bool { self.0.is_zero() } fn set_zero(&mut self) { self.0.set_zero(); } fn is_one(&self) -> bool { self.0.is_one() } fn set_one(&mut self) { self.0.set_one(); } fn inverse(&self) -> Option<Self> { Some(Self(self.0.inverse().unwrap())) } fn square(&self) -> Self { Self(self.0.square()) } fn double(&self) -> Self { Self(self.0.double()) } fn from_underlying_arr(arr: &[u64; 6]) -> Self { let mut default = ArkFpInt::default(); default.0 .0 = *arr; Self(default) } fn neg_assign(&mut self) { self.0 = -self.0; } fn mul_assign_fp(&mut self, b: &Self) { self.0 *= b.0; } fn sub_assign_fp(&mut self, b: &Self) { self.0 -= b.0; } fn add_assign_fp(&mut self, b: &Self) { self.0 += b.0; } fn mul3(&self) -> Self { Self(self.0 * ArkFpInt::from(3)) } fn zero() -> Self { Self(ArkFpInt::ZERO) } fn one() -> Self { Self(ArkFpInt::ONE) } fn bls12_381_rx_p() -> Self { Self(blst_fp_into_pc_fq(&blst_fp { l: [ 8505329371266088957, 17002214543764226050, 6865905132761471162, 8632934651105793861, 6631298214892334189, 1582556514881692819, ], })) } } impl G1GetFp<ArkFp> for ArkG1 { fn x(&self) -> &ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&self.0.x) } } fn y(&self) -> &ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&self.0.y) } } fn z(&self) -> &ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&self.0.z) } } fn x_mut(&mut self) -> &mut ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&mut self.0.x) } } fn y_mut(&mut self) -> &mut ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&mut self.0.y) } } fn z_mut(&mut self) -> &mut ArkFp { unsafe { // Transmute safe due to repr(C) on FsFp core::mem::transmute(&mut self.0.z) } } fn from_jacobian(x: ArkFp, y: ArkFp, z: ArkFp) -> Self { Self(Projective { x: x.0, y: y.0, z: z.0, }) } } #[repr(C)] #[derive(Debug, Default, PartialEq, Eq, Clone, Copy)] pub struct ArkG1Affine { pub aff: G1Affine, } impl<'a> Arbitrary<'a> for ArkG1Affine { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> { Ok(ArkG1Affine::into_affine( &ArkG1::generator().mul(&u.arbitrary()?), )) } } impl G1AffineTrait<ArkG1, ArkFp> for ArkG1Affine { fn into_affine(g1: &ArkG1) -> Self { Self { aff: g1.0.into_affine(), } } fn into_affines(g1: &[ArkG1]) -> Vec<Self> { let ark_points: &[Projective<g1::Config>] = unsafe { core::mem::transmute(g1) }; let ark_points = CurveGroup::normalize_batch(ark_points); unsafe { core::mem::transmute(ark_points) } } fn into_affines_loc(out: &mut [Self], g1: &[ArkG1]) { out.copy_from_slice(&Self::into_affines(g1)); } fn to_proj(&self) -> ArkG1 { ArkG1(self.aff.into_group()) } fn x(&self) -> &ArkFp { unsafe { core::mem::transmute(&self.aff.x) } } fn y(&self) -> &ArkFp { unsafe { core::mem::transmute(&self.aff.y) } } fn is_infinity(&self) -> bool { self.aff.infinity } fn is_zero(&self) -> bool { self.aff.is_zero() } fn zero() -> Self { Self { aff: G1Affine { x: ArkFp::zero().0, y: ArkFp::zero().0, infinity: true, }, } } fn x_mut(&mut self) -> &mut ArkFp { unsafe { core::mem::transmute(&mut self.aff.x) } } fn y_mut(&mut self) -> &mut ArkFp { unsafe { core::mem::transmute(&mut self.aff.y) } } fn neg(&self) -> Self { Self { aff: -self.aff } } fn from_xy(x: ArkFp, y: ArkFp) -> Self { Self { aff: G1Affine::new(x.0, y.0), } } fn to_bytes_uncompressed(&self) -> [u8; 96] { let mut buffer = [0u8; 96]; self.aff .serialize_uncompressed(&mut buffer[..]) .expect("impossible to happen"); buffer } fn from_bytes_uncompressed(bytes: [u8; 96]) -> Result<Self, String> { G1Affine::deserialize_uncompressed(&bytes[..]) .map(|aff| ArkG1Affine { aff }) .map_err(|err| err.to_string()) } } #[derive(Debug)] pub struct ArkG1ProjAddAffine; impl G1ProjAddAffine<ArkG1, ArkFp, ArkG1Affine> for ArkG1ProjAddAffine { fn add_assign_affine(proj: &mut ArkG1, aff: &ArkG1Affine) { proj.0 += aff.aff; } fn add_or_double_assign_affine(proj: &mut ArkG1, aff: &ArkG1Affine) { proj.0 += aff.aff; } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/zero_poly.rs
arkworks4/src/zero_poly.rs
use super::kzg_proofs::FFTSettings; use super::utils::{blst_poly_into_pc_poly, pc_poly_into_blst_poly, PolyData}; use crate::kzg_types::ArkFr as BlstFr; use kzg::common_utils::next_pow_of_2; use kzg::{FFTFr, Fr as FrTrait, ZeroPoly}; use std::cmp::{min, Ordering}; use std::ops::Neg; pub(crate) fn pad_poly(poly: &PolyData, new_length: usize) -> Result<Vec<BlstFr>, String> { if new_length <= poly.coeffs.len() { return Ok(poly.coeffs.clone()); } let mut out = poly.coeffs.to_vec(); for _i in poly.coeffs.len()..new_length { out.push(BlstFr::zero()) } Ok(out) } impl ZeroPoly<BlstFr, PolyData> for FFTSettings { fn do_zero_poly_mul_partial( &self, indices: &[usize], stride: usize, ) -> Result<PolyData, String> { if indices.is_empty() { return Err(String::from("idx array must be non-zero")); } let blstpoly = PolyData { coeffs: vec![BlstFr::one(); indices.len() + 1], }; let mut poly = blst_poly_into_pc_poly(&blstpoly.coeffs); poly.coeffs[0] = (self.roots_of_unity[indices[0] * stride]).fr.neg(); for (i, indice) in indices.iter().enumerate().skip(1) { let neg_di = (self.roots_of_unity[indice * stride]).fr.neg(); poly.coeffs[i] = neg_di + poly.coeffs[i - 1]; let mut j = i - 1; while j > 0 { let temp = poly.coeffs[j] * neg_di; poly.coeffs[j] = temp + poly.coeffs[j - 1]; j -= 1; } poly.coeffs[0] *= neg_di; } Ok(pc_poly_into_blst_poly(poly)) } fn reduce_partials(&self, len_out: usize, partials: &[PolyData]) -> Result<PolyData, String> { let mut out_degree: usize = 0; for partial in partials { out_degree += partial.coeffs.len() - 1; } if out_degree + 1 > len_out { return Err(String::from("Expected domain size to be a power of 2")); } let mut p_partial = pad_poly(&partials[0], len_out).unwrap(); let mut mul_eval_ps = self.fft_fr(&p_partial, false).unwrap(); for partial in partials.iter().skip(1) { p_partial = pad_poly(partial, len_out)?; let p_eval = self.fft_fr(&p_partial, false).unwrap(); for j in 0..len_out { mul_eval_ps[j].fr *= p_eval[j].fr; } } let coeffs = self.fft_fr(&mul_eval_ps, true)?; let out = PolyData { coeffs: coeffs[..(out_degree + 1)].to_vec(), }; Ok(out) } fn zero_poly_via_multiplication( &self, length: usize, missing_indices: &[usize], ) -> Result<(Vec<BlstFr>, PolyData), String> { let zero_eval: Vec<BlstFr>; let mut zero_poly: PolyData; if missing_indices.is_empty() { zero_eval = Vec::new(); zero_poly = PolyData { coeffs: Vec::new() }; return Ok((zero_eval, zero_poly)); } if missing_indices.len() >= length { return Err(String::from("Missing idxs greater than domain size")); } else if length > self.max_width { return Err(String::from( "Domain size greater than fft_settings.max_width", )); } else if !length.is_power_of_two() { return Err(String::from("Domain size must be a power of 2")); } let degree_of_partial = 256; let missing_per_partial = degree_of_partial - 1; let domain_stride = self.max_width / length; let mut partial_count = (missing_per_partial + missing_indices.len() - 1) / missing_per_partial; let domain_ceiling = min(next_pow_of_2(partial_count * degree_of_partial), length); if missing_indices.len() <= missing_per_partial { zero_poly = self.do_zero_poly_mul_partial(missing_indices, domain_stride)?; } else { let mut work = vec![BlstFr::zero(); next_pow_of_2(partial_count * degree_of_partial)]; let mut partial_lens = Vec::new(); let mut offset = 0; let mut out_offset = 0; let max = missing_indices.len(); for _i in 0..partial_count { let end = min(offset + missing_per_partial, max); let mut partial = self.do_zero_poly_mul_partial(&missing_indices[offset..end], domain_stride)?; partial.coeffs = pad_poly(&partial, degree_of_partial)?; work.splice( out_offset..(out_offset + degree_of_partial), partial.coeffs.to_vec(), ); partial_lens.push(degree_of_partial); offset += missing_per_partial; out_offset += degree_of_partial; } partial_lens[partial_count - 1] = 1 + missing_indices.len() - (partial_count - 1) * missing_per_partial; let reduction_factor = 4; while partial_count > 1 { let reduced_count = 1 + (partial_count - 1) / reduction_factor; let partial_size = next_pow_of_2(partial_lens[0]); for i in 0..reduced_count { let start = i * reduction_factor; let out_end = min((start + reduction_factor) * partial_size, domain_ceiling); let reduced_len = min(out_end - start * partial_size, length); let partials_num = min(reduction_factor, partial_count - start); let mut partial_vec = Vec::new(); for j in 0..partials_num { let k = (start + j) * partial_size; partial_vec.push(PolyData { coeffs: work[k..(k + partial_lens[i + j])].to_vec(), }); } if partials_num > 1 { let mut reduced_poly = self.reduce_partials(reduced_len, &partial_vec)?; partial_lens[i] = reduced_poly.coeffs.len(); reduced_poly.coeffs = pad_poly(&reduced_poly, partial_size * partials_num)?; work.splice( (start * partial_size) ..(start * partial_size + reduced_poly.coeffs.len()), reduced_poly.coeffs, ); } else { partial_lens[i] = partial_lens[start]; } } partial_count = reduced_count; } zero_poly = PolyData { coeffs: work }; } match zero_poly.coeffs.len().cmp(&length) { Ordering::Less => zero_poly.coeffs = pad_poly(&zero_poly, length)?, Ordering::Greater => zero_poly.coeffs = zero_poly.coeffs[..length].to_vec(), Ordering::Equal => {} } zero_eval = self.fft_fr(&zero_poly.coeffs, false)?; Ok((zero_eval, zero_poly)) } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/fk20_proofs.rs
arkworks4/src/fk20_proofs.rs
use crate::consts::G1_IDENTITY; use crate::kzg_proofs::{FFTSettings, KZGSettings}; use crate::kzg_types::{ArkFp, ArkFr as BlstFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2}; use crate::utils::PolyData; use kzg::common_utils::reverse_bit_order; use kzg::{FFTFr, FK20MultiSettings, FK20SingleSettings, Fr, G1Mul, Poly, FFTG1, G1}; #[cfg(feature = "parallel")] use rayon::prelude::*; #[repr(C)] #[derive(Debug, Clone, Default)] pub struct KzgFK20SingleSettings { pub ks: KZGSettings, pub x_ext_fft: Vec<ArkG1>, pub x_ext_fft_len: usize, } #[repr(C)] #[derive(Debug, Clone, Default)] pub struct KzgFK20MultiSettings { pub ks: KZGSettings, pub chunk_len: usize, pub x_ext_fft_files: Vec<Vec<ArkG1>>, } impl FK20SingleSettings< BlstFr, ArkG1, ArkG2, FFTSettings, PolyData, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, > for KzgFK20SingleSettings { fn new(ks: &KZGSettings, n2: usize) -> Result<Self, String> { let n = n2 / 2; if n2 > ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n2.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } if n2 < 2 { return Err(String::from("n2 must be equal or greater than 2")); } let mut x = Vec::new(); for i in 0..(n - 1) { x.push(ks.g1_values_monomial[n - 2 - i]) } x.push(G1_IDENTITY); let new_ks = KZGSettings { fs: ks.fs.clone(), ..KZGSettings::default() }; Ok(KzgFK20SingleSettings { ks: new_ks, x_ext_fft: toeplitz_part_1(&x, &ks.fs).unwrap(), x_ext_fft_len: n2, }) } fn data_availability(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> { let n = p.len(); let n2 = n * 2; if n2 > self.ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } let mut out = fk20_single_da_opt(p, self).unwrap(); reverse_bit_order(&mut out)?; Ok(out) } fn data_availability_optimized(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> { fk20_single_da_opt(p, self) } } impl FK20MultiSettings< BlstFr, ArkG1, ArkG2, FFTSettings, PolyData, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, > for KzgFK20MultiSettings { fn new(ks: &KZGSettings, n2: usize, chunk_len: usize) -> Result<Self, String> { if n2 > ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n2.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } if n2 < 2 { return Err(String::from("n2 must be equal or greater than 2")); } if chunk_len > n2 / 2 { return Err(String::from("chunk_len must be equal or less than n2/2")); } if !chunk_len.is_power_of_two() { return Err(String::from("chunk_len must be power of 2")); } if chunk_len == 0 { return Err(String::from("chunk_len must be greater than 0")); } let n = n2 / 2; let k = n / chunk_len; let mut x_ext_fft_files = Vec::new(); for offset in 0..chunk_len { let mut x = vec![ArkG1::default(); k]; let start = if n >= chunk_len + 1 + offset { n - chunk_len - 1 - offset } else { 0 }; let mut j = start; for i in x.iter_mut().take(k - 1) { i.0 = ks.g1_values_monomial[j].0; if j >= chunk_len { j -= chunk_len; } else { j = 0; } } x[k - 1] = G1_IDENTITY; x_ext_fft_files.push(toeplitz_part_1(&x, &ks.fs).unwrap()); } let new_ks = KZGSettings { fs: ks.fs.clone(), ..KZGSettings::default() }; Ok(KzgFK20MultiSettings { ks: new_ks, x_ext_fft_files, chunk_len, }) } fn data_availability(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> { let n = p.len(); let n2 = n * 2; if n2 > self.ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } let mut out = fk20_multi_da_opt(p, self).unwrap(); reverse_bit_order(&mut out)?; Ok(out) } fn data_availability_optimized(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> { fk20_multi_da_opt(p, self) } } fn fk20_single_da_opt(p: &PolyData, fk: &KzgFK20SingleSettings) -> Result<Vec<ArkG1>, String> { let n = p.len(); let n2 = n * 2; if n2 > fk.ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } let outlen = 2 * p.len(); let toeplitz_coeffs = toeplitz_coeffs_step(p, outlen).unwrap(); let h_ext_fft = toeplitz_part_2(&toeplitz_coeffs, &fk.x_ext_fft, &fk.ks.fs).unwrap(); let h = toeplitz_part_3(&h_ext_fft, &fk.ks.fs).unwrap(); fk.ks.fs.fft_g1(&h, false) } fn fk20_multi_da_opt(p: &PolyData, fk: &KzgFK20MultiSettings) -> Result<Vec<ArkG1>, String> { let n = p.len(); let n2 = n * 2; if n2 > fk.ks.fs.max_width { return Err(String::from( "n2 must be equal or less than kzg settings max width", )); } if !n.is_power_of_two() { return Err(String::from("n2 must be power of 2")); } let n = n2 / 2; let k = n / fk.chunk_len; let k2 = k * 2; let mut h_ext_fft = Vec::new(); for _i in 0..k2 { h_ext_fft.push(G1_IDENTITY); } let mut toeplitz_coeffs = PolyData::new(n2 / fk.chunk_len); for i in 0..fk.chunk_len { toeplitz_coeffs = toeplitz_coeffs_stride(p, i, fk.chunk_len, toeplitz_coeffs.len()).unwrap(); let h_ext_fft_file = toeplitz_part_2(&toeplitz_coeffs, &fk.x_ext_fft_files[i], &fk.ks.fs).unwrap(); for j in 0..k2 { h_ext_fft[j] = h_ext_fft[j].add_or_dbl(&h_ext_fft_file[j]); } } // Calculate `h` let mut h = toeplitz_part_3(&h_ext_fft, &fk.ks.fs).unwrap(); // Overwrite the second half of `h` with zero for i in h.iter_mut().take(k2).skip(k) { i.0 = G1_IDENTITY.0; } fk.ks.fs.fft_g1(&h, false) } fn toeplitz_coeffs_step(p: &PolyData, outlen: usize) -> Result<PolyData, String> { toeplitz_coeffs_stride(p, 0, 1, outlen) } fn toeplitz_coeffs_stride( poly: &PolyData, offset: usize, stride: usize, outlen: usize, ) -> Result<PolyData, String> { let n = poly.len(); if stride == 0 { return Err(String::from("stride must be greater than 0")); } let k = n / stride; let k2 = k * 2; if outlen < k2 { return Err(String::from("outlen must be equal or greater than k2")); } let mut out = PolyData::new(outlen); out.set_coeff_at(0, &poly.coeffs[n - 1 - offset]); let mut i = 1; while i <= (k + 1) && i < k2 { out.set_coeff_at(i, &BlstFr::zero()); i += 1; } let mut j = 2 * stride - offset - 1; for i in (k + 2)..k2 { out.set_coeff_at(i, &poly.coeffs[j]); j += stride; } Ok(out) } fn toeplitz_part_1(x: &[ArkG1], fs: &FFTSettings) -> Result<Vec<ArkG1>, String> { let n = x.len(); let n2 = n * 2; let mut x_ext = Vec::new(); for i in x.iter().take(n) { x_ext.push(*i); } for _i in n..n2 { x_ext.push(G1_IDENTITY); } fs.fft_g1(&x_ext, false) } fn toeplitz_part_2( toeplitz_coeffs: &PolyData, x_ext_fft: &[ArkG1], fs: &FFTSettings, ) -> Result<Vec<ArkG1>, String> { let toeplitz_coeffs_fft = fs.fft_fr(&toeplitz_coeffs.coeffs, false).unwrap(); #[cfg(feature = "parallel")] { let out: Vec<_> = (0..toeplitz_coeffs.len()) .into_par_iter() .map(|i| x_ext_fft[i].mul(&toeplitz_coeffs_fft[i])) .collect(); Ok(out) } #[cfg(not(feature = "parallel"))] { let mut out = Vec::new(); for i in 0..toeplitz_coeffs.len() { out.push(x_ext_fft[i].mul(&toeplitz_coeffs_fft[i])); } Ok(out) } } fn toeplitz_part_3(h_ext_fft: &[ArkG1], fs: &FFTSettings) -> Result<Vec<ArkG1>, String> { let n = h_ext_fft.len() / 2; let mut out = fs.fft_g1(h_ext_fft, true).unwrap(); // Zero the second half of h for i in out.iter_mut().take(h_ext_fft.len()).skip(n) { i.0 = G1_IDENTITY.0; } Ok(out) }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/utils.rs
arkworks4/src/utils.rs
use crate::kzg_proofs::FFTSettings; use crate::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine}; use ark_bls12_381::{g1, g2, Fq, Fq2, Fr as Bls12Fr}; use ark_ec::models::short_weierstrass::Projective; use ark_ff::Fp2; use ark_poly::univariate::DensePolynomial as DensePoly; use ark_poly::DenseUVPolynomial; use kzg::eip_4844::PrecomputationTableManager; use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_fr, blst_p1, blst_p2, CKZGSettings}; use kzg::eth; #[derive(Debug, PartialEq, Eq)] pub struct Error; #[derive(Debug, Clone, Eq, PartialEq, Default)] pub struct PolyData { pub coeffs: Vec<ArkFr>, } // FIXME: Store just dense poly here pub fn pc_poly_into_blst_poly(poly: DensePoly<Bls12Fr>) -> PolyData { let mut bls_pol: Vec<ArkFr> = { Vec::new() }; for x in poly.coeffs { bls_pol.push(ArkFr { fr: x }); } PolyData { coeffs: bls_pol } } pub fn blst_poly_into_pc_poly(pd: &[ArkFr]) -> DensePoly<Bls12Fr> { let mut poly: Vec<Bls12Fr> = vec![Bls12Fr::default(); pd.len()]; for i in 0..pd.len() { poly[i] = pd[i].fr; } DensePoly::from_coefficients_vec(poly) } pub const fn pc_fq_into_blst_fp(fq: Fq) -> blst_fp { blst_fp { l: fq.0 .0 } } pub const fn blst_fr_into_pc_fr(fr: blst_fr) -> Bls12Fr { Bls12Fr { 0: ark_ff::BigInt(fr.l), 1: core::marker::PhantomData, } } pub const fn pc_fr_into_blst_fr(fr: Bls12Fr) -> blst_fr { blst_fr { l: fr.0 .0 } } pub const fn blst_fp_into_pc_fq(fp: &blst_fp) -> Fq { Fq { 0: ark_ff::BigInt(fp.l), 1: core::marker::PhantomData, } } pub const fn blst_fp2_into_pc_fq2(fp: &blst_fp2) -> Fq2 { Fp2 { c0: blst_fp_into_pc_fq(&fp.fp[0]), c1: blst_fp_into_pc_fq(&fp.fp[1]), } } pub const fn blst_p1_into_pc_g1projective(p1: &blst_p1) -> Projective<g1::Config> { Projective { x: blst_fp_into_pc_fq(&p1.x), y: blst_fp_into_pc_fq(&p1.y), z: blst_fp_into_pc_fq(&p1.z), } } pub const fn pc_g1projective_into_blst_p1(p1: Projective<g1::Config>) -> blst_p1 { blst_p1 { x: blst_fp { l: p1.x.0 .0 }, y: blst_fp { l: p1.y.0 .0 }, z: blst_fp { l: p1.z.0 .0 }, } } pub const fn blst_p2_into_pc_g2projective(p2: &blst_p2) -> Projective<g2::Config> { Projective { x: blst_fp2_into_pc_fq2(&p2.x), y: blst_fp2_into_pc_fq2(&p2.y), z: blst_fp2_into_pc_fq2(&p2.z), } } pub const fn pc_g2projective_into_blst_p2(p2: Projective<g2::Config>) -> blst_p2 { blst_p2 { x: blst_fp2 { fp: [blst_fp { l: p2.x.c0.0 .0 }, blst_fp { l: p2.x.c1.0 .0 }], }, y: blst_fp2 { fp: [blst_fp { l: p2.y.c0.0 .0 }, blst_fp { l: p2.y.c1.0 .0 }], }, z: blst_fp2 { fp: [blst_fp { l: p2.z.c0.0 .0 }, blst_fp { l: p2.z.c1.0 .0 }], }, } } pub(crate) fn fft_settings_to_rust(c_settings: *const CKZGSettings) -> Result<FFTSettings, String> { let settings = unsafe { &*c_settings }; let roots_of_unity = unsafe { core::slice::from_raw_parts( settings.roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1, ) .iter() .map(|r| ArkFr::from_blst_fr(*r)) .collect::<Vec<ArkFr>>() }; let brp_roots_of_unity = unsafe { core::slice::from_raw_parts( settings.brp_roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB, ) .iter() .map(|r| ArkFr::from_blst_fr(*r)) .collect::<Vec<ArkFr>>() }; let reverse_roots_of_unity = unsafe { core::slice::from_raw_parts( settings.reverse_roots_of_unity, eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1, ) .iter() .map(|r| ArkFr::from_blst_fr(*r)) .collect::<Vec<ArkFr>>() }; Ok(FFTSettings { max_width: eth::FIELD_ELEMENTS_PER_EXT_BLOB, root_of_unity: roots_of_unity[0], roots_of_unity, brp_roots_of_unity, reverse_roots_of_unity, }) } pub(crate) static mut PRECOMPUTATION_TABLES: PrecomputationTableManager< ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, > = PrecomputationTableManager::new();
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/fft_g1.rs
arkworks4/src/fft_g1.rs
use crate::consts::G1_GENERATOR; use crate::kzg_proofs::FFTSettings; use crate::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine}; use crate::kzg_types::ArkG1ProjAddAffine; use kzg::msm::msm_impls::msm; use kzg::msm::precompute::PrecomputationTable; use kzg::{Fr as KzgFr, G1Mul}; use kzg::{FFTG1, G1}; use std::ops::MulAssign; extern crate alloc; pub fn g1_linear_combination( out: &mut ArkG1, points: &[ArkG1], scalars: &[ArkFr], len: usize, precomputation: Option< &PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>, >, ) { *out = msm::<ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, ArkFr>( points, scalars, len, precomputation, ); } pub fn make_data(data: usize) -> Vec<ArkG1> { let mut vec = Vec::new(); if data != 0 { vec.push(G1_GENERATOR); for i in 1..data as u64 { let res = vec[(i - 1) as usize].add_or_dbl(&G1_GENERATOR); vec.push(res); } } vec } impl FFTG1<ArkG1> for FFTSettings { fn fft_g1(&self, data: &[ArkG1], inverse: bool) -> Result<Vec<ArkG1>, String> { if data.len() > self.max_width { return Err(String::from("data length is longer than allowed max width")); } if !data.len().is_power_of_two() { return Err(String::from("data length is not power of 2")); } let stride: usize = self.max_width / data.len(); let mut ret = vec![ArkG1::default(); data.len()]; let roots = if inverse { &self.reverse_roots_of_unity } else { &self.roots_of_unity }; fft_g1_fast(&mut ret, data, 1, roots, stride); if inverse { let inv_fr_len = ArkFr::from_u64(data.len() as u64).inverse(); ret[..data.len()] .iter_mut() .for_each(|f| f.0.mul_assign(&inv_fr_len.fr)); } Ok(ret) } } pub fn fft_g1_slow( ret: &mut [ArkG1], data: &[ArkG1], stride: usize, roots: &[ArkFr], roots_stride: usize, ) { for i in 0..data.len() { ret[i] = data[0].mul(&roots[0]); for j in 1..data.len() { let jv = data[j * stride]; let r = roots[((i * j) % data.len()) * roots_stride]; let v = jv.mul(&r); ret[i] = ret[i].add_or_dbl(&v); } } } pub fn fft_g1_fast( ret: &mut [ArkG1], data: &[ArkG1], stride: usize, roots: &[ArkFr], roots_stride: usize, ) { let half = ret.len() / 2; if half > 0 { #[cfg(feature = "parallel")] { let (lo, hi) = ret.split_at_mut(half); rayon::join( || fft_g1_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2), || fft_g1_fast(lo, data, stride * 2, roots, roots_stride * 2), ); } #[cfg(not(feature = "parallel"))] { fft_g1_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2); fft_g1_fast( &mut ret[half..], &data[stride..], stride * 2, roots, roots_stride * 2, ); } for i in 0..half { let y_times_root = ret[i + half].mul(&roots[i * roots_stride]); ret[i + half] = ret[i].sub(&y_times_root); ret[i] = ret[i].add_or_dbl(&y_times_root); } } else { ret[0] = data[0]; } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/recover.rs
arkworks4/src/recover.rs
use crate::consts::SCALE_FACTOR; use crate::kzg_proofs::FFTSettings; use crate::kzg_types::ArkFr as BlstFr; use crate::utils::PolyData; use kzg::{FFTFr, Fr, Poly, PolyRecover, ZeroPoly}; #[cfg(feature = "parallel")] use kzg::common_utils::next_pow_of_2; #[cfg(feature = "parallel")] static mut INVERSE_FACTORS: Vec<BlstFr> = Vec::new(); #[cfg(feature = "parallel")] static mut UNSCALE_FACTOR_POWERS: Vec<BlstFr> = Vec::new(); #[allow(clippy::needless_range_loop)] pub fn scale_poly(p: &mut PolyData) { let scale_factor = BlstFr::from_u64(SCALE_FACTOR); let inv_factor = scale_factor.inverse(); #[allow(static_mut_refs)] #[cfg(feature = "parallel")] { let optim = next_pow_of_2(p.len() - 1); if optim <= 1024 { unsafe { if INVERSE_FACTORS.len() < p.len() { if INVERSE_FACTORS.is_empty() { INVERSE_FACTORS.push(BlstFr::one()); } for i in (INVERSE_FACTORS.len())..p.len() { INVERSE_FACTORS.push(INVERSE_FACTORS[i - 1].mul(&inv_factor)); } } for i in 1..p.len() { p.coeffs[i] = p.coeffs[i].mul(&INVERSE_FACTORS[i]); } } } else { let mut factor_power = BlstFr::one(); for i in 1..p.len() { factor_power = factor_power.mul(&inv_factor); p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power)); } } } #[cfg(not(feature = "parallel"))] { let mut factor_power = BlstFr::one(); for i in 1..p.len() { factor_power = factor_power.mul(&inv_factor); p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power)); } } } #[allow(clippy::needless_range_loop)] pub fn unscale_poly(p: &mut PolyData) { let scale_factor = BlstFr::from_u64(SCALE_FACTOR); #[allow(static_mut_refs)] #[cfg(feature = "parallel")] { unsafe { if UNSCALE_FACTOR_POWERS.len() < p.len() { if UNSCALE_FACTOR_POWERS.is_empty() { UNSCALE_FACTOR_POWERS.push(BlstFr::one()); } for i in (UNSCALE_FACTOR_POWERS.len())..p.len() { UNSCALE_FACTOR_POWERS.push(UNSCALE_FACTOR_POWERS[i - 1].mul(&scale_factor)); } } for i in 1..p.len() { p.coeffs[i] = p.coeffs[i].mul(&UNSCALE_FACTOR_POWERS[i]); } } } #[cfg(not(feature = "parallel"))] { let mut factor_power = BlstFr::one(); for i in 1..p.len() { factor_power = factor_power.mul(&scale_factor); p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power)); } } } impl PolyRecover<BlstFr, PolyData, FFTSettings> for PolyData { fn recover_poly_coeffs_from_samples( samples: &[Option<BlstFr>], fs: &FFTSettings, ) -> Result<Self, String> { if !samples.len().is_power_of_two() { return Err(String::from("samples lenght has to be power of 2")); } let mut missing = Vec::new(); for (i, sample) in samples.iter().enumerate() { if sample.is_none() { missing.push(i); } } if missing.len() > samples.len() / 2 { return Err(String::from( "Impossible to recover, too many shards are missing", )); } // Calculate `Z_r,I` let (zero_eval, mut zero_poly) = fs.zero_poly_via_multiplication(samples.len(), missing.as_slice())?; // Check all is well for (i, item) in zero_eval.iter().enumerate().take(samples.len()) { if samples[i].is_none() != item.is_zero() { return Err(String::from("sample and item are both zero")); } } // Construct E * Z_r,I: the loop makes the evaluation polynomial let mut poly_evaluations_with_zero = vec![BlstFr::zero(); samples.len()]; for i in 0..samples.len() { if samples[i].is_none() { poly_evaluations_with_zero[i] = BlstFr::zero(); } else { poly_evaluations_with_zero[i] = samples[i].unwrap().mul(&zero_eval[i]); } } // Now inverse FFT so that poly_with_zero is (E * Z_r,I)(x) = (D * Z_r,I)(x) let mut poly_with_zero = PolyData { coeffs: fs .fft_fr(poly_evaluations_with_zero.as_slice(), true) .unwrap(), }; #[cfg(feature = "parallel")] let optim = next_pow_of_2(poly_with_zero.len() - 1); #[cfg(feature = "parallel")] { if optim > 1024 { rayon::join( || scale_poly(&mut poly_with_zero), || scale_poly(&mut zero_poly), ); } else { scale_poly(&mut poly_with_zero); scale_poly(&mut zero_poly); } } #[cfg(not(feature = "parallel"))] { scale_poly(&mut poly_with_zero); scale_poly(&mut zero_poly); } // Q1 = (D * Z_r,I)(k * x) let scaled_poly_with_zero = poly_with_zero; // Renaming // Q2 = Z_r,I(k * x) let scaled_zero_poly = zero_poly.coeffs; // Renaming let eval_scaled_poly_with_zero; let eval_scaled_zero_poly; #[cfg(feature = "parallel")] { if optim > 1024 { let mut eval_scaled_poly_with_zero_temp = vec![]; let mut eval_scaled_zero_poly_temp = vec![]; rayon::join( || { eval_scaled_poly_with_zero_temp = fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap() }, || eval_scaled_zero_poly_temp = fs.fft_fr(&scaled_zero_poly, false).unwrap(), ); eval_scaled_poly_with_zero = eval_scaled_poly_with_zero_temp; eval_scaled_zero_poly = eval_scaled_zero_poly_temp; } else { eval_scaled_poly_with_zero = fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap(); eval_scaled_zero_poly = fs.fft_fr(&scaled_zero_poly, false).unwrap(); } } #[cfg(not(feature = "parallel"))] { eval_scaled_poly_with_zero = fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap(); eval_scaled_zero_poly = fs.fft_fr(&scaled_zero_poly, false).unwrap(); } let mut eval_scaled_reconstructed_poly = eval_scaled_poly_with_zero.clone(); for i in 0..samples.len() { eval_scaled_reconstructed_poly[i] = eval_scaled_poly_with_zero[i] .div(&eval_scaled_zero_poly[i]) .unwrap(); } // The result of the division is D(k * x): let mut scaled_reconstructed_poly = PolyData { coeffs: fs.fft_fr(&eval_scaled_reconstructed_poly, true).unwrap(), }; // k * x -> x unscale_poly(&mut scaled_reconstructed_poly); // Finally we have D(x) which evaluates to our original data at the powers of roots of unity Ok(scaled_reconstructed_poly) } fn recover_poly_from_samples( samples: &[Option<BlstFr>], fs: &FFTSettings, ) -> Result<Self, String> { let reconstructed_poly = Self::recover_poly_coeffs_from_samples(samples, fs)?; // The evaluation polynomial for D(x) is the reconstructed data: let out = PolyData { coeffs: fs.fft_fr(&reconstructed_poly.coeffs, false).unwrap(), }; // Check all is well for (i, sample) in samples.iter().enumerate() { if !sample.is_none() && !out.get_coeff_at(i).equals(&sample.unwrap()) { return Err(String::from( "sample is zero and out coeff at i is not equals to sample", )); } } Ok(out) } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/src/fft.rs
arkworks4/src/fft.rs
use crate::kzg_proofs::FFTSettings; use crate::kzg_types::ArkFr as BlstFr; use kzg::{FFTFr, Fr as FFr}; impl FFTFr<BlstFr> for FFTSettings { fn fft_fr(&self, data: &[BlstFr], inverse: bool) -> Result<Vec<BlstFr>, String> { if data.len() > self.max_width { return Err(String::from("data length is longer than allowed max width")); } if !data.len().is_power_of_two() { return Err(String::from("data length is not power of 2")); } let stride = self.max_width / data.len(); let mut ret = vec![BlstFr::default(); data.len()]; let roots = if inverse { &self.reverse_roots_of_unity } else { &self.roots_of_unity }; fft_fr_fast(&mut ret, data, 1, roots, stride); if inverse { let inv_fr_len = BlstFr::from_u64(data.len() as u64).inverse(); ret[..data.len()] .iter_mut() .for_each(|f| *f = BlstFr::mul(f, &inv_fr_len)); } Ok(ret) } } pub fn fft_fr_fast( ret: &mut [BlstFr], data: &[BlstFr], stride: usize, roots: &[BlstFr], roots_stride: usize, ) { let half: usize = ret.len() / 2; if half > 0 { #[cfg(not(feature = "parallel"))] { fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2); fft_fr_fast( &mut ret[half..], &data[stride..], stride * 2, roots, roots_stride * 2, ); } #[cfg(feature = "parallel")] { if half > 256 { let (lo, hi) = ret.split_at_mut(half); rayon::join( || fft_fr_fast(lo, data, stride * 2, roots, roots_stride * 2), || fft_fr_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2), ); } else { fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2); fft_fr_fast( &mut ret[half..], &data[stride..], stride * 2, roots, roots_stride * 2, ); } } for i in 0..half { let y_times_root = ret[i + half].mul(&roots[i * roots_stride]); ret[i + half] = ret[i].sub(&y_times_root); ret[i] = ret[i].add(&y_times_root); } } else { ret[0] = data[0]; } } pub fn fft_fr_slow( ret: &mut [BlstFr], data: &[BlstFr], stride: usize, roots: &[BlstFr], roots_stride: usize, ) { let mut v; let mut jv; let mut r; for i in 0..data.len() { ret[i] = data[0].mul(&roots[0]); for j in 1..data.len() { jv = data[j * stride]; r = roots[((i * j) % data.len()) * roots_stride]; v = jv.mul(&r); ret[i] = ret[i].add(&v); } } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/consts.rs
arkworks4/tests/consts.rs
#[cfg(test)] mod tests { use kzg_bench::tests::consts::{ expand_roots_is_plausible, new_fft_settings_is_plausible, roots_of_unity_are_plausible, roots_of_unity_is_the_expected_size, roots_of_unity_out_of_bounds_fails, }; use rust_kzg_arkworks4::consts::SCALE2_ROOT_OF_UNITY; use rust_kzg_arkworks4::kzg_proofs::expand_root_of_unity; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; #[test] fn roots_of_unity_out_of_bounds_fails_() { roots_of_unity_out_of_bounds_fails::<ArkFr, FFTSettings>(); } #[test] fn roots_of_unity_are_plausible_() { roots_of_unity_are_plausible::<ArkFr>(&SCALE2_ROOT_OF_UNITY); } #[test] fn expand_roots_is_plausible_() { expand_roots_is_plausible::<ArkFr>(&SCALE2_ROOT_OF_UNITY, &expand_root_of_unity); } #[test] fn new_fft_settings_is_plausible_() { new_fft_settings_is_plausible::<ArkFr, FFTSettings>(); } #[test] fn roots_of_unity_is_the_expected_size_() { roots_of_unity_is_the_expected_size(&SCALE2_ROOT_OF_UNITY); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/das.rs
arkworks4/tests/das.rs
#[cfg(test)] mod tests { use kzg_bench::tests::das::{das_extension_test_known, das_extension_test_random}; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; #[test] fn das_extension_test_known_() { das_extension_test_known::<ArkFr, FFTSettings>(); } #[test] fn das_extension_test_random_() { das_extension_test_random::<ArkFr, FFTSettings>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/eip_4844.rs
arkworks4/tests/eip_4844.rs
#[cfg(test)] mod tests { use kzg::eip_4844::{ blob_to_kzg_commitment_rust, blob_to_polynomial, bytes_to_blob, compute_blob_kzg_proof_rust, compute_challenge_rust, compute_kzg_proof_rust, compute_powers, evaluate_polynomial_in_evaluation_form, verify_blob_kzg_proof_batch_rust, verify_blob_kzg_proof_rust, verify_kzg_proof_rust, }; use kzg::Fr; use kzg_bench::tests::eip_4844::{ blob_to_kzg_commitment_test, bytes_to_bls_field_test, compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test, compute_and_verify_blob_kzg_proof_test, compute_and_verify_kzg_proof_fails_with_incorrect_proof_test, compute_and_verify_kzg_proof_round_trip_test, compute_and_verify_kzg_proof_within_domain_test, compute_kzg_proof_test, compute_powers_test, test_vectors_blob_to_kzg_commitment, test_vectors_compute_blob_kzg_proof, test_vectors_compute_challenge, test_vectors_compute_kzg_proof, test_vectors_verify_blob_kzg_proof, test_vectors_verify_blob_kzg_proof_batch, test_vectors_verify_kzg_proof, verify_kzg_proof_batch_fails_with_incorrect_proof_test, verify_kzg_proof_batch_test, }; use rust_kzg_arkworks4::consts::SCALE2_ROOT_OF_UNITY; use rust_kzg_arkworks4::eip_4844::load_trusted_setup_filename_rust; use rust_kzg_arkworks4::kzg_proofs::{expand_root_of_unity, FFTSettings, KZGSettings}; use rust_kzg_arkworks4::kzg_types::{ ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2, }; use rust_kzg_arkworks4::utils::PolyData; #[test] pub fn bytes_to_bls_field_test_() { bytes_to_bls_field_test::<ArkFr>(); } #[test] pub fn compute_powers_test_() { compute_powers_test::<ArkFr>(&compute_powers); } #[test] pub fn blob_to_kzg_commitment_test_() { blob_to_kzg_commitment_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, ); } #[test] pub fn compute_kzg_proof_test_() { compute_kzg_proof_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &compute_kzg_proof_rust, &blob_to_polynomial, &evaluate_polynomial_in_evaluation_form, ); } #[test] pub fn compute_and_verify_kzg_proof_round_trip_test_() { compute_and_verify_kzg_proof_round_trip_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_kzg_proof_rust, &blob_to_polynomial, &evaluate_polynomial_in_evaluation_form, &verify_kzg_proof_rust, ); } #[test] pub fn compute_and_verify_kzg_proof_within_domain_test_() { compute_and_verify_kzg_proof_within_domain_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_kzg_proof_rust, &blob_to_polynomial, &evaluate_polynomial_in_evaluation_form, &verify_kzg_proof_rust, ); } #[test] pub fn compute_and_verify_kzg_proof_fails_with_incorrect_proof_test_() { compute_and_verify_kzg_proof_fails_with_incorrect_proof_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_kzg_proof_rust, &blob_to_polynomial, &evaluate_polynomial_in_evaluation_form, &verify_kzg_proof_rust, ); } #[test] pub fn compute_and_verify_blob_kzg_proof_test_() { compute_and_verify_blob_kzg_proof_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_blob_kzg_proof_rust, &verify_blob_kzg_proof_rust, ); } #[test] pub fn compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test_() { compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_blob_kzg_proof_rust, &verify_blob_kzg_proof_rust, ); } #[test] pub fn verify_kzg_proof_batch_test_() { verify_kzg_proof_batch_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_blob_kzg_proof_rust, &verify_blob_kzg_proof_batch_rust, ); } #[test] pub fn verify_kzg_proof_batch_fails_with_incorrect_proof_test_() { verify_kzg_proof_batch_fails_with_incorrect_proof_test::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, &compute_blob_kzg_proof_rust, &verify_blob_kzg_proof_batch_rust, ); } #[test] pub fn test_vectors_blob_to_kzg_commitment_() { test_vectors_blob_to_kzg_commitment::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &blob_to_kzg_commitment_rust, &bytes_to_blob, ); } #[test] pub fn test_vectors_compute_kzg_proof_() { test_vectors_compute_kzg_proof::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &compute_kzg_proof_rust, &bytes_to_blob, ); } #[test] pub fn test_vectors_compute_blob_kzg_proof_() { test_vectors_compute_blob_kzg_proof::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &bytes_to_blob, &compute_blob_kzg_proof_rust, ); } #[test] pub fn test_vectors_verify_kzg_proof_() { test_vectors_verify_kzg_proof::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >(&load_trusted_setup_filename_rust, &verify_kzg_proof_rust); } #[test] pub fn test_vectors_verify_blob_kzg_proof_() { test_vectors_verify_blob_kzg_proof::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &bytes_to_blob, &verify_blob_kzg_proof_rust, ); } #[test] pub fn test_vectors_verify_blob_kzg_proof_batch_() { test_vectors_verify_blob_kzg_proof_batch::< ArkFr, ArkG1, ArkG2, PolyData, FFTSettings, KZGSettings, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >( &load_trusted_setup_filename_rust, &bytes_to_blob, &verify_blob_kzg_proof_batch_rust, ); } #[test] pub fn test_vectors_compute_challenge_() { test_vectors_compute_challenge::<ArkFr, ArkG1>(&bytes_to_blob, &compute_challenge_rust); } #[test] pub fn expand_root_of_unity_too_long() { let out = expand_root_of_unity(&ArkFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 1); assert!(out.is_err()); } #[test] pub fn expand_root_of_unity_too_short() { let out = expand_root_of_unity(&ArkFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 3); assert!(out.is_err()); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/kzg_proofs.rs
arkworks4/tests/kzg_proofs.rs
#[cfg(test)] mod tests { use kzg_bench::tests::kzg_proofs::{ commit_to_nil_poly, commit_to_too_long_poly_returns_err, proof_multi, proof_single, trusted_setup_in_correct_form, }; use rust_kzg_arkworks4::eip_7594::ArkBackend; use rust_kzg_arkworks4::kzg_proofs::generate_trusted_setup; #[test] pub fn test_trusted_setup_in_correct_form() { trusted_setup_in_correct_form::<ArkBackend>(&generate_trusted_setup); } #[test] fn proof_single_() { proof_single::<ArkBackend>(&generate_trusted_setup); } #[test] fn commit_to_nil_poly_() { commit_to_nil_poly::<ArkBackend>(&generate_trusted_setup); } #[test] fn commit_to_too_long_poly_() { commit_to_too_long_poly_returns_err::<ArkBackend>(&generate_trusted_setup); } #[test] fn proof_multi_() { proof_multi::<ArkBackend>(&generate_trusted_setup); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/eip_7594.rs
arkworks4/tests/eip_7594.rs
#[cfg(test)] mod tests { use kzg::eip_4844::bytes_to_blob; use kzg_bench::tests::eip_7594::{ test_vectors_compute_cells, test_vectors_compute_cells_and_kzg_proofs, test_vectors_compute_verify_cell_kzg_proof_batch_challenge, test_vectors_recover_cells_and_kzg_proofs, test_vectors_verify_cell_kzg_proof_batch, }; use rust_kzg_arkworks4::eip_4844::load_trusted_setup_filename_rust; use rust_kzg_arkworks4::eip_7594::ArkBackend; #[test] pub fn test_vectors_compute_cells_() { test_vectors_compute_cells::<ArkBackend>(&load_trusted_setup_filename_rust, &bytes_to_blob); } #[test] pub fn test_vectors_compute_cells_and_kzg_proofs_() { test_vectors_compute_cells_and_kzg_proofs::<ArkBackend>( &load_trusted_setup_filename_rust, &bytes_to_blob, ); } #[test] pub fn test_vectors_recover_cells_and_kzg_proofs_() { test_vectors_recover_cells_and_kzg_proofs::<ArkBackend>(&load_trusted_setup_filename_rust); } #[test] pub fn test_vectors_verify_cell_kzg_proof_batch_() { test_vectors_verify_cell_kzg_proof_batch::<ArkBackend>(&load_trusted_setup_filename_rust); } #[test] pub fn test_vectors_compute_verify_cell_kzg_proof_batch_challenge_() { test_vectors_compute_verify_cell_kzg_proof_batch_challenge::<ArkBackend>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/msm.rs
arkworks4/tests/msm.rs
#[cfg(test)] mod tests { use kzg_bench::tests::msm::msm_slice::{ test_msm_slice_window_size_1, test_msm_slice_window_size_16, test_msm_slice_window_size_2, test_msm_slice_window_size_3, }; #[test] pub fn test_msm_slice_window_size_1_() { test_msm_slice_window_size_1() } #[test] fn test_msm_slice_window_size_2_() { test_msm_slice_window_size_2(); } #[test] fn test_msm_slice_window_size_3_() { test_msm_slice_window_size_3(); } #[test] fn test_msm_slice_window_size_16_() { test_msm_slice_window_size_16(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/poly.rs
arkworks4/tests/poly.rs
#[cfg(test)] mod tests { use kzg_bench::tests::poly::{ create_poly_of_length_ten, poly_div_by_zero, poly_div_fast_test, poly_div_long_test, poly_div_random, poly_eval_0_check, poly_eval_check, poly_eval_nil_check, poly_inverse_simple_0, poly_inverse_simple_1, poly_mul_direct_test, poly_mul_fft_test, poly_mul_random, poly_test_div, }; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; use rust_kzg_arkworks4::utils::PolyData; #[test] fn create_poly_of_length_ten_() { create_poly_of_length_ten::<ArkFr, PolyData>(); } #[test] fn poly_eval_check_() { poly_eval_check::<ArkFr, PolyData>(); } #[test] fn poly_eval_0_check_() { poly_eval_0_check::<ArkFr, PolyData>(); } #[test] fn poly_eval_nil_check_() { poly_eval_nil_check::<ArkFr, PolyData>(); } #[test] fn poly_inverse_simple_0_() { poly_inverse_simple_0::<ArkFr, PolyData>(); } #[test] fn poly_inverse_simple_1_() { poly_inverse_simple_1::<ArkFr, PolyData>(); } #[test] fn poly_test_div_() { poly_test_div::<ArkFr, PolyData>(); } #[test] #[should_panic] fn poly_div_by_zero_() { poly_div_by_zero::<ArkFr, PolyData>(); } #[test] fn poly_mul_direct_test_() { poly_mul_direct_test::<ArkFr, PolyData>(); } #[test] fn poly_mul_fft_test_() { poly_mul_fft_test::<ArkFr, PolyData, FFTSettings>(); } #[test] fn poly_mul_random_() { poly_mul_random::<ArkFr, PolyData, FFTSettings>(); } #[test] fn poly_div_random_() { poly_div_random::<ArkFr, PolyData>(); } #[test] fn poly_div_long_test_() { poly_div_long_test::<ArkFr, PolyData>() } #[test] fn poly_div_fast_test_() { poly_div_fast_test::<ArkFr, PolyData>() } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/zero_poly.rs
arkworks4/tests/zero_poly.rs
#[cfg(test)] mod tests { use kzg_bench::tests::zero_poly::{ check_test_data, reduce_partials_random, test_reduce_partials, zero_poly_252, zero_poly_all_but_one, zero_poly_known, zero_poly_random, }; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; use rust_kzg_arkworks4::utils::PolyData; #[test] fn test_reduce_partials_() { test_reduce_partials::<ArkFr, FFTSettings, PolyData>(); } #[test] fn reduce_partials_random_() { reduce_partials_random::<ArkFr, FFTSettings, PolyData>(); } #[test] fn check_test_data_() { check_test_data::<ArkFr, FFTSettings, PolyData>(); } #[test] fn zero_poly_known_() { zero_poly_known::<ArkFr, FFTSettings, PolyData>(); } #[test] fn zero_poly_random_() { zero_poly_random::<ArkFr, FFTSettings, PolyData>(); } #[test] fn zero_poly_all_but_one_() { zero_poly_all_but_one::<ArkFr, FFTSettings, PolyData>(); } #[test] fn zero_poly_252_() { zero_poly_252::<ArkFr, FFTSettings, PolyData>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/bls12_381.rs
arkworks4/tests/bls12_381.rs
#[cfg(test)] mod tests { use kzg::common_utils::log_2_byte; use kzg_bench::tests::bls12_381::*; use rust_kzg_arkworks4::fft_g1::g1_linear_combination; use rust_kzg_arkworks4::kzg_proofs::pairings_verify; use rust_kzg_arkworks4::kzg_types::{ ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2, }; #[test] pub fn log_2_byte_works_() { log_2_byte_works(&log_2_byte); } #[test] pub fn fr_is_zero_works_() { fr_is_zero_works::<ArkFr>(); } #[test] pub fn fr_is_one_works_() { fr_is_one_works::<ArkFr>(); } #[test] pub fn fr_from_uint64_works_() { fr_from_uint64_works::<ArkFr>(); } #[test] pub fn fr_equal_works_() { fr_equal_works::<ArkFr>(); } #[test] pub fn fr_negate_works_() { fr_negate_works::<ArkFr>(); } #[test] pub fn fr_pow_works_() { fr_pow_works::<ArkFr>(); } #[test] pub fn fr_div_works_() { fr_div_works::<ArkFr>(); } #[test] #[should_panic] pub fn fr_div_by_zero_() { fr_div_by_zero::<ArkFr>(); } #[test] pub fn fr_uint64s_roundtrip_() { fr_uint64s_roundtrip::<ArkFr>(); } #[test] pub fn p1_mul_works_() { p1_mul_works::<ArkFr, ArkG1>(); } #[test] pub fn p1_sub_works_() { p1_sub_works::<ArkG1>(); } #[test] pub fn p2_add_or_dbl_works_() { p2_add_or_dbl_works::<ArkG2>(); } #[test] pub fn p2_mul_works_() { p2_mul_works::<ArkFr, ArkG2>(); } #[test] pub fn p2_sub_works_() { p2_sub_works::<ArkG2>(); } #[test] pub fn g1_identity_is_infinity_() { g1_identity_is_infinity::<ArkG1>(); } #[test] pub fn g1_identity_is_identity_() { g1_identity_is_identity::<ArkG1>(); } #[test] pub fn g1_make_linear_combination_() { g1_make_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>( &g1_linear_combination, ); } #[test] pub fn g1_random_linear_combination_() { g1_random_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>( &g1_linear_combination, ); } #[test] pub fn g1_linear_combination_infinity_points_() { g1_linear_combination_infinity_points::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>( &g1_linear_combination, ); } #[test] fn g1_small_linear_combination_() { g1_small_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>( &g1_linear_combination, ) } #[test] pub fn pairings_work_() { pairings_work::<ArkFr, ArkG1, ArkG2>(&pairings_verify); } #[test] pub fn fr_is_null_works_() { fr_is_null_works::<ArkFr>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/fk20_proofs.rs
arkworks4/tests/fk20_proofs.rs
#[cfg(test)] mod tests { use kzg_bench::tests::fk20_proofs::*; use rust_kzg_arkworks4::eip_7594::ArkBackend; use rust_kzg_arkworks4::fk20_proofs::{KzgFK20MultiSettings, KzgFK20SingleSettings}; use rust_kzg_arkworks4::kzg_proofs::generate_trusted_setup; #[test] fn test_fk_single() { fk_single::<ArkBackend, KzgFK20SingleSettings>(&generate_trusted_setup); } #[test] fn test_fk_single_strided() { fk_single_strided::<ArkBackend, KzgFK20SingleSettings>(&generate_trusted_setup); } #[test] fn test_fk_multi_settings() { fk_multi_settings::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup); } #[test] fn test_fk_multi_chunk_len_1_512() { fk_multi_chunk_len_1_512::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup); } #[test] fn test_fk_multi_chunk_len_16_512() { fk_multi_chunk_len_16_512::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup); } #[test] fn test_fk_multi_chunk_len_16_16() { fk_multi_chunk_len_16_16::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/bucket_msm.rs
arkworks4/tests/bucket_msm.rs
#[cfg(test)] mod tests { use kzg_bench::tests::msm::bucket_msm::{ test_process_point_and_slices_deal_three_points, test_process_point_and_slices_glv_deal_two_points, }; use rust_kzg_arkworks4::kzg_types::{ArkFp, ArkG1, ArkG1Affine, ArkG1ProjAddAffine}; #[test] pub fn test_process_point_and_slices_deal_three_points_() { test_process_point_and_slices_deal_three_points::< ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >(); } #[test] fn test_process_point_and_slices_glv_deal_two_points_() { test_process_point_and_slices_glv_deal_two_points::< ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, >(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/fft_g1.rs
arkworks4/tests/fft_g1.rs
#[cfg(test)] mod tests { use kzg_bench::tests::fft_g1::{compare_ft_fft, roundtrip_fft, stride_fft}; use rust_kzg_arkworks4::fft_g1::{fft_g1_fast, fft_g1_slow, make_data}; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::{ArkFr, ArkG1}; #[test] fn roundtrip_fft_() { roundtrip_fft::<ArkFr, ArkG1, FFTSettings>(&make_data); } #[test] fn stride_fft_() { stride_fft::<ArkFr, ArkG1, FFTSettings>(&make_data); } #[test] fn compare_sft_fft_() { compare_ft_fft::<ArkFr, ArkG1, FFTSettings>(&fft_g1_slow, &fft_g1_fast, &make_data); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/fft_fr.rs
arkworks4/tests/fft_fr.rs
mod batch_adder; #[cfg(test)] mod tests { use kzg_bench::tests::fft_fr::{compare_sft_fft, inverse_fft, roundtrip_fft, stride_fft}; use rust_kzg_arkworks4::fft::{fft_fr_fast, fft_fr_slow}; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; #[test] fn compare_sft_fft_() { compare_sft_fft::<ArkFr, FFTSettings>(&fft_fr_slow, &fft_fr_fast); } #[test] fn roundtrip_fft_() { roundtrip_fft::<ArkFr, FFTSettings>(); } #[test] fn inverse_fft_() { inverse_fft::<ArkFr, FFTSettings>(); } #[test] fn stride_fft_() { stride_fft::<ArkFr, FFTSettings>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/batch_adder.rs
arkworks4/tests/batch_adder.rs
#[cfg(test)] mod tests { use kzg_bench::tests::msm::batch_adder::{ test_batch_add, test_batch_add_indexed, test_batch_add_indexed_single_bucket, test_batch_add_step_n, test_phase_one_p_add_p, test_phase_one_p_add_q, test_phase_one_p_add_q_twice, test_phase_one_zero_or_neg, test_phase_two_p_add_neg, test_phase_two_p_add_p, test_phase_two_p_add_q, test_phase_two_zero_add_p, }; use rust_kzg_arkworks4::kzg_types::{ArkFp, ArkG1, ArkG1Affine}; #[test] fn test_phase_one_zero_or_neg_() { test_phase_one_zero_or_neg::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_one_p_add_p_() { test_phase_one_p_add_p::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_one_p_add_q_() { test_phase_one_p_add_q::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_one_p_add_q_twice_() { test_phase_one_p_add_q_twice::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_two_zero_add_p_() { test_phase_two_zero_add_p::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_two_p_add_neg_() { test_phase_two_p_add_neg::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_phase_two_p_add_q_() { test_phase_two_p_add_q::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] pub fn test_phase_two_p_add_p_() { test_phase_two_p_add_p::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_batch_add_() { test_batch_add::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_batch_add_step_n_() { test_batch_add_step_n::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_batch_add_indexed_() { test_batch_add_indexed::<ArkG1, ArkFp, ArkG1Affine>(); } #[test] fn test_batch_add_indexed_single_bucket_() { test_batch_add_indexed_single_bucket::<ArkG1, ArkFp, ArkG1Affine>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/tests/recover.rs
arkworks4/tests/recover.rs
#[cfg(test)] mod recover_tests { use kzg_bench::tests::recover::*; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr as Fr; use rust_kzg_arkworks4::utils::PolyData; #[test] fn recover_simple_() { recover_simple::<Fr, FFTSettings, PolyData, PolyData>(); } //Could be not working because of zero poly. #[test] fn recover_random_() { recover_random::<Fr, FFTSettings, PolyData, PolyData>(); } #[test] fn more_than_half_missing_() { more_than_half_missing::<Fr, FFTSettings, PolyData, PolyData>(); } }
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false
grandinetech/rust-kzg
https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks4/benches/das.rs
arkworks4/benches/das.rs
use criterion::{criterion_group, criterion_main, Criterion}; use kzg_bench::benches::das::bench_das_extension; use rust_kzg_arkworks4::kzg_proofs::FFTSettings; use rust_kzg_arkworks4::kzg_types::ArkFr; fn bench_das_extension_(c: &mut Criterion) { bench_das_extension::<ArkFr, FFTSettings>(c); } criterion_group! { name = benches; config = Criterion::default().sample_size(10); targets = bench_das_extension_ } criterion_main!(benches);
rust
Apache-2.0
d47acbdf587753f466a5e6842395e03930ae1f96
2026-01-04T20:22:26.256259Z
false