after
stringlengths
51
30.2k
before
stringlengths
30
10.1k
index
int64
0
1.54k
fn main() -> i32 { unsafe { puts(getenv(b"HOME\0" as *const u8 as *const i8)); } return 0; }
int main() { puts(getenv("HOME")); return 0; }
0
pub extern "C" fn gcd(mut m: i32, mut n: i32) -> i32 { let mut t: i32 = 0; while m != 0 { t = m; m = n % m; n = t; } return n; }
int gcd(int m, int n) { int t; while (m) { t = m; m = n % m; n = t; } return n; }
1
pub extern "C" fn reset() { let mut i: i32 = 0; unsafe { msg = 0 as *const i8; pos = 0; pool_ptr = pos; } i = 0; unsafe { while i < 8 { pool[i as usize].op = OP_NONE as i32; pool[i as usize].right = 0 as expr; pool[i as usize].left = pool[i as usize].right; i += 1; i; } } i = 0; unsafe { while i < 4 { digits[i as usize].used = 0; i += 1; i; } } }
void reset() { int i; msg = 0; pool_ptr = pos = 0; for (i = 0; i < POOL_SIZE; i++) { pool[i].op = OP_NONE; pool[i].left = pool[i].right = 0; } for (i = 0; i < N_DIGITS; i++) digits[i].used = 0; }
2
pub extern "C" fn get_input() { let mut i: i32 = 0; unsafe { loop { reset(); print!("\nAvailable digits are:"); i = 0; while i < 4 { print!(" {}", digits[i as usize].val); i += 1; i; } printf (b". Type an expression and I'll check it for you, or make new numbers.\nYour choice? [Expr/n/q] \0" as * const u8 as * const i8,); i = 0; while i < 64 { str[i as usize] = '\n' as i8; i += 1; i; } fgets(str.as_mut_ptr(), 64, stdin); if *str.as_mut_ptr() as i32 == '\0' as i32 { continue; } if str[(64 - 1i32) as usize] as i32 != '\n' as i32 { bail(b"string too long\0" as *const u8 as *const i8); } i = 0; while i < 64 { if str[i as usize] as i32 == '\n' as i32 { str[i as usize] = '\0' as i8; } i += 1; i; } if str[0 as usize] as i32 == 'q' as i32 { print!("Bye\n"); exit(0); } if !(str[0 as usize] as i32 == 'n' as i32) { break; } gen_digits(); } } }
void get_input() { int i; reinput: reset(); printf("\nAvailable digits are:"); for (i = 0; i < N_DIGITS; i++) printf(" %d", digits[i].val); printf(". Type an expression and I'll check it for you, or make new numbers.\n" "Your choice? [Expr/n/q] "); while (1) { for (i = 0; i < MAX_INPUT; i++) str[i] = '\n'; fgets(str, MAX_INPUT, stdin); if (*str == '\0') goto reinput; if (str[MAX_INPUT - 1] != '\n') bail("string too long"); for (i = 0; i < MAX_INPUT; i++) if (str[i] == '\n') str[i] = '\0'; if (str[0] == 'q') { printf("Bye\n"); exit(0); } if (str[0] == 'n') { gen_digits(); goto reinput; } return; } }
3
pub extern "C" fn parse() -> expr { let mut i: i32 = 0; let mut ret: expr = get_expr(); if next_tok() != '\0' as i32 { bail(b"Trailing garbage\0" as *const u8 as *const i8); } i = 0; unsafe { while i < 4 { if digits[i as usize].used == 0 { bail(b"Not all digits are used\0" as *const u8 as *const i8); } i += 1; i; } } return ret; }
expr parse() { int i; expr ret = get_expr(); if (next_tok() != '\0') bail("Trailing garbage"); for (i = 0; i < N_DIGITS; i++) if (!digits[i].used) bail("Not all digits are used"); return ret; }
4
pub extern "C" fn gen_digits() { let mut i: i32 = 0; i = 0; unsafe { while i < 4 { digits[i as usize].val = 1 + rand() % 9; i += 1; i; } } }
void gen_digits() { int i; for (i = 0; i < N_DIGITS; i++) digits[i].val = 1 + rand() % 9; }
5
pub extern "C" fn new_expr() -> expr { unsafe { if pool_ptr < 8 { let fresh0 = pool_ptr; pool_ptr = pool_ptr + 1; return pool.as_mut_ptr().offset(fresh0 as isize); } } return 0 as expr; }
expr new_expr() { if (pool_ptr < POOL_SIZE) return pool + pool_ptr++; return 0; }
6
pub extern "C" fn get_digit() -> expr { let mut i: i32 = 0; let mut c: i32 = next_tok(); let mut ret: expr = 0 as *mut expr_t; unsafe { if c >= '0' as i32 && c <= '9' as i32 { take(); ret = new_expr(); (*ret).op = OP_NUM as i32; (*ret).val = c - '0' as i32; i = 0; while i < 4 { if digits[i as usize].val == (*ret).val && digits[i as usize].used == 0 { digits[i as usize].used = 1; return ret; } i += 1; i; } bail(b"Invalid digit\0" as *const u8 as *const i8); } } return 0 as expr; }
expr get_digit() { int i, c = next_tok(); expr ret; if (c >= '0' && c <= '9') { take(); ret = new_expr(); ret->op = OP_NUM; ret->val = c - '0'; for (i = 0; i < N_DIGITS; i++) if (digits[i].val == ret->val && !digits[i].used) { digits[i].used = 1; return ret; } bail("Invalid digit"); } return 0; }
7
pub extern "C" fn take() -> i32 { unsafe { if str[pos as usize] as i32 != '\0' as i32 { pos += 1; return pos; } } return 0; }
int take() { if (str[pos] != '\0') return ++pos; return 0; }
8
pub extern "C" fn next_tok() -> i32 { unsafe { while *(*__ctype_b_loc()).offset(str[pos as usize] as i32 as isize) as i32 & _ISspace as i32 != 0 { pos += 1; pos; } return str[pos as usize] as i32; } }
int next_tok() { while (isspace(str[pos])) pos++; return str[pos]; }
9
fn main() -> i32 { let mut f: frac_t = frac_t { denom: 0, num: 0 }; unsafe { srand(rust_time(None) as u32); } gen_digits(); unsafe { loop { get_input(); _setjmp(ctx.as_mut_ptr()); if !msg.is_null() { print!( "{0:} at {2:.2$}\n", build_str_from_raw_ptr(msg as *mut u8), pos, build_str_from_raw_ptr(str.as_mut_ptr() as *mut u8) ); } else { eval_tree(parse(), &mut f); if f.denom == 0 { bail(b"Divide by zero\0" as *const u8 as *const i8); } if f.denom == 1 && f.num == 24 { print!("You got 24. Very good.\n"); } else { if f.denom == 1 { print!("Eval to: {}, ", f.num); } else { print!("Eval to: {}/{}, ", f.num, f.denom); } print!("no good. Try again.\n"); } } } } }
int main() { frac_t f; srand(time(0)); gen_digits(); while(1) { get_input(); setjmp(ctx); /* if parse error, jump back here with err msg set */ if (msg) { /* after error jump; announce, reset, redo */ printf("%s at '%.*s'\n", msg, pos, str); continue; } eval_tree(parse(), &f); if (f.denom == 0) bail("Divide by zero"); if (f.denom == 1 && f.num == 24) printf("You got 24. Very good.\n"); else { if (f.denom == 1) printf("Eval to: %d, ", f.num); else printf("Eval to: %d/%d, ", f.num, f.denom); printf("no good. Try again.\n"); } } return 0; }
10
pub extern "C" fn get_term() -> expr { let mut c: i32 = 0; let mut l: expr = 0 as *mut expr_t; let mut r: expr = 0 as *mut expr_t; let mut ret: expr = 0 as *mut expr_t; ret = get_fact(); loop { c = next_tok(); if !(c == '*' as i32 || c == '/' as i32) { break; } if take() == 0 { bail(b"Unexpected end of input\0" as *const u8 as *const i8); } r = get_fact(); l = ret; ret = new_expr(); (*ret).op = if c == '*' as i32 { OP_MUL as i32 } else { OP_DIV as i32 }; (*ret).left = l; (*ret).right = r; } return ret; }
expr get_term() { int c; expr l, r, ret; ret = get_fact(); while((c = next_tok()) == '*' || c == '/') { if (!take()) bail("Unexpected end of input"); r = get_fact(); l = ret; ret = new_expr(); ret->op = (c == '*') ? OP_MUL : OP_DIV; ret->left = l; ret->right = r; } return ret; }
11
pub extern "C" fn get_fact() -> expr { let mut c: i32 = 0; let mut l: expr = get_digit(); if !l.is_null() { return l; } c = next_tok(); if c == '(' as i32 { take(); l = get_expr(); if next_tok() != ')' as i32 { bail(b"Unbalanced parens\0" as *const u8 as *const i8); } take(); return l; } return 0 as expr; }
expr get_fact() { int c; expr l = get_digit(); if (l) return l; if ((c = next_tok()) == '(') { take(); l = get_expr(); if (next_tok() != ')') bail("Unbalanced parens"); take(); return l; } return 0; }
12
pub extern "C" fn bail(mut s: *const i8) { unsafe { msg = s; longjmp(ctx.as_mut_ptr(), 1); } }
void bail(const char *s) { msg = s; longjmp(ctx, 1); }
13
pub extern "C" fn eval_tree(mut e: expr, mut res: frac) { let mut l: frac_t = frac_t { denom: 0, num: 0 }; let mut r: frac_t = frac_t { denom: 0, num: 0 }; let mut t: i32 = 0; if (*e).op == OP_NUM as i32 { (*res).num = (*e).val; (*res).denom = 1; return; } eval_tree((*e).left, &mut l); eval_tree((*e).right, &mut r); match (*e).op { 2 => { (*res).num = l.num * r.denom + l.denom * r.num; (*res).denom = l.denom * r.denom; } 3 => { (*res).num = l.num * r.denom - l.denom * r.num; (*res).denom = l.denom * r.denom; } 4 => { (*res).num = l.num * r.num; (*res).denom = l.denom * r.denom; } 5 => { (*res).num = l.num * r.denom; (*res).denom = l.denom * r.num; } _ => {} } t = gcd((*res).denom, (*res).num); if t != 0 { (*res).denom /= t; (*res).num /= t; } }
void eval_tree(expr e, frac res) { frac_t l, r; int t; if (e->op == OP_NUM) { res->num = e->val; res->denom = 1; return; } eval_tree(e->left, &l); eval_tree(e->right, &r); switch(e->op) { case OP_ADD: res->num = l.num * r.denom + l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_SUB: res->num = l.num * r.denom - l.denom * r.num; res->denom = l.denom * r.denom; break; case OP_MUL: res->num = l.num * r.num; res->denom = l.denom * r.denom; break; case OP_DIV: res->num = l.num * r.denom; res->denom = l.denom * r.num; break; } if ((t = gcd(res->denom, res->num))) { res->denom /= t; res->num /= t; } }
14
pub extern "C" fn get_expr() -> expr { let mut c: i32 = 0; let mut l: expr = 0 as *mut expr_t; let mut r: expr = 0 as *mut expr_t; let mut ret: expr = 0 as *mut expr_t; ret = get_term(); if ret.is_null() { bail(b"Expected term\0" as *const u8 as *const i8); } loop { c = next_tok(); if !(c == '+' as i32 || c == '-' as i32) { break; } if take() == 0 { bail(b"Unexpected end of input\0" as *const u8 as *const i8); } r = get_term(); if r.is_null() { bail(b"Expected term\0" as *const u8 as *const i8); } l = ret; ret = new_expr(); (*ret).op = if c == '+' as i32 { OP_ADD as i32 } else { OP_SUB as i32 }; (*ret).left = l; (*ret).right = r; } return ret; }
expr get_expr() { int c; expr l, r, ret; if (!(ret = get_term())) bail("Expected term"); while ((c = next_tok()) == '+' || c == '-') { if (!take()) bail("Unexpected end of input"); if (!(r = get_term())) bail("Expected term"); l = ret; ret = new_expr(); ret->op = (c == '+') ? OP_ADD : OP_SUB; ret->left = l; ret->right = r; } return ret; }
15
fn main() -> i32 { let mut i: i32 = 0; let mut a: [u64; 3] = [0; 3]; unsafe { let mut p: [threadfunc; 3] = [ Some(t_enjoy as unsafe extern "C" fn(*mut libc::c_void) -> *mut libc::c_void), Some(t_rosetta as unsafe extern "C" fn(*mut libc::c_void) -> *mut libc::c_void), Some(t_code as unsafe extern "C" fn(*mut libc::c_void) -> *mut libc::c_void), ]; i = 0; while i < 3 { pthread_create( &mut *a.as_mut_ptr().offset(i as isize), 0 as *const pthread_attr_t, p[i as usize], 0 as *mut libc::c_void, ); i += 1; i; } sleep(1); bang = 1; pthread_cond_broadcast(&mut cond); } i = 0; unsafe { while i < 3 { pthread_join(a[i as usize], 0 as *mut *mut libc::c_void); i += 1; i; } } return 0; }
int main() { int i; pthread_t a[3]; threadfunc p[3] = {t_enjoy, t_rosetta, t_code}; for(i=0;i<3;i++) { pthread_create(&a[i], NULL, p[i], NULL); } sleep(1); bang = 1; pthread_cond_broadcast(&cond); for(i=0;i<3;i++) { pthread_join(a[i], NULL); } }
16
fn main() -> i32 { unsafe { let mut str: [i8; 35] = *::core::mem::transmute::<&[u8; 35], &mut [i8; 35]>( b"This is a top secret text message!\0", ); print!( "Original: {}\n", build_str_from_raw_ptr(str.as_mut_ptr() as *mut u8) ); rot(13, str.as_mut_ptr()); print!( "Encrypted: {}\n", build_str_from_raw_ptr(str.as_mut_ptr() as *mut u8) ); rot(13, str.as_mut_ptr()); print!( "Decrypted: {}\n", build_str_from_raw_ptr(str.as_mut_ptr() as *mut u8) ); } return 0; }
int main() { char str[] = "This is a top secret text message!"; printf("Original: %s\n", str); caesar(str); printf("Encrypted: %s\n", str); decaesar(str); printf("Decrypted: %s\n", str); return 0; }
17
pub extern "C" fn rot(mut c: i32, mut str: *mut i8) { unsafe { let mut l: i32 = strlen(str) as i32; let mut alpha: [*const i8; 2] = [ b"abcdefghijklmnopqrstuvwxyz\0" as *const u8 as *const i8, b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\0" as *const u8 as *const i8, ]; let mut i: i32 = 0; i = 0; while i < l { if !(*(*__ctype_b_loc()).offset(*str.offset(i as isize) as i32 as isize) as i32 & _ISalpha as i32 == 0) { if *(*__ctype_b_loc()).offset(*str.offset(i as isize) as i32 as isize) as i32 & _ISupper as i32 != 0 { *str.offset(i as isize) = *(alpha[1 as usize]).offset( ((tolower(*str.offset(i as isize) as i32) - 'a' as i32 + c) % 26i32) as isize, ); } else { *str.offset(i as isize) = *(alpha[0 as usize]).offset( ((tolower(*str.offset(i as isize) as i32) - 'a' as i32 + c) % 26i32) as isize, ); } } i += 1; i; } } }
void rot(int c, char *str) { int l = strlen(str); const char *alpha[2] = { "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"}; int i; for (i = 0; i < l; i++) { if (!isalpha(str[i])) continue; if (isupper(str[i])) str[i] = alpha[1][((int)(tolower(str[i]) - 'a') + c) % 26]; else str[i] = alpha[0][((int)(tolower(str[i]) - 'a') + c) % 26]; } }
18
pub extern "C" fn chao(mut in_0: *const i8, mut out: *mut i8, mut mode: u32, mut show_steps: i32) { unsafe { let mut i: i32 = 0; let mut j: i32 = 0; let mut index: i32 = 0; let mut store: i8 = 0; let mut len: u64 = strlen(in_0); let mut left: [i8; 27] = [0; 27]; let mut right: [i8; 27] = [0; 27]; let mut temp: [i8; 27] = [0; 27]; strcpy(left.as_mut_ptr(), l_alphabet); strcpy(right.as_mut_ptr(), r_alphabet); temp[26 as usize] = '\0' as i8; i = 0; while (i as u64) < len { if show_steps != 0 { print!( "{} {}\n", build_str_from_raw_ptr(left.as_mut_ptr() as *mut u8), build_str_from_raw_ptr(right.as_mut_ptr() as *mut u8) ); } if mode as u32 == ENCRYPT as u32 { index = (strchr(right.as_mut_ptr(), *in_0.offset(i as isize) as i32)) .offset_from(right.as_mut_ptr()) as i32; *out.offset(i as isize) = left[index as usize]; } else { index = (strchr(left.as_mut_ptr(), *in_0.offset(i as isize) as i32)) .offset_from(left.as_mut_ptr()) as i32; *out.offset(i as isize) = right[index as usize]; } if i as u64 == len.wrapping_sub(1) { break; } j = index; while j < 26 { temp[(j - index) as usize] = left[j as usize]; j += 1; j; } j = 0; while j < index { temp[(26 - index + j) as usize] = left[j as usize]; j += 1; j; } store = temp[1 as usize]; j = 2; while j < 14 { temp[(j - 1i32) as usize] = temp[j as usize]; j += 1; j; } temp[13 as usize] = store; strcpy(left.as_mut_ptr(), temp.as_mut_ptr()); j = index; while j < 26 { temp[(j - index) as usize] = right[j as usize]; j += 1; j; } j = 0; while j < index { temp[(26 - index + j) as usize] = right[j as usize]; j += 1; j; } store = temp[0 as usize]; j = 1; while j < 26 { temp[(j - 1i32) as usize] = temp[j as usize]; j += 1; j; } temp[25 as usize] = store; store = temp[2 as usize]; j = 3; while j < 14 { temp[(j - 1i32) as usize] = temp[j as usize]; j += 1; j; } temp[13 as usize] = store; strcpy(right.as_mut_ptr(), temp.as_mut_ptr()); i += 1; i; } } }
void chao(const char *in, char *out, cmode mode, bool show_steps) { int i, j, index; char store; size_t len = strlen(in); char left[27], right[27], temp[27]; strcpy(left, l_alphabet); strcpy(right, r_alphabet); temp[26] = '\0'; for (i = 0; i < len; ++i ) { if (show_steps) printf("%s %s\n", left, right); if (mode == ENCRYPT) { index = strchr(right, in[i]) - right; out[i] = left[index]; } else { index = strchr(left, in[i]) - left; out[i] = right[index]; } if (i == len - 1) break; /* permute left */ for (j = index; j < 26; ++j) temp[j - index] = left[j]; for (j = 0; j < index; ++j) temp[26 - index + j] = left[j]; store = temp[1]; for (j = 2; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; strcpy(left, temp); /* permute right */ for (j = index; j < 26; ++j) temp[j - index] = right[j]; for (j = 0; j < index; ++j) temp[26 - index + j] = right[j]; store = temp[0]; for (j = 1; j < 26; ++j) temp[j - 1] = temp[j]; temp[25] = store; store = temp[2]; for (j = 3; j < 14; ++j) temp[j - 1] = temp[j]; temp[13] = store; strcpy(right, temp); } }
19
fn main() -> i32 { unsafe { let mut plain_text: *const i8 = b"WELLDONEISBETTERTHANWELLSAID\0" as *const u8 as *const i8; let mut cipher_text: *mut i8 = malloc((strlen(plain_text)).wrapping_add(1)) as *mut i8; let mut plain_text2: *mut i8 = malloc((strlen(plain_text)).wrapping_add(1)) as *mut i8; print!( "The original plaintext is : {}\n", build_str_from_raw_ptr(plain_text as *mut u8) ); print!("\nThe left and right alphabets after each permutation during encryption are :\n\n"); chao(plain_text, cipher_text, ENCRYPT, 1); print!( "\nThe ciphertext is : {}\n", build_str_from_raw_ptr(cipher_text as *mut u8) ); chao(cipher_text, plain_text2, DECRYPT, 0); print!( "\nThe recovered plaintext is : {}\n", build_str_from_raw_ptr(plain_text2 as *mut u8) ); free(cipher_text as *mut libc::c_void); free(plain_text2 as *mut libc::c_void); return 0; } }
int main() { const char *plain_text = "WELLDONEISBETTERTHANWELLSAID"; char *cipher_text = malloc(strlen(plain_text) + 1); char *plain_text2 = malloc(strlen(plain_text) + 1); printf("The original plaintext is : %s\n", plain_text); printf("\nThe left and right alphabets after each permutation" " during encryption are :\n\n"); chao(plain_text, cipher_text, ENCRYPT, TRUE); printf("\nThe ciphertext is : %s\n", cipher_text); chao(cipher_text, plain_text2, DECRYPT, FALSE); printf("\nThe recovered plaintext is : %s\n", plain_text2); free(cipher_text); free(plain_text2); return 0; }
20
fn main() -> i32 { let mut a: i32 = 0; let mut b: i32 = 0; unsafe { scanf( b"%d %d\0" as *const u8 as *const i8, &mut a as *mut i32, &mut b as *mut i32, ); } if a < b { print!("{} is less than {}\n", a, b); } if a == b { print!("{} is equal to {}\n", a, b); } if a > b { print!("{} is greater than {}\n", a, b); } return 0; }
int main() { int a, b; scanf("%d %d", &a, &b); if (a < b) printf("%d is less than %d\n", a, b); if (a == b) printf("%d is equal to %d\n", a, b); if (a > b) printf("%d is greater than %d\n", a, b); return 0; }
21
fn main() -> i32 { unsafe { oldColor = 1; newColor = (if oldColor as i32 != 0 { 0 } else { 1 }) as u8; readPortableBitMap(stdin); floodFill(height / 2, width / 2); writePortableBitMap(stdout); } return 0; }
int main(void) { oldColor = 1; newColor = oldColor ? 0 : 1; readPortableBitMap(stdin); floodFill(height/2,width/2); writePortableBitMap(stdout); return EXIT_SUCCESS; }
22
pub extern "C" fn skipCommentLines(mut file: *mut FILE) { unsafe { let mut c: i32 = 0; let mut comment: i32 = '#' as i32; loop { c = fgetc(file); if !(c == comment) { break; } skipLine(file); } ungetc(c, file); } }
void skipCommentLines(FILE* file) { int c; int comment = '#'; while ((c = fgetc(file)) == comment) skipLine(file); ungetc(c,file); }
23
pub extern "C" fn floodFill(mut i: i32, mut j: i32) { unsafe { if 0 <= i && i < height && 0 <= j && j < width && bitmap[i as usize][j as usize] as i32 == oldColor as i32 { bitmap[i as usize][j as usize] = newColor; floodFill(i - 1, j); floodFill(i + 1, j); floodFill(i, j - 1); floodFill(i, j + 1); } } }
void floodFill(int i, int j) { if ( 0 <= i && i < height && 0 <= j && j < width && bitmap[i][j] == oldColor ) { bitmap[i][j] = newColor; floodFill(i-1,j); floodFill(i+1,j); floodFill(i,j-1); floodFill(i,j+1); } }
24
pub extern "C" fn skipLine(mut file: *mut FILE) { unsafe { while ferror(file) == 0 && feof(file) == 0 && fgetc(file) != '\n' as i32 {} } }
void skipLine(FILE* file) { while(!ferror(file) && !feof(file) && fgetc(file) != '\n') ; }
25
pub extern "C" fn writePortableBitMap(mut file: *mut FILE) { unsafe { let mut i: i32 = 0; let mut j: i32 = 0; fprintf(file, b"P1\n\0" as *const u8 as *const i8); fprintf(file, b"%d %d\n\0" as *const u8 as *const i8, width, height); i = 0; while i < height { j = 0; while j < width { fprintf( file, b"%1d\0" as *const u8 as *const i8, bitmap[i as usize][j as usize] as i32, ); j += 1; j; } fprintf(file, b"\n\0" as *const u8 as *const i8); i += 1; i; } } }
void writePortableBitMap(FILE* file) { int i,j; fprintf(file,"P1\n"); fprintf(file,"%d %d\n", width, height); for ( i = 0; i < height; i++ ) { for ( j = 0; j < width; j++ ) fprintf(file,"%1d", bitmap[i][j]); fprintf(file,"\n"); } }
26
pub extern "C" fn iter_string(mut str: *const i8, mut d: i32) { unsafe { let mut len: i64 = 0; while *str as i32 != '\0' as i32 { let fresh0 = str; str = str.offset(1); match *fresh0 as i32 { 88 => { if d != 0 { iter_string(b"XHXVX\0" as *const u8 as *const i8, d - 1); } else { clen += 1; clen; h_rgb(x / scale, y / scale); x += dx; y -= dy; } } 86 => { len = (1u64 << d) as i64; loop { let fresh1 = len; len = len - 1; if !(fresh1 != 0) { break; } clen += 1; clen; h_rgb(x / scale, y / scale); y += dy; } } 72 => { len = (1u64 << d) as i64; loop { let fresh2 = len; len = len - 1; if !(fresh2 != 0) { break; } clen += 1; clen; h_rgb(x / scale, y / scale); x -= dx; } } _ => {} } } } }
void iter_string(const char * str, int d) { long long len; while (*str != '\0') { switch(*(str++)) { case 'X': if (d) iter_string("XHXVX", d - 1); else{ clen ++; h_rgb(x/scale, y/scale); x += dx; y -= dy; } continue; case 'V': len = 1LLU << d; while (len--) { clen ++; h_rgb(x/scale, y/scale); y += dy; } continue; case 'H': len = 1LLU << d; while(len --) { clen ++; h_rgb(x/scale, y/scale); x -= dx; } continue; } } }
27
pub extern "C" fn sierp(mut leng: i64, mut depth: i32) { unsafe { let mut i: i64 = 0; let mut h: i64 = leng + 20; let mut w: i64 = leng + 20; let mut buf: *mut rgb = malloc( (::core::mem::size_of::<rgb>() as u64) .wrapping_mul(w as u64) .wrapping_mul(h as u64), ) as *mut rgb; pix = malloc((::core::mem::size_of::<*mut rgb>() as u64).wrapping_mul(h as u64)) as *mut *mut rgb; i = 0; while i < h { let ref mut fresh3 = *pix.offset(i as isize); *fresh3 = buf.offset((w * i) as isize); i += 1; i; } memset( buf as *mut libc::c_void, 0, (::core::mem::size_of::<rgb>() as u64) .wrapping_mul(w as u64) .wrapping_mul(h as u64), ); y = 10; x = y; dx = leng as i64; dy = leng as i64; scale = 1; clen = 0; cscale = 3; i = 0; while i < depth as i64 { sc_up(); i += 1; i; } iter_string(b"VXH\0" as *const u8 as *const i8, depth); let mut fpix: *mut u8 = malloc((w * h * 3i64) as u64) as *mut u8; let mut maxv: f64 = 0 as f64; let mut dbuf: *mut f64 = buf as *mut f64; i = 3 * w * h - 1; while i >= 0 { if *dbuf.offset(i as isize) > maxv { maxv = *dbuf.offset(i as isize); } i -= 1; i; } i = 3 * h * w - 1; while i >= 0 { *fpix.offset(i as isize) = (255 as f64 * *dbuf.offset(i as isize) / maxv) as u8; i -= 1; i; } print!("P6\n{} {}\n255\n", w, h); fflush(stdout); fwrite( fpix as *const libc::c_void, (h * w * 3i64) as u64, 1, stdout, ); } }
void sierp(long leng, int depth) { long i; long h = leng + 20, w = leng + 20; /* allocate pixel buffer */ rgb *buf = malloc(sizeof(rgb) * w * h); pix = malloc(sizeof(rgb *) * h); for (i = 0; i < h; i++) pix[i] = buf + w * i; memset(buf, 0, sizeof(rgb) * w * h); /* init coords; scale up to desired; exec string */ x = y = 10; dx = leng; dy = leng; scale = 1; clen = 0; cscale = 3; for (i = 0; i < depth; i++) sc_up(); iter_string("VXH", depth); /* write color PNM file */ unsigned char *fpix = malloc(w * h * 3); double maxv = 0, *dbuf = (double*)buf; for (i = 3 * w * h - 1; i >= 0; i--) if (dbuf[i] > maxv) maxv = dbuf[i]; for (i = 3 * h * w - 1; i >= 0; i--) fpix[i] = 255 * dbuf[i] / maxv; printf("P6\n%ld %ld\n255\n", w, h); fflush(stdout); /* printf and fwrite may treat buffer differently */ fwrite(fpix, h * w * 3, 1, stdout); }
28
pub extern "C" fn sc_up() { unsafe { scale *= 2; x *= 2; y *= 2; cscale *= 3; } }
void sc_up() { scale *= 2; x *= 2; y *= 2; cscale *= 3; }
29
fn main(mut c: i32, mut v: *mut *mut i8) -> i32 { unsafe { let mut size: i32 = 0; let mut depth: i32 = 0; depth = if c > 1 { atoi(*v.offset(1 as isize)) } else { 10 }; size = 1 << depth; fprintf( stderr, b"size: %d depth: %d\n\0" as *const u8 as *const i8, size, depth, ); sierp(size as i64, depth + 2); return 0; } }
int main(int c, char ** v) { int size, depth; depth = (c > 1) ? atoi(v[1]) : 10; size = 1 << depth; fprintf(stderr, "size: %d depth: %d\n", size, depth); sierp(size, depth + 2); return 0; }
30
pub extern "C" fn h_rgb(mut x_0: i64, mut y_0: i64) { unsafe { let mut p: *mut rgb = &mut *(*pix.offset(y_0 as isize)).offset(x_0 as isize) as *mut rgb; let mut h: f64 = 6.0f64 * clen as f64 / cscale as f64; let mut VAL: f64 = 1 as f64; let mut c: f64 = 1 as f64 * VAL; let mut X: f64 = c * (1 as f64 - fabs(fmod(h, 2 as f64) - 1 as f64)); match h as i32 { 0 => { (*p).r += c; (*p).g += X; return; } 1 => { (*p).r += X; (*p).g += c; return; } 2 => { (*p).g += c; (*p).b += X; return; } 3 => { (*p).g += X; (*p).b += c; return; } 4 => { (*p).r += X; (*p).b += c; return; } _ => { (*p).r += c; (*p).b += X; } }; } }
void h_rgb(long long x, long long y) { rgb *p = &pix[y][x]; # define SAT 1 double h = 6.0 * clen / cscale; double VAL = 1; double c = SAT * VAL; double X = c * (1 - fabs(fmod(h, 2) - 1)); switch((int)h) { case 0: p->r += c; p->g += X; return; case 1: p->r += X; p->g += c; return; case 2: p->g += c; p->b += X; return; case 3: p->g += X; p->b += c; return; case 4: p->r += X; p->b += c; return; default: p->r += c; p->b += X; } }
31
fn main(mut argc: i32, mut argv: *mut *mut i8) -> i32 { unsafe { if argc != 2 { print!("Usage: benford <file>\n"); return 1; } let mut actual: *mut libc::c_float = get_actual_distribution(*argv.offset(1 as isize)); let mut expected: *mut libc::c_float = benford_distribution(); puts(b"digit\tactual\texpected\0" as *const u8 as *const i8); let mut i: i32 = 0; while i < 9 { print!( "{} {:.3} {:.3}\n", i + 1, *actual.offset(i as isize) as f64, *expected.offset(i as isize) as f64 ); i += 1; i; } return 0; } }
int main(int argc, char **argv) { if (argc != 2) { printf("Usage: benford <file>\n"); return EXIT_FAILURE; } float *actual = get_actual_distribution(argv[1]); float *expected = benford_distribution(); puts("digit\tactual\texpected"); for (int i = 0; i < 9; i++) printf("%d\t%.3f\t%.3f\n", i + 1, actual[i], expected[i]); return EXIT_SUCCESS; }
32
fn main() -> i32 { let mut i: i32 = 0; print!("Set [0,25]:\n"); i = 0; unsafe { while i < 26 { let mut s: [i8; 5] = [0; 5]; print!( "{} ", build_str_from_raw_ptr(addSuffix(i, s.as_mut_ptr(), 5) as *mut u8) ); i += 1; i; } } print!("{}", '\n' as i32); print!("Set [250,265]:\n"); i = 250; unsafe { while i < 266 { let mut s_0: [i8; 6] = [0; 6]; print!( "{} ", build_str_from_raw_ptr(addSuffix(i, s_0.as_mut_ptr(), 6) as *mut u8) ); i += 1; i; } } print!("{}", '\n' as i32); print!("Set [1000,1025]:\n"); i = 1000; unsafe { while i < 1026 { let mut s_1: [i8; 7] = [0; 7]; print!( "{} ", build_str_from_raw_ptr(addSuffix(i, s_1.as_mut_ptr(), 7) as *mut u8) ); i += 1; i; } } print!("{}", '\n' as i32); return 0; }
int main(void) { int i; printf("Set [0,25]:\n"); for (i = 0; i < 26; i++) { char s[5]; printf("%s ", addSuffix(i, s, 5)); } putchar('\n'); printf("Set [250,265]:\n"); for (i = 250; i < 266; i++) { char s[6]; printf("%s ", addSuffix(i, s, 6)); } putchar('\n'); printf("Set [1000,1025]:\n"); for (i = 1000; i < 1026; i++) { char s[7]; printf("%s ", addSuffix(i, s, 7)); } putchar('\n'); return 0; }
33
fn main() -> i32 { let mut test1: [range_t; 1] = [{ let mut init = range_tag { low: 1.1f64, high: 2.2f64, }; init }]; let mut test2: [range_t; 2] = [ { let mut init = range_tag { low: 6.1f64, high: 7.2f64, }; init }, { let mut init = range_tag { low: 7.2f64, high: 8.3f64, }; init }, ]; let mut test3: [range_t; 2] = [ { let mut init = range_tag { low: 4 as f64, high: 3 as f64, }; init }, { let mut init = range_tag { low: 2 as f64, high: 1 as f64, }; init }, ]; let mut test4: [range_t; 4] = [ { let mut init = range_tag { low: 4 as f64, high: 3 as f64, }; init }, { let mut init = range_tag { low: 2 as f64, high: 1 as f64, }; init }, { let mut init = range_tag { low: -1i32 as f64, high: -2i32 as f64, }; init }, { let mut init = range_tag { low: 3.9f64, high: 10 as f64, }; init }, ]; let mut test5: [range_t; 5] = [ { let mut init = range_tag { low: 1 as f64, high: 3 as f64, }; init }, { let mut init = range_tag { low: -6i32 as f64, high: -1i32 as f64, }; init }, { let mut init = range_tag { low: -4i32 as f64, high: -5i32 as f64, }; init }, { let mut init = range_tag { low: 8 as f64, high: 2 as f64, }; init }, { let mut init = range_tag { low: -6i32 as f64, high: -6i32 as f64, }; init }, ]; test_consolidate_ranges( test1.as_mut_ptr(), (::core::mem::size_of::<[range_t; 1]>() as u64) .wrapping_div(::core::mem::size_of::<range_t>() as u64), ); test_consolidate_ranges( test2.as_mut_ptr(), (::core::mem::size_of::<[range_t; 2]>() as u64) .wrapping_div(::core::mem::size_of::<range_t>() as u64), ); test_consolidate_ranges( test3.as_mut_ptr(), (::core::mem::size_of::<[range_t; 2]>() as u64) .wrapping_div(::core::mem::size_of::<range_t>() as u64), ); test_consolidate_ranges( test4.as_mut_ptr(), (::core::mem::size_of::<[range_t; 4]>() as u64) .wrapping_div(::core::mem::size_of::<range_t>() as u64), ); test_consolidate_ranges( test5.as_mut_ptr(), (::core::mem::size_of::<[range_t; 5]>() as u64) .wrapping_div(::core::mem::size_of::<range_t>() as u64), ); return 0; }
int main() { range_t test1[] = { {1.1, 2.2} }; range_t test2[] = { {6.1, 7.2}, {7.2, 8.3} }; range_t test3[] = { {4, 3}, {2, 1} }; range_t test4[] = { {4, 3}, {2, 1}, {-1, -2}, {3.9, 10} }; range_t test5[] = { {1, 3}, {-6, -1}, {-4, -5}, {8, 2}, {-6, -6} }; test_consolidate_ranges(test1, LENGTHOF(test1)); test_consolidate_ranges(test2, LENGTHOF(test2)); test_consolidate_ranges(test3, LENGTHOF(test3)); test_consolidate_ranges(test4, LENGTHOF(test4)); test_consolidate_ranges(test5, LENGTHOF(test5)); return 0; }
34
pub extern "C" fn consolidate_ranges(mut ranges: *mut range_t, mut count: u64) -> u64 { unsafe { normalize_ranges(ranges, count); let mut out_index: u64 = 0; let mut i: u64 = 0; while i < count { let mut j: u64 = i; loop { j = j.wrapping_add(1); if !(j < count && (*ranges.offset(j as isize)).low <= (*ranges.offset(i as isize)).high) { break; } if (*ranges.offset(i as isize)).high < (*ranges.offset(j as isize)).high { (*ranges.offset(i as isize)).high = (*ranges.offset(j as isize)).high; } } let fresh0 = out_index; out_index = out_index.wrapping_add(1); *ranges.offset(fresh0 as isize) = *ranges.offset(i as isize); i = j; } return out_index; } }
size_t consolidate_ranges(range_t* ranges, size_t count) { normalize_ranges(ranges, count); size_t out_index = 0; for (size_t i = 0; i < count; ) { size_t j = i; while (++j < count && ranges[j].low <= ranges[i].high) { if (ranges[i].high < ranges[j].high) ranges[i].high = ranges[j].high; } ranges[out_index++] = ranges[i]; i = j; } return out_index; }
35
pub extern "C" fn test_consolidate_ranges(mut ranges: *mut range_t, mut count: u64) { unsafe { print_ranges(ranges, count); print!(" -> "); count = consolidate_ranges(ranges, count); print_ranges(ranges, count); print!("\n"); } }
void test_consolidate_ranges(range_t* ranges, size_t count) { print_ranges(ranges, count); printf(" -> "); count = consolidate_ranges(ranges, count); print_ranges(ranges, count); printf("\n"); }
36
pub extern "C" fn normalize_ranges(mut ranges: *mut range_t, mut count: u64) { unsafe { let mut i: u64 = 0; while i < count { normalize_range(&mut *ranges.offset(i as isize)); i = i.wrapping_add(1); i; } qsort( ranges as *mut libc::c_void, count, ::core::mem::size_of::<range_t>() as u64, Some( range_compare as unsafe extern "C" fn(*const libc::c_void, *const libc::c_void) -> i32, ), ); } }
void normalize_ranges(range_t* ranges, size_t count) { for (size_t i = 0; i < count; ++i) normalize_range(&ranges[i]); qsort(ranges, count, sizeof(range_t), range_compare); }
37
pub extern "C" fn normalize_range(mut range: *mut range_t) { unsafe { if (*range).high < (*range).low { let mut tmp: f64 = (*range).low; (*range).low = (*range).high; (*range).high = tmp; } } }
void normalize_range(range_t* range) { if (range->high < range->low) { double tmp = range->low; range->low = range->high; range->high = tmp; } }
38
pub extern "C" fn range_compare(mut p1: *const libc::c_void, mut p2: *const libc::c_void) -> i32 { unsafe { let mut r1: *const range_t = p1 as *const range_t; let mut r2: *const range_t = p2 as *const range_t; if (*r1).low < (*r2).low { return -1; } if (*r1).low > (*r2).low { return 1; } if (*r1).high < (*r2).high { return -1; } if (*r1).high > (*r2).high { return 1; } return 0; } }
int range_compare(const void* p1, const void* p2) { const range_t* r1 = p1; const range_t* r2 = p2; if (r1->low < r2->low) return -1; if (r1->low > r2->low) return 1; if (r1->high < r2->high) return -1; if (r1->high > r2->high) return 1; return 0; }
39
pub extern "C" fn print_ranges(mut ranges: *const range_t, mut count: u64) { unsafe { if count == 0 { return; } print_range(&*ranges.offset(0 as isize)); let mut i: u64 = 1; while i < count { print!(", "); print_range(&*ranges.offset(i as isize)); i = i.wrapping_add(1); i; } } }
void print_ranges(const range_t* ranges, size_t count) { if (count == 0) return; print_range(&ranges[0]); for (size_t i = 1; i < count; ++i) { printf(", "); print_range(&ranges[i]); } }
40
pub extern "C" fn print_range(mut range: *const range_t) { print!("[{}, {}]", (*range).low, (*range).high); }
void print_range(const range_t* range) { printf("[%g, %g]", range->low, range->high); }
41
fn main() -> i32 { let mut us_coins: [i32; 7] = [100, 50, 25, 10, 5, 1, 0]; let mut eu_coins: [i32; 9] = [200, 100, 50, 20, 10, 5, 2, 1, 0]; unsafe { show(count(100, us_coins.as_mut_ptr().offset(2 as isize))); } show(count(1000, us_coins.as_mut_ptr())); show(count(1000 * 100, us_coins.as_mut_ptr())); show(count(10000 * 100, us_coins.as_mut_ptr())); show(count(100000 * 100, us_coins.as_mut_ptr())); print!("{}", '\n' as i32); show(count(1 * 100, eu_coins.as_mut_ptr())); show(count(1000 * 100, eu_coins.as_mut_ptr())); show(count(10000 * 100, eu_coins.as_mut_ptr())); show(count(100000 * 100, eu_coins.as_mut_ptr())); return 0; }
int main(void) { int us_coins[] = { 100, 50, 25, 10, 5, 1, 0 }; int eu_coins[] = { 200, 100, 50, 20, 10, 5, 2, 1, 0 }; show(count( 100, us_coins + 2)); show(count( 1000, us_coins)); show(count( 1000 * 100, us_coins)); show(count( 10000 * 100, us_coins)); show(count(100000 * 100, us_coins)); putchar('\n'); show(count( 1 * 100, eu_coins)); show(count( 1000 * 100, eu_coins)); show(count( 10000 * 100, eu_coins)); show(count(100000 * 100, eu_coins)); return 0; }
42
pub extern "C" fn count2(mut sum: i32, mut coins: *mut i32) -> i32 { unsafe { if *coins == 0 || sum < 0 { return 0; } if sum == 0 { return 1; } return count2(sum - *coins, coins) + count2(sum, coins.offset(1 as isize)); } }
int count2(int sum, int *coins) { if (!*coins || sum < 0) return 0; if (!sum) return 1; return count2(sum - *coins, coins) + count2(sum, coins + 1); }
43
pub extern "C" fn count(mut sum: i32, mut coins: *mut i32) -> i128_0 { unsafe { let mut n: i32 = 0; let mut i: i32 = 0; let mut k: i32 = 0; n = 0; while *coins.offset(n as isize) != 0 { n += 1; n; } let mut v: *mut *mut i128_0 = malloc((::core::mem::size_of::<*mut i32>() as u64).wrapping_mul(n as u64)) as *mut *mut i128_0; let mut idx: *mut i32 = malloc((::core::mem::size_of::<i32>() as u64).wrapping_mul(n as u64)) as *mut i32; i = 0; while i < n { *idx.offset(i as isize) = *coins.offset(i as isize); let ref mut fresh3 = *v.offset(i as isize); *fresh3 = calloc( ::core::mem::size_of::<i128_0>() as u64, *coins.offset(i as isize) as u64, ) as *mut i128_0; i += 1; i; } *(*v.offset(0 as isize)).offset((*coins.offset(0 as isize) - 1i32) as isize) = { let mut init = i128_0 { x: [1, 0] }; init }; k = 0; while k <= sum { i = 0; while i < n { let ref mut fresh4 = *idx.offset(i as isize); let fresh5 = *fresh4; *fresh4 = *fresh4 - 1; if fresh5 == 0 { *idx.offset(i as isize) = *coins.offset(i as isize) - 1; } i += 1; i; } let mut c: i128_0 = *(*v.offset(0 as isize)).offset(*idx.offset(0 as isize) as isize); i = 1; while i < n { let mut p: *mut i128_0 = (*v.offset(i as isize)).offset(*idx.offset(i as isize) as isize); (*p).x[0 as usize] = ((*p).x[0 as usize] as u64).wrapping_add(c.x[0 as usize]) as u64; (*p).x[1 as usize] = ((*p).x[1 as usize] as u64).wrapping_add(c.x[1 as usize]) as u64; if (*p).x[0 as usize] < c.x[0 as usize] { (*p).x[1 as usize] = ((*p).x[1 as usize]).wrapping_add(1); (*p).x[1 as usize]; } c = *p; i += 1; i; } k += 1; k; } let mut r: i128_0 = *(*v.offset((n - 1i32) as isize)).offset(*idx.offset((n - 1i32) as isize) as isize); i = 0; while i < n { free(*v.offset(i as isize) as *mut libc::c_void); i += 1; i; } free(v as *mut libc::c_void); free(idx as *mut libc::c_void); return r; } }
i128 count(int sum, int *coins) { int n, i, k; for (n = 0; coins[n]; n++); i128 **v = malloc(sizeof(int*) * n); int *idx = malloc(sizeof(int) * n); for (i = 0; i < n; i++) { idx[i] = coins[i]; // each v[i] is a cyclic buffer v[i] = calloc(sizeof(i128), coins[i]); } v[0][coins[0] - 1] = (i128) {{1, 0}}; for (k = 0; k <= sum; k++) { for (i = 0; i < n; i++) if (!idx[i]--) idx[i] = coins[i] - 1; i128 c = v[0][ idx[0] ]; for (i = 1; i < n; i++) { i128 *p = v[i] + idx[i]; // 128 bit addition p->x[0] += c.x[0]; p->x[1] += c.x[1]; if (p->x[0] < c.x[0]) // carry p->x[1] ++; c = *p; } } i128 r = v[n - 1][idx[n-1]]; for (i = 0; i < n; i++) free(v[i]); free(v); free(idx); return r; }
44
pub extern "C" fn show(mut v: i128_0) { let mut x: [u32; 4] = [ v.x[0 as usize] as u32, (v.x[0 as usize] >> 32i32) as u32, v.x[1 as usize] as u32, (v.x[1 as usize] >> 32i32) as u32, ]; let mut i: i32 = 0; let mut j: i32 = 0; let mut len: i32 = 4; let mut buf: [i8; 100] = [0; 100]; loop { let mut c: u64 = 0; i = len; loop { let fresh0 = i; i = i - 1; if !(fresh0 != 0) { break; } c = (c << 32i32).wrapping_add(x[i as usize] as u64); x[i as usize] = c.wrapping_div(10) as u32; c = (c).wrapping_rem(10) as u64; } let fresh1 = j; j = j + 1; buf[fresh1 as usize] = c.wrapping_add('0' as u64) as i8; len = 4; while x[(len - 1i32) as usize] == 0 { len -= 1; len; } if !(len != 0) { break; } } loop { let fresh2 = j; j = j - 1; if !(fresh2 != 0) { break; } print!("{}", buf[j as usize] as i32); } print!("{}", '\n' as i32); }
void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char buf[100]; do { uint64_t c = 0; for (i = len; i--; ) { c = (c << 32) + x[i]; x[i] = c / 10, c %= 10; } buf[j++] = c + '0'; for (len = 4; !x[len - 1]; len--); } while (len); while (j--) putchar(buf[j]); putchar('\n'); }
45
fn main() -> i32 { let mut i: i32 = 0; i = 2; while i < 100 { if semiprime(i) != 0 { print!(" {}", i); } i += 1; i; } print!("{}", '\n' as i32); return 0; }
int main(void) { int i; for (i = 2; i < 100; i++) if (semiprime(i)) printf(" %d", i); putchar('\n'); return 0; }
46
pub extern "C" fn semiprime(mut n: i32) -> i32 { let mut p: i32 = 0; let mut f: i32 = 0; p = 2; while f < 2 && p * p <= n { while 0 == n % p { n /= p; f += 1; f; } p += 1; p; } return (f + (n > 1i32) as i32 == 2) as i32; }
int semiprime(int n) { int p, f = 0; for (p = 2; f < 2 && p*p <= n; p++) while (0 == n % p) n /= p, f++; return f + (n > 1) == 2; }
47
fn main() -> i32 { let mut n: u64 = 1; let mut i: i32 = 0; while i < 30 { print!("{} ", n.count_ones() as i32); n = n.wrapping_mul(3); i += 1; i; } print!("\n"); let mut od: [i32; 30] = [0; 30]; let mut ne: i32 = 0; let mut no: i32 = 0; print!("evil : "); let mut n_0: i32 = 0; while ne + no < 60 { if (n_0 as u32).count_ones() as i32 & 1 == 0 { if ne < 30 { print!("{} ", n_0); ne += 1; ne; } } else if no < 30 { let fresh0 = no; no = no + 1; od[fresh0 as usize] = n_0; } n_0 += 1; n_0; } print!("\n"); print!("odious: "); let mut i_0: i32 = 0; while i_0 < 30 { print!("{} ", od[i_0 as usize]); i_0 += 1; i_0; } print!("\n"); return 0; }
int main() { { unsigned long long n = 1; for (int i = 0; i < 30; i++) { // __builtin_popcount() for unsigned int // __builtin_popcountl() for unsigned long // __builtin_popcountll() for unsigned long long printf("%d ", __builtin_popcountll(n)); n *= 3; } printf("\n"); } int od[30]; int ne = 0, no = 0; printf("evil : "); for (int n = 0; ne+no < 60; n++) { if ((__builtin_popcount(n) & 1) == 0) { if (ne < 30) { printf("%d ", n); ne++; } } else { if (no < 30) { od[no++] = n; } } } printf("\n"); printf("odious: "); for (int i = 0; i < 30; i++) { printf("%d ", od[i]); } printf("\n"); return 0; }
48
pub extern "C" fn InvokeComposed(mut f1: Class2Func, mut f2: Class2Func, mut val: f64) -> f64 { unsafe { return f1.expect("non-null function pointer")(f2.expect("non-null function pointer")(val)); } }
double InvokeComposed( Class2Func f1, Class2Func f2, double val ) { return f1(f2(val)); }
49
pub extern "C" fn WhichFunc(mut idx: i32) -> Class2Func { return if idx < 4 { Some(functionA as unsafe extern "C" fn(f64) -> f64) } else { Some(functionB as unsafe extern "C" fn(f64) -> f64) }; }
Class2Func WhichFunc( int idx) { return (idx < 4) ? &functionA : &functionB; }
50
fn main(mut argc: i32, mut argv: *mut *mut i8) -> i32 { unsafe { let mut ix: i32 = 0; let mut c: Composition = 0 as *mut sComposition; print!( "Function1(functionA, 3.0) = {}\n", Function1(WhichFunc(0), 3.0f64) ); ix = 0; while ix < 4 { c = Compose(funcListA[ix as usize], funcListB[ix as usize]); print!("Compostion {}(0.9) = {}\n", ix, CallComposed(c, 0.9f64)); ix += 1; ix; } return 0; } }
int main(int argc, char *argv[]) { int ix; Composition c; printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0)); for (ix=0; ix<4; ix++) { c = Compose(funcListA[ix], funcListB[ix]); printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9)); } return 0; }
51
pub extern "C" fn Function1(mut f2: Class2Func, mut val: f64) -> f64 { unsafe { return f2.expect("non-null function pointer")(val); } }
double Function1( Class2Func f2, double val ) { return f2(val); }
52
pub extern "C" fn functionB(mut v: f64) -> f64 { unsafe { return exp(log(v) / 3 as f64); } }
double functionB(double v) { return exp(log(v)/3); }
53
pub extern "C" fn Compose(mut f1: Class2Func, mut f2: Class2Func) -> Composition { unsafe { let mut comp: Composition = malloc(::core::mem::size_of::<sComposition>() as u64) as Composition; (*comp).f1 = f1; (*comp).f2 = f2; return comp; } }
Composition Compose( Class2Func f1, Class2Func f2) { Composition comp = malloc(sizeof(struct sComposition)); comp->f1 = f1; comp->f2 = f2; return comp; }
54
pub extern "C" fn functionA(mut v: f64) -> f64 { return v * v * v; }
double functionA( double v) { return v*v*v; }
55
pub extern "C" fn CallComposed(mut comp: Composition, mut val: f64) -> f64 { return ((*comp).f1).expect("non-null function pointer")(((*comp).f2) .expect("non-null function pointer")( val )); }
double CallComposed( Composition comp, double val ) { return comp->f1( comp->f2(val) ); }
56
pub extern "C" fn testcase(mut pszTest: *const i8) { unsafe { let mut abyAddr: [u8; 16] = [0; 16]; let mut bIsIPv6: i32 = 0; let mut nPort: i32 = 0; let mut bSuccess: i32 = 0; print!("Test case {}\n", build_str_from_raw_ptr(pszTest as *mut u8)); let mut pszTextCursor: *const i8 = pszTest; bSuccess = ParseIPv4OrIPv6( &mut pszTextCursor, abyAddr.as_mut_ptr(), &mut nPort, &mut bIsIPv6, ); if bSuccess == 0 { print!( "parse failed, at about index {}; rest: {}\n", pszTextCursor.offset_from(pszTest) as i64, build_str_from_raw_ptr(pszTextCursor as *mut u8) ); return; } print!("addr: "); dumpbin(abyAddr.as_mut_ptr(), if bIsIPv6 != 0 { 16 } else { 4 }); print!("\n"); if 0 == nPort { print!("port absent"); } else { print!("port: {}", htons(nPort as u16) as i32); } print!("\n\n"); } }
void testcase(const char *pszTest) { unsigned char abyAddr[16]; int bIsIPv6; int nPort; int bSuccess; printf("Test case '%s'\n", pszTest); const char *pszTextCursor = pszTest; bSuccess = ParseIPv4OrIPv6(&pszTextCursor, abyAddr, &nPort, &bIsIPv6); if (!bSuccess) { printf("parse failed, at about index %d; rest: '%s'\n", pszTextCursor - pszTest, pszTextCursor); return; } printf("addr: "); dumpbin(abyAddr, bIsIPv6 ? 16 : 4); printf("\n"); if (0 == nPort) printf("port absent"); else printf("port: %d", htons(nPort)); printf("\n\n"); }
57
pub extern "C" fn htons(mut us: u16) -> u16 { unsafe { return (((*(&mut us as *mut u16 as *mut u8).offset(0 as isize) as i32) << 8i32) + *(&mut us as *mut u16 as *mut u8).offset(1 as isize) as i32) as u16; } }
unsigned short htons(unsigned short us) { return (((unsigned char *)&us)[0] << 8) + ((unsigned char *)&us)[1]; }
58
pub extern "C" fn ParseIPv4OrIPv6_2( mut pszText: *const i8, mut abyAddr: *mut u8, mut pnPort: *mut i32, mut pbIsIPv6: *mut i32, ) -> i32 { unsafe { let mut pszTextLocal: *const i8 = pszText; return ParseIPv4OrIPv6(&mut pszTextLocal, abyAddr, pnPort, pbIsIPv6); } }
int ParseIPv4OrIPv6_2(const char *pszText, unsigned char *abyAddr, int *pnPort, int *pbIsIPv6) { const char *pszTextLocal = pszText; return ParseIPv4OrIPv6(&pszTextLocal, abyAddr, pnPort, pbIsIPv6); }
59
pub extern "C" fn dumpbin(mut pbyBin: *mut u8, mut nLen: i32) { unsafe { let mut i: i32 = 0; i = 0; while i < nLen { print!("{:02x}", *pbyBin.offset(i as isize) as i32); i += 1; i; } } }
void dumpbin(unsigned char *pbyBin, int nLen) { int i; for (i = 0; i < nLen; ++i) { printf("%02x", pbyBin[i]); } }
60
extern "C" fn _parseHex(mut pchCursor: *mut *const i8) -> u32 { unsafe { let mut nVal: u32 = 0; let mut chNow: i8 = 0; loop { chNow = (**pchCursor as i32 & 0x5fi32) as i8; if !(chNow as i32 >= '0' as i32 & 0x5f && chNow as i32 <= '9' as i32 & 0x5f || chNow as i32 >= 'A' as i32 && chNow as i32 <= 'F' as i32) { break; } let mut nybbleValue: u8 = 0; chNow = (chNow as i32 - 0x10i32) as i8; nybbleValue = (if chNow as i32 > 9i32 { chNow as i32 - (0x31 - 0xa) } else { chNow as i32 }) as u8; nVal <<= 4; nVal = nVal.wrapping_add(nybbleValue as u32); *pchCursor = (*pchCursor).offset(1); *pchCursor; } return nVal; } }
static unsigned int _parseHex(const char **pchCursor) { unsigned int nVal = 0; char chNow; while (chNow = **pchCursor & 0x5f, //(collapses case, but mutilates digits) (chNow >= ('0' & 0x5f) && chNow <= ('9' & 0x5f)) || (chNow >= 'A' && chNow <= 'F')) { unsigned char nybbleValue; chNow -= 0x10; //scootch digital values down; hex now offset by x31 nybbleValue = (chNow > 9 ? chNow - (0x31 - 0x0a) : chNow); //shift nybble in nVal <<= 4; nVal += nybbleValue; ++*pchCursor; } return nVal; }
61
pub extern "C" fn ParseIPv4OrIPv6( mut ppszText: *mut *const i8, mut abyAddr: *mut u8, mut pnPort: *mut i32, mut pbIsIPv6: *mut i32, ) -> i32 { unsafe { let mut abyAddrLocal: *mut u8 = 0 as *mut u8; let mut abyDummyAddr: [u8; 16] = [0; 16]; let mut pchColon: *const i8 = strchr(*ppszText, ':' as i32); let mut pchDot: *const i8 = strchr(*ppszText, '.' as i32); let mut pchOpenBracket: *const i8 = strchr(*ppszText, '[' as i32); let mut pchCloseBracket: *const i8 = 0 as *const i8; let mut bIsIPv6local: i32 = (!pchOpenBracket.is_null() || pchDot.is_null() || !pchColon.is_null() && (pchDot.is_null() || pchColon < pchDot)) as i32; if bIsIPv6local != 0 { pchCloseBracket = strchr(*ppszText, ']' as i32); if !pchOpenBracket.is_null() && (pchCloseBracket.is_null() || pchCloseBracket < pchOpenBracket) { return 0; } } else if pchDot.is_null() || !pchColon.is_null() && pchColon < pchDot { return 0; } if !pbIsIPv6.is_null() { *pbIsIPv6 = bIsIPv6local; } abyAddrLocal = abyAddr; if abyAddrLocal.is_null() { abyAddrLocal = abyDummyAddr.as_mut_ptr(); } if bIsIPv6local == 0 { let mut pbyAddrCursor: *mut u8 = abyAddrLocal; let mut nVal: u32 = 0; let mut pszTextBefore: *const i8 = *ppszText; nVal = _parseDecimal(ppszText); if '.' as i32 != **ppszText as i32 || nVal > 255 || pszTextBefore == *ppszText { return 0; } let fresh0 = pbyAddrCursor; pbyAddrCursor = pbyAddrCursor.offset(1); *fresh0 = nVal as u8; *ppszText = (*ppszText).offset(1); *ppszText; pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if '.' as i32 != **ppszText as i32 || nVal > 255 || pszTextBefore == *ppszText { return 0; } let fresh1 = pbyAddrCursor; pbyAddrCursor = pbyAddrCursor.offset(1); *fresh1 = nVal as u8; *ppszText = (*ppszText).offset(1); *ppszText; pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if '.' as i32 != **ppszText as i32 || nVal > 255 || pszTextBefore == *ppszText { return 0; } let fresh2 = pbyAddrCursor; pbyAddrCursor = pbyAddrCursor.offset(1); *fresh2 = nVal as u8; *ppszText = (*ppszText).offset(1); *ppszText; pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if nVal > 255 || pszTextBefore == *ppszText { return 0; } let fresh3 = pbyAddrCursor; pbyAddrCursor = pbyAddrCursor.offset(1); *fresh3 = nVal as u8; if ':' as i32 == **ppszText as i32 && !pnPort.is_null() { let mut usPortNetwork: u16 = 0; *ppszText = (*ppszText).offset(1); *ppszText; pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if nVal > 65535 || pszTextBefore == *ppszText { return 0; }; *(&mut usPortNetwork as *mut u16 as *mut u8).offset(0 as isize) = ((nVal & 0xff00u32) >> 8) as u8; *(&mut usPortNetwork as *mut u16 as *mut u8).offset(1 as isize) = (nVal & 0xffu32) as u8; *pnPort = usPortNetwork as i32; return 1; } else { if !pnPort.is_null() { *pnPort = 0; } return 1; } } else { let mut pbyAddrCursor_0: *mut u8 = 0 as *mut u8; let mut pbyZerosLoc: *mut u8 = 0 as *mut u8; let mut bIPv4Detected: i32 = 0; let mut nIdx: i32 = 0; if !pchOpenBracket.is_null() { *ppszText = pchOpenBracket.offset(1 as isize); } pbyAddrCursor_0 = abyAddrLocal; pbyZerosLoc = 0 as *mut u8; bIPv4Detected = 0; nIdx = 0; while nIdx < 8 { let mut pszTextBefore_0: *const i8 = *ppszText; let mut nVal_0: u32 = _parseHex(ppszText); if pszTextBefore_0 == *ppszText { if !pbyZerosLoc.is_null() { if pbyZerosLoc == pbyAddrCursor_0 { nIdx -= 1; nIdx; break; } else { return 0; } } else { if ':' as i32 != **ppszText as i32 { return 0; } if 0 == nIdx { *ppszText = (*ppszText).offset(1); *ppszText; if ':' as i32 != **ppszText as i32 { return 0; } } pbyZerosLoc = pbyAddrCursor_0; *ppszText = (*ppszText).offset(1); *ppszText; } } else if '.' as i32 == **ppszText as i32 { let mut pszTextlocal: *const i8 = pszTextBefore_0; let mut abyAddrlocal: [u8; 16] = [0; 16]; let mut bIsIPv6local_0: i32 = 0; let mut bParseResultlocal: i32 = ParseIPv4OrIPv6( &mut pszTextlocal, abyAddrlocal.as_mut_ptr(), 0 as *mut i32, &mut bIsIPv6local_0, ); *ppszText = pszTextlocal; if bParseResultlocal == 0 || bIsIPv6local_0 != 0 { return 0; } let fresh4 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh4 = abyAddrlocal[0 as usize]; let fresh5 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh5 = abyAddrlocal[1 as usize]; let fresh6 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh6 = abyAddrlocal[2 as usize]; let fresh7 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh7 = abyAddrlocal[3 as usize]; nIdx += 1; nIdx; bIPv4Detected = 1; break; } else { if nVal_0 > 65535 { return 0; } let fresh8 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh8 = (nVal_0 >> 8i32) as u8; let fresh9 = pbyAddrCursor_0; pbyAddrCursor_0 = pbyAddrCursor_0.offset(1); *fresh9 = (nVal_0 & 0xffu32) as u8; if !(':' as i32 == **ppszText as i32) { break; } *ppszText = (*ppszText).offset(1); *ppszText; } nIdx += 1; nIdx; } if !pbyZerosLoc.is_null() { let mut nHead: i32 = pbyZerosLoc.offset_from(abyAddrLocal) as i32; let mut nTail: i32 = nIdx * 2 - pbyZerosLoc.offset_from(abyAddrLocal) as i32; let mut nZeros: i32 = 16 - nTail - nHead; memmove( &mut *abyAddrLocal.offset((16 - nTail) as isize) as *mut u8 as *mut libc::c_void, pbyZerosLoc as *const libc::c_void, nTail as u64, ); memset(pbyZerosLoc as *mut libc::c_void, 0, nZeros as u64); } if bIPv4Detected != 0 { static mut abyPfx: [u8; 12] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]; if 0 != memcmp( abyAddrLocal as *const libc::c_void, abyPfx.as_ptr() as *const libc::c_void, ::core::mem::size_of::<[u8; 12]>() as u64, ) { return 0; } } if !pchOpenBracket.is_null() { if ']' as i32 != **ppszText as i32 { return 0; } *ppszText = (*ppszText).offset(1); *ppszText; } if ':' as i32 == **ppszText as i32 && !pnPort.is_null() { let mut pszTextBefore_1: *const i8 = 0 as *const i8; let mut nVal_1: u32 = 0; let mut usPortNetwork_0: u16 = 0; *ppszText = (*ppszText).offset(1); *ppszText; pszTextBefore_1 = *ppszText; pszTextBefore_1 = *ppszText; nVal_1 = _parseDecimal(ppszText); if nVal_1 > 65535 || pszTextBefore_1 == *ppszText { return 0; }; *(&mut usPortNetwork_0 as *mut u16 as *mut u8).offset(0 as isize) = ((nVal_1 & 0xff00u32) >> 8) as u8; *(&mut usPortNetwork_0 as *mut u16 as *mut u8).offset(1 as isize) = (nVal_1 & 0xffu32) as u8; *pnPort = usPortNetwork_0 as i32; return 1; } else { if !pnPort.is_null() { *pnPort = 0; } return 1; } }; } }
int ParseIPv4OrIPv6(const char **ppszText, unsigned char *abyAddr, int *pnPort, int *pbIsIPv6) { unsigned char *abyAddrLocal; unsigned char abyDummyAddr[16]; //find first colon, dot, and open bracket const char *pchColon = strchr(*ppszText, ':'); const char *pchDot = strchr(*ppszText, '.'); const char *pchOpenBracket = strchr(*ppszText, '['); const char *pchCloseBracket = NULL; //we'll consider this to (probably) be IPv6 if we find an open //bracket, or an absence of dots, or if there is a colon, and it //precedes any dots that may or may not be there int bIsIPv6local = NULL != pchOpenBracket || NULL == pchDot || (NULL != pchColon && (NULL == pchDot || pchColon < pchDot)); //OK, now do a little further sanity check our initial guess... if (bIsIPv6local) { //if open bracket, then must have close bracket that follows somewhere pchCloseBracket = strchr(*ppszText, ']'); if (NULL != pchOpenBracket && (NULL == pchCloseBracket || pchCloseBracket < pchOpenBracket)) return 0; } else //probably ipv4 { //dots must exist, and precede any colons if (NULL == pchDot || (NULL != pchColon && pchColon < pchDot)) return 0; } //we figured out this much so far.... if (NULL != pbIsIPv6) *pbIsIPv6 = bIsIPv6local; //especially for IPv6 (where we will be decompressing and validating) //we really need to have a working buffer even if the caller didn't //care about the results. abyAddrLocal = abyAddr; //prefer to use the caller's if (NULL == abyAddrLocal) //but use a dummy if we must abyAddrLocal = abyDummyAddr; //OK, there should be no correctly formed strings which are miscategorized, //and now any format errors will be found out as we continue parsing //according to plan. if (!bIsIPv6local) //try to parse as IPv4 { //4 dotted quad decimal; optional port if there is a colon //since there are just 4, and because the last one can be terminated //differently, I'm just going to unroll any potential loop. unsigned char *pbyAddrCursor = abyAddrLocal; unsigned int nVal; const char *pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); //get first val if ('.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText) //must be in range and followed by dot and nonempty return 0; *(pbyAddrCursor++) = (unsigned char)nVal; //stick it in addr ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); //get second val if ('.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText) return 0; *(pbyAddrCursor++) = (unsigned char)nVal; ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); //get third val if ('.' != **ppszText || nVal > 255 || pszTextBefore == *ppszText) return 0; *(pbyAddrCursor++) = (unsigned char)nVal; ++(*ppszText); //past the dot pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); //get fourth val if (nVal > 255 || pszTextBefore == *ppszText) //(we can terminate this one in several ways) return 0; *(pbyAddrCursor++) = (unsigned char)nVal; if (':' == **ppszText && NULL != pnPort) //have port part, and we want it { unsigned short usPortNetwork; //save value in network order ++(*ppszText); //past the colon pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if (nVal > 65535 || pszTextBefore == *ppszText) return 0; ((unsigned char *)&usPortNetwork)[0] = (nVal & 0xff00) >> 8; ((unsigned char *)&usPortNetwork)[1] = (nVal & 0xff); *pnPort = usPortNetwork; return 1; } else //finished just with ip address { if (NULL != pnPort) *pnPort = 0; //indicate we have no port part return 1; } } else //try to parse as IPv6 { unsigned char *pbyAddrCursor; unsigned char *pbyZerosLoc; int bIPv4Detected; int nIdx; //up to 8 16-bit hex quantities, separated by colons, with at most one //empty quantity, acting as a stretchy run of zeroes. optional port //if there are brackets followed by colon and decimal port number. //A further form allows an ipv4 dotted quad instead of the last two //16-bit quantities, but only if in the ipv4 space ::ffff:x:x . if (NULL != pchOpenBracket) //start past the open bracket, if it exists *ppszText = pchOpenBracket + 1; pbyAddrCursor = abyAddrLocal; pbyZerosLoc = NULL; //if we find a 'zero compression' location bIPv4Detected = 0; for (nIdx = 0; nIdx < 8; ++nIdx) //we've got up to 8 of these, so we will use a loop { const char *pszTextBefore = *ppszText; unsigned nVal = _parseHex(ppszText); //get value; these are hex if (pszTextBefore == *ppszText) //if empty, we are zero compressing; note the loc { if (NULL != pbyZerosLoc) //there can be only one! { //unless it's a terminal empty field, then this is OK, it just means we're done with the host part if (pbyZerosLoc == pbyAddrCursor) { --nIdx; break; } return 0; //otherwise, it's a format error } if (':' != **ppszText) //empty field can only be via : return 0; if (0 == nIdx) //leading zero compression requires an extra peek, and adjustment { ++(*ppszText); if (':' != **ppszText) return 0; } pbyZerosLoc = pbyAddrCursor; ++(*ppszText); } else { if ('.' == **ppszText) //special case of ipv4 convenience notation { //who knows how to parse ipv4? we do! const char *pszTextlocal = pszTextBefore; //back it up unsigned char abyAddrlocal[16]; int bIsIPv6local; int bParseResultlocal = ParseIPv4OrIPv6(&pszTextlocal, abyAddrlocal, NULL, &bIsIPv6local); *ppszText = pszTextlocal; //success or fail, remember the terminating char if (!bParseResultlocal || bIsIPv6local) //must parse and must be ipv4 return 0; //transfer addrlocal into the present location *(pbyAddrCursor++) = abyAddrlocal[0]; *(pbyAddrCursor++) = abyAddrlocal[1]; *(pbyAddrCursor++) = abyAddrlocal[2]; *(pbyAddrCursor++) = abyAddrlocal[3]; ++nIdx; //pretend like we took another short, since the ipv4 effectively is two shorts bIPv4Detected = 1; //remember how we got here for further validation later break; //totally done with address } if (nVal > 65535) //must be 16 bit quantity return 0; *(pbyAddrCursor++) = nVal >> 8; //transfer in network order *(pbyAddrCursor++) = nVal & 0xff; if (':' == **ppszText) //typical case inside; carry on { ++(*ppszText); } else //some other terminating character; done with this parsing parts { break; } } } //handle any zero compression we found if (NULL != pbyZerosLoc) { int nHead = (int)(pbyZerosLoc - abyAddrLocal); //how much before zero compression int nTail = nIdx * 2 - (int)(pbyZerosLoc - abyAddrLocal); //how much after zero compression int nZeros = 16 - nTail - nHead; //how much zeros memmove(&abyAddrLocal[16 - nTail], pbyZerosLoc, nTail); //scootch stuff down memset(pbyZerosLoc, 0, nZeros); //clear the compressed zeros } //validation of ipv4 subspace ::ffff:x.x if (bIPv4Detected) { static const unsigned char abyPfx[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; if (0 != memcmp(abyAddrLocal, abyPfx, sizeof(abyPfx))) return 0; } //close bracket if (NULL != pchOpenBracket) { if (']' != **ppszText) return 0; ++(*ppszText); } if (':' == **ppszText && NULL != pnPort) //have port part, and we want it { const char *pszTextBefore; unsigned int nVal; unsigned short usPortNetwork; //save value in network order ++(*ppszText); //past the colon pszTextBefore = *ppszText; pszTextBefore = *ppszText; nVal = _parseDecimal(ppszText); if (nVal > 65535 || pszTextBefore == *ppszText) return 0; ((unsigned char *)&usPortNetwork)[0] = (nVal & 0xff00) >> 8; ((unsigned char *)&usPortNetwork)[1] = (nVal & 0xff); *pnPort = usPortNetwork; return 1; } else //finished just with ip address { if (NULL != pnPort) *pnPort = 0; //indicate we have no port part return 1; } } }
62
extern "C" fn _parseDecimal(mut pchCursor: *mut *const i8) -> u32 { unsafe { let mut nVal: u32 = 0; let mut chNow: i8 = 0; loop { chNow = **pchCursor; if !(chNow as i32 >= '0' as i32 && chNow as i32 <= '9' as i32) { break; } nVal = nVal.wrapping_mul(10); nVal = nVal.wrapping_add((chNow as i32 - '0' as i32) as u32); *pchCursor = (*pchCursor).offset(1); *pchCursor; } return nVal; } }
static unsigned int _parseDecimal(const char **pchCursor) { unsigned int nVal = 0; char chNow; while (chNow = **pchCursor, chNow >= '0' && chNow <= '9') { //shift digit in nVal *= 10; nVal += chNow - '0'; ++*pchCursor; } return nVal; }
63
fn main(mut argc: i32, mut argv: *mut *mut i8) -> i32 { unsafe { testcase(b"127.0.0.1\0" as *const u8 as *const i8); testcase(b"127.0.0.1:80\0" as *const u8 as *const i8); testcase(b"::1\0" as *const u8 as *const i8); testcase(b"[::1]:80\0" as *const u8 as *const i8); testcase(b"2605:2700:0:3::4713:93e3\0" as *const u8 as *const i8); testcase(b"[2605:2700:0:3::4713:93e3]:80\0" as *const u8 as *const i8); testcase(b"::ffff:192.168.173.22\0" as *const u8 as *const i8); testcase(b"[::ffff:192.168.173.22]:80\0" as *const u8 as *const i8); testcase(b"1::\0" as *const u8 as *const i8); testcase(b"[1::]:80\0" as *const u8 as *const i8); testcase(b"::\0" as *const u8 as *const i8); testcase(b"[::]:80\0" as *const u8 as *const i8); return 0; } }
int main(int argc, char *argv[]) { //The "localhost" IPv4 address testcase("127.0.0.1"); //The "localhost" IPv4 address, with a specified port (80) testcase("127.0.0.1:80"); //The "localhost" IPv6 address testcase("::1"); //The "localhost" IPv6 address, with a specified port (80) testcase("[::1]:80"); //Rosetta Code's primary server's public IPv6 address testcase("2605:2700:0:3::4713:93e3"); //Rosetta Code's primary server's public IPv6 address, with a specified port (80) testcase("[2605:2700:0:3::4713:93e3]:80"); //ipv4 space testcase("::ffff:192.168.173.22"); //ipv4 space with port testcase("[::ffff:192.168.173.22]:80"); //trailing compression testcase("1::"); //trailing compression with port testcase("[1::]:80"); //'any' address compression testcase("::"); //'any' address compression with port testcase("[::]:80"); return 0; }
64
pub extern "C" fn example() { print!("Example\n"); }
void example() { printf("Example\n"); }
65
fn main(mut argc: i32, mut argv: *mut *mut i8) -> i32 { unsafe { repeat( ::core::mem::transmute::< Option<unsafe extern "C" fn() -> ()>, Option<unsafe extern "C" fn() -> ()>, >(Some(::core::mem::transmute::< unsafe extern "C" fn() -> (), unsafe extern "C" fn() -> (), >(example))), 4, ); return 0; } }
int main(int argc, char *argv[]) { repeat(example, 4); return 0; }
66
pub extern "C" fn repeat(mut f: Option<unsafe extern "C" fn() -> ()>, mut n: u32) { unsafe { loop { let fresh0 = n; n = n.wrapping_sub(1); if !(fresh0 > 0) { break; }; (Some(f.expect("non-null function pointer"))).expect("non-null function pointer")(); } } }
void repeat(void (*f)(void), unsigned int n) { while (n-->0) (*f)(); //or just f() }
67
pub extern "C" fn vc_cmp(mut a: *const libc::c_void, mut b: *const libc::c_void) -> i32 { unsafe { return (*(b as *const vcount)).c - (*(a as *const vcount)).c; } }
int vc_cmp(const void *a, const void *b) { return ((const vcount*)b)->c - ((const vcount*)a)->c; }
68
pub extern "C" fn cmp_dbl(mut a: *const libc::c_void, mut b: *const libc::c_void) -> i32 { unsafe { let mut x: f64 = *(a as *const f64) - *(b as *const f64); return if x < 0 as f64 { -1 } else { (x > 0 as f64) as i32 }; } }
int cmp_dbl(const void *a, const void *b) { double x = *(const double*)a - *(const double*)b; return x < 0 ? -1 : x > 0; }
69
pub extern "C" fn get_mode(mut x: *mut f64, mut len_0: i32, mut list: *mut *mut vcount) -> i32 { unsafe { let mut i: i32 = 0; let mut j: i32 = 0; let mut vc: *mut vcount = 0 as *mut vcount; qsort( x as *mut libc::c_void, len_0 as u64, ::core::mem::size_of::<f64>() as u64, Some(cmp_dbl as unsafe extern "C" fn(*const libc::c_void, *const libc::c_void) -> i32), ); i = 0; j = 1; while i < len_0 - 1 { i += 1; i; j += (*x.offset(i as isize) != *x.offset((i + 1i32) as isize)) as i32; } vc = malloc((::core::mem::size_of::<vcount>() as u64).wrapping_mul(j as u64)) as *mut vcount; *list = vc; (*vc.offset(0 as isize)).v = *x.offset(0 as isize); (*vc.offset(0 as isize)).c = 1; j = 0; i = j; while i < len_0 - 1 { if *x.offset(i as isize) != *x.offset((i + 1i32) as isize) { j += 1; (*vc.offset(j as isize)).v = *x.offset((i + 1i32) as isize); } i += 1; i; let ref mut fresh0 = (*vc.offset(j as isize)).c; *fresh0 += 1; *fresh0; } qsort( vc as *mut libc::c_void, (j + 1i32) as u64, ::core::mem::size_of::<vcount>() as u64, Some(vc_cmp as unsafe extern "C" fn(*const libc::c_void, *const libc::c_void) -> i32), ); i = 0; while i <= j && (*vc.offset(i as isize)).c == (*vc.offset(0 as isize)).c { i += 1; i; } return i; } }
int get_mode(double* x, int len, vcount **list) { int i, j; vcount *vc; /* sort values */ qsort(x, len, sizeof(double), cmp_dbl); /* count occurence of each value */ for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1])); *list = vc = malloc(sizeof(vcount) * j); vc[0].v = x[0]; vc[0].c = 1; /* generate list value-count pairs */ for (i = j = 0; i < len - 1; i++, vc[j].c++) if (x[i] != x[i + 1]) vc[++j].v = x[i + 1]; /* sort that by count in descending order */ qsort(vc, j + 1, sizeof(vcount), vc_cmp); /* the number of entries with same count as the highest */ for (i = 0; i <= j && vc[i].c == vc[0].c; i++); return i; }
70
fn main() -> i32 { unsafe { let mut values: [f64; 13] = [ 1 as f64, 3 as f64, 6 as f64, 6 as f64, 6 as f64, 6 as f64, 7 as f64, 7 as f64, 12 as f64, 12 as f64, 12 as f64, 12 as f64, 17 as f64, ]; let mut vc: *mut vcount = 0 as *mut vcount; let mut i: i32 = 0; let mut n_modes: i32 = get_mode( values.as_mut_ptr(), (::core::mem::size_of::<[f64; 13]>() as u64) .wrapping_div(::core::mem::size_of::<f64>() as u64) as i32, &mut vc, ); print!("got {} modes:\n", n_modes); i = 0; while i < n_modes { print!( " value = {}, count = {}\n", (*vc.offset(i as isize)).v, (*vc.offset(i as isize)).c ); i += 1; i; } free(vc as *mut libc::c_void); return 0; } }
int main() { double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 }; # define len sizeof(values)/sizeof(double) vcount *vc; int i, n_modes = get_mode(values, len, &vc); printf("got %d modes:\n", n_modes); for (i = 0; i < n_modes; i++) printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c); free(vc); return 0; }
71
fn main() -> i32 { print!("Pi is {}\n", pi(3e-4f64)); return 0; }
int main() { printf("Pi is %f\n", pi(3e-4)); /* set to 1e-4 for some fun */ return 0; }
72
pub extern "C" fn pi(mut tolerance: f64) -> f64 { let mut x: f64 = 0.; let mut y: f64 = 0.; let mut val: f64 = 0.; let mut error: f64 = 0.; let mut sampled: u64 = 0; let mut hit: u64 = 0; let mut i: u64 = 0; unsafe { loop { i = 1000000; while i != 0 { x = rand() as f64 / (2147483647 as f64 + 1.0f64); y = rand() as f64 / (2147483647 as f64 + 1.0f64); if x * x + y * y < 1 as f64 { hit = hit.wrapping_add(1); hit; } i = i.wrapping_sub(1); i; sampled = sampled.wrapping_add(1); sampled; } val = hit as f64 / sampled as f64; error = sqrt(val * (1 as f64 - val) / sampled as f64) * 4 as f64; val *= 4 as f64; fprintf( stderr, b"Pi = %f +/- %5.3e at %ldM samples.\r\0" as *const u8 as *const i8, val, error, sampled.wrapping_div(1000000), ); if !(hit == 0 || error > tolerance) { break; } } } return val; }
double pi(double tolerance) { double x, y, val, error; unsigned long sampled = 0, hit = 0, i; do { /* don't check error every turn, make loop tight */ for (i = 1000000; i; i--, sampled++) { x = rand() / (RAND_MAX + 1.0); y = rand() / (RAND_MAX + 1.0); if (x * x + y * y < 1) hit ++; } val = (double) hit / sampled; error = sqrt(val * (1 - val) / sampled) * 4; val *= 4; /* some feedback, or user gets bored */ fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples.\r", val, error, sampled/1000000); } while (!hit || error > tolerance); /* !hit is for completeness's sake; if no hit after 1M samples, your rand() is BROKEN */ return val; }
73
pub unsafe extern "C" fn sma(mut action: u32, mut args: ...) -> sma_result_t { let mut vl: ::core::ffi::VaListImpl; let mut r: sma_result_t = sma_result { handle: 0 as *mut sma_obj_t, }; let mut o: *mut sma_obj_t = 0 as *mut sma_obj_t; let mut v_0: f64 = 0.; vl = args.clone(); match action as u32 { 0 => { r.handle = malloc(::core::mem::size_of::<sma_obj_t>() as u64) as *mut sma_obj_t; (*r.handle).sma = 0.0f64; (*r.handle).period = vl.arg::<i32>(); (*r.handle).values = malloc( ((*r.handle).period as u64).wrapping_mul(::core::mem::size_of::<f64>() as u64), ) as *mut f64; (*r.handle).lv = 0; (*r.handle).sum = 0.0f64; } 1 => { r.handle = vl.arg::<*mut sma_obj_t>(); free((*r.handle).values as *mut libc::c_void); free(r.handle as *mut libc::c_void); r.handle = 0 as *mut sma_obj_t; } 2 => { o = vl.arg::<*mut sma_obj_t>(); r.values = (*o).values; } 4 => { o = vl.arg::<*mut sma_obj_t>(); r.sma = (*o).sma; } 3 => { o = vl.arg::<*mut sma_obj_t>(); v_0 = vl.arg::<f64>(); if (*o).lv < (*o).period { let fresh0 = (*o).lv; (*o).lv = (*o).lv + 1; *((*o).values).offset(fresh0 as isize) = v_0; (*o).sum += v_0; (*o).sma = (*o).sum / (*o).lv as f64; } else { (*o).sum -= *((*o).values).offset(((*o).lv % (*o).period) as isize); (*o).sum += v_0; (*o).sma = (*o).sum / (*o).period as f64; *((*o).values).offset(((*o).lv % (*o).period) as isize) = v_0; (*o).lv += 1; (*o).lv; } r.sma = (*o).sma; } _ => {} } return r; }
sma_result_t sma(enum Action action, ...) { va_list vl; sma_result_t r; sma_obj_t *o; double v; va_start(vl, action); switch(action) { case SMA_NEW: // args: int period r.handle = malloc(sizeof(sma_obj_t)); r.handle->sma = 0.0; r.handle->period = va_arg(vl, int); r.handle->values = malloc(r.handle->period * sizeof(double)); r.handle->lv = 0; r.handle->sum = 0.0; break; case SMA_FREE: // args: sma_obj_t *handle r.handle = va_arg(vl, sma_obj_t *); free(r.handle->values); free(r.handle); r.handle = NULL; break; case SMA_VALUES: // args: sma_obj_t *handle o = va_arg(vl, sma_obj_t *); r.values = o->values; break; case SMA_MEAN: // args: sma_obj_t *handle o = va_arg(vl, sma_obj_t *); r.sma = o->sma; break; case SMA_ADD: // args: sma_obj_t *handle, double value o = va_arg(vl, sma_obj_t *); v = va_arg(vl, double); if ( o->lv < o->period ) { o->values[o->lv++] = v; o->sum += v; o->sma = o->sum / o->lv; } else { o->sum -= o->values[ o->lv % o->period]; o->sum += v; o->sma = o->sum / o->period; o->values[ o->lv % o->period ] = v; o->lv++; } r.sma = o->sma; break; } va_end(vl); return r; }
74
fn main() -> i32 { unsafe { let mut i: i32 = 0; let mut h3: *mut sma_obj_t = (sma(SMA_NEW, 3)).handle; let mut h5: *mut sma_obj_t = (sma(SMA_NEW, 5)).handle; i = 0; while (i as u64) < (::core::mem::size_of::<[f64; 10]>() as u64) .wrapping_div(::core::mem::size_of::<f64>() as u64) { print!( "next number {}, SMA_3 = {}, SMA_5 = {}\n", v[i as usize], (sma(SMA_ADD, h3, v[i as usize])).sma, (sma(SMA_ADD, h5, v[i as usize])).sma ); i += 1; i; } sma(SMA_FREE, h3); sma(SMA_FREE, h5); return 0; } }
int main() { int i; sma_obj_t *h3 = sma(SMA_NEW, 3).handle; sma_obj_t *h5 = sma(SMA_NEW, 5).handle; for(i=0; i < sizeof(v)/sizeof(double) ; i++) { printf("next number %lf, SMA_3 = %lf, SMA_5 = %lf\n", v[i], sma(SMA_ADD, h3, v[i]).sma, sma(SMA_ADD, h5, v[i]).sma); } sma(SMA_FREE, h3); sma(SMA_FREE, h5); return 0; }
75
pub extern "C" fn mapRange(mut a1: f64, mut a2: f64, mut b1: f64, mut b2: f64, mut s: f64) -> f64 { return b1 + (s - a1) * (b2 - b1) / (a2 - a1); }
double mapRange(double a1,double a2,double b1,double b2,double s) { return b1 + (s-a1)*(b2-b1)/(a2-a1); }
76
fn main() -> i32 { let mut i: i32 = 0; unsafe { puts(b"Mapping [0,10] to [-1,0] at intervals of 1:\0" as *const u8 as *const i8); } i = 0; while i <= 10 { print!( "f({}) = {}\n", i, mapRange(0 as f64, 10 as f64, -1i32 as f64, 0 as f64, i as f64) ); i += 1; i; } return 0; }
int main() { int i; puts("Mapping [0,10] to [-1,0] at intervals of 1:"); for(i=0;i<=10;i++) { printf("f(%d) = %g\n",i,mapRange(0,10,-1,0,i)); } return 0; }
77
pub extern "C" fn do_tick(mut d: i32) -> i32 { unsafe { game.have_moved = 0; } do_gravity(d); do_merge(d); do_gravity(d); unsafe { return game.have_moved; } }
int do_tick(int d) { game.have_moved = 0; do_gravity(d); do_merge(d); do_gravity(d); return game.have_moved; }
78
pub extern "C" fn do_newblock() { unsafe { if game.blocks_in_play >= 16 { return; } let mut bn: i32 = rand() % (16 - game.blocks_in_play); let mut pn: i32 = 0; let mut x: i32 = 0; while x < 4 { let mut y: i32 = 0; while y < 4 { if !(game.grid[x as usize][y as usize] != 0) { if pn == bn { game.grid[x as usize][y as usize] = if rand() % 10 != 0 { 1 } else { 2 }; game.blocks_in_play += 1; return; } else { pn += 1; pn; } } y += 1; y; } x += 1; x; } } }
void do_newblock(void) { if (game.blocks_in_play >= 16) return; int bn = rand() % (16 - game.blocks_in_play); int pn = 0; for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { if (game.grid[x][y]) continue; if (pn == bn){ game.grid[x][y] = rand() % 10 ? 1 : 2; game.blocks_in_play += 1; return; } else { ++pn; } } } }
79
pub extern "C" fn do_gravity(mut d: i32) { unsafe { match d { 4 => { let mut break_cond: i32 = 0; while break_cond == 0 { break_cond = 1; let mut x: i32 = 0; while x < 3 { let mut y: i32 = 0; while y < 4 { if game.grid[x as usize][y as usize] == 0 && game.grid[(x + 1i32) as usize][(y + 0i32) as usize] != 0 { game.grid[x as usize][y as usize] = game.grid[(x + 1i32) as usize][(y + 0i32) as usize]; break_cond = 0; game.grid[(x + 1i32) as usize][(y + 0i32) as usize] = break_cond; game.have_moved = 1; } y += 1; } x += 1; } do_draw(); usleep(40000); } } 3 => { let mut break_cond_0: i32 = 0; while break_cond_0 == 0 { break_cond_0 = 1; let mut x_0: i32 = 3; while x_0 > 0 { let mut y_0: i32 = 0; while y_0 < 4 { if game.grid[x_0 as usize][y_0 as usize] == 0 && game.grid[(x_0 + -1i32) as usize][(y_0 + 0i32) as usize] != 0 { game.grid[x_0 as usize][y_0 as usize] = game.grid[(x_0 + -1i32) as usize][(y_0 + 0i32) as usize]; break_cond_0 = 0; game.grid[(x_0 + -1i32) as usize][(y_0 + 0i32) as usize] = break_cond_0; game.have_moved = 1; } y_0 += 1; } x_0 += -1; } do_draw(); usleep(40000); } } 2 => { let mut break_cond_1: i32 = 0; while break_cond_1 == 0 { break_cond_1 = 1; let mut y_1: i32 = 3; while y_1 > 0 { let mut x_1: i32 = 0; while x_1 < 4 { if game.grid[x_1 as usize][y_1 as usize] == 0 && game.grid[(x_1 + 0i32) as usize][(y_1 + -1i32) as usize] != 0 { game.grid[x_1 as usize][y_1 as usize] = game.grid[(x_1 + 0i32) as usize][(y_1 + -1i32) as usize]; break_cond_1 = 0; game.grid[(x_1 + 0i32) as usize][(y_1 + -1i32) as usize] = break_cond_1; game.have_moved = 1; } x_1 += 1; } y_1 += -1; } do_draw(); usleep(40000); } } 1 => { let mut break_cond_2: i32 = 0; while break_cond_2 == 0 { break_cond_2 = 1; let mut y_2: i32 = 0; while y_2 < 3 { let mut x_2: i32 = 0; while x_2 < 4 { if game.grid[x_2 as usize][y_2 as usize] == 0 && game.grid[(x_2 + 0i32) as usize][(y_2 + 1i32) as usize] != 0 { game.grid[x_2 as usize][y_2 as usize] = game.grid[(x_2 + 0i32) as usize][(y_2 + 1i32) as usize]; break_cond_2 = 0; game.grid[(x_2 + 0i32) as usize][(y_2 + 1i32) as usize] = break_cond_2; game.have_moved = 1; } x_2 += 1; } y_2 += 1; } do_draw(); usleep(40000); } } _ => {} }; } }
void do_gravity(int d) { #define GRAVITATE_DIRECTION(_v1, _v2, _xs, _xc, _xi, _ys, _yc, _yi, _x, _y) \ do { \ int break_cond = 0; \ while (!break_cond) { \ break_cond = 1; \ for (int _v1 = _xs; _v1 _xc; _v1 += _xi) { \ for (int _v2 = _ys; _v2 _yc; _v2 += _yi) { \ if (!game.grid[x][y] && game.grid[x + _x][y + _y]) { \ game.grid[x][y] = game.grid[x + _x][y + _y]; \ game.grid[x + _x][y + _y] = break_cond = 0; \ game.have_moved = 1; \ } \ } \ } \ do_draw(); usleep(40000); \ } \ } while (0) switch (d) { case D_LEFT: GRAVITATE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0); break; case D_RIGHT: GRAVITATE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0); break; case D_DOWN: GRAVITATE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1); break; case D_UP: GRAVITATE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1); break; } #undef GRAVITATE_DIRECTION }
80
pub extern "C" fn do_merge(mut d: i32) { unsafe { game.score_last_move = 0; match d { 4 => { let mut x: i32 = 0; while x < 3 { let mut y: i32 = 0; while y < 4 { if game.grid[x as usize][y as usize] != 0 && game.grid[x as usize][y as usize] == game.grid[(x + 1i32) as usize][(y + 0i32) as usize] { game.have_moved = 1; game.grid[x as usize][y as usize] += game.have_moved; let fresh0 = game.blocks_in_play; game.blocks_in_play = game.blocks_in_play - 1; game.grid[(x + 1i32) as usize][(y + 0i32) as usize] = 0 * fresh0; game.score_last_move += values[game.grid[x as usize][y as usize] as usize]; game.total_score += values[game.grid[x as usize][y as usize] as usize]; } y += 1; } x += 1; } } 3 => { let mut x_0: i32 = 3; while x_0 > 0 { let mut y_0: i32 = 0; while y_0 < 4 { if game.grid[x_0 as usize][y_0 as usize] != 0 && game.grid[x_0 as usize][y_0 as usize] == game.grid[(x_0 + -1i32) as usize][(y_0 + 0i32) as usize] { game.have_moved = 1; game.grid[x_0 as usize][y_0 as usize] += game.have_moved; let fresh1 = game.blocks_in_play; game.blocks_in_play = game.blocks_in_play - 1; game.grid[(x_0 + -1i32) as usize][(y_0 + 0i32) as usize] = 0 * fresh1; game.score_last_move += values[game.grid[x_0 as usize][y_0 as usize] as usize]; game.total_score += values[game.grid[x_0 as usize][y_0 as usize] as usize]; } y_0 += 1; } x_0 += -1; } } 2 => { let mut y_1: i32 = 3; while y_1 > 0 { let mut x_1: i32 = 0; while x_1 < 4 { if game.grid[x_1 as usize][y_1 as usize] != 0 && game.grid[x_1 as usize][y_1 as usize] == game.grid[(x_1 + 0i32) as usize][(y_1 + -1i32) as usize] { game.have_moved = 1; game.grid[x_1 as usize][y_1 as usize] += game.have_moved; let fresh2 = game.blocks_in_play; game.blocks_in_play = game.blocks_in_play - 1; game.grid[(x_1 + 0i32) as usize][(y_1 + -1i32) as usize] = 0 * fresh2; game.score_last_move += values[game.grid[x_1 as usize][y_1 as usize] as usize]; game.total_score += values[game.grid[x_1 as usize][y_1 as usize] as usize]; } x_1 += 1; } y_1 += -1; } } 1 => { let mut y_2: i32 = 0; while y_2 < 3 { let mut x_2: i32 = 0; while x_2 < 4 { if game.grid[x_2 as usize][y_2 as usize] != 0 && game.grid[x_2 as usize][y_2 as usize] == game.grid[(x_2 + 0i32) as usize][(y_2 + 1i32) as usize] { game.have_moved = 1; game.grid[x_2 as usize][y_2 as usize] += game.have_moved; let fresh3 = game.blocks_in_play; game.blocks_in_play = game.blocks_in_play - 1; game.grid[(x_2 + 0i32) as usize][(y_2 + 1i32) as usize] = 0 * fresh3; game.score_last_move += values[game.grid[x_2 as usize][y_2 as usize] as usize]; game.total_score += values[game.grid[x_2 as usize][y_2 as usize] as usize]; } x_2 += 1; } y_2 += 1; } } _ => {} }; } }
void do_merge(int d) { /* These macros look pretty scary, but mainly demonstrate some space saving */ #define MERGE_DIRECTION(_v1, _v2, _xs, _xc, _xi, _ys, _yc, _yi, _x, _y) \ do { \ for (int _v1 = _xs; _v1 _xc; _v1 += _xi) { \ for (int _v2 = _ys; _v2 _yc; _v2 += _yi) { \ if (game.grid[x][y] && (game.grid[x][y] == \ game.grid[x + _x][y + _y])) { \ game.grid[x][y] += (game.have_moved = 1); \ game.grid[x + _x][y + _y] = (0 * game.blocks_in_play--);\ game.score_last_move += values[game.grid[x][y]]; \ game.total_score += values[game.grid[x][y]]; \ } \ } \ } \ } while (0) game.score_last_move = 0; switch (d) { case D_LEFT: MERGE_DIRECTION(x, y, 0, < 3, 1, 0, < 4, 1, 1, 0); break; case D_RIGHT: MERGE_DIRECTION(x, y, 3, > 0, -1, 0, < 4, 1, -1, 0); break; case D_DOWN: MERGE_DIRECTION(y, x, 3, > 0, -1, 0, < 4, 1, 0, -1); break; case D_UP: MERGE_DIRECTION(y, x, 0, < 3, 1, 0, < 4, 1, 0, 1); break; } #undef MERGE_DIRECTION }
81
fn main() -> i32 { let mut current_block: u64; unsafe { tcgetattr(0, &mut oldt); newt = oldt; newt.c_lflag &= !(0o2 | 0o10i32) as u32; tcsetattr(0, 0, &mut newt); srand(rust_time(None) as u32); memset( &mut game as *mut gamestate_struct__ as *mut libc::c_void, 0, ::core::mem::size_of::<gamestate_struct__>() as u64, ); } do_newblock(); do_newblock(); do_draw(); unsafe { 's_31: loop { let mut found_valid_key: i32 = 0; let mut direction: i32 = 0; let mut value: i32 = 0; loop { found_valid_key = 1; direction = -1; value = rust_getchar() as i32; match value { 104 | 97 => { direction = 4; } 108 | 100 => { direction = 3; } 106 | 115 => { direction = 2; } 107 | 119 => { direction = 1; } 113 => { current_block = 1947375109854664918; break 's_31; } 27 => { if rust_getchar() as i32 == 91 { value = rust_getchar() as i32; match value { 65 => { direction = 1; } 66 => { direction = 2; } 67 => { direction = 3; } 68 => { direction = 4; } _ => { found_valid_key = 0; } } } } _ => { found_valid_key = 0; } } if !(found_valid_key == 0) { break; } } do_tick(direction); if game.have_moved != 0 { do_newblock(); } do_draw(); match do_check_end_condition() { -1 => { current_block = 267910298023665031; break; } 1 => { current_block = 340875295666714687; break; } 0 | _ => {} } } } match current_block { 267910298023665031 => { print!("You lose!\n"); } 340875295666714687 => { print!("You win!\n"); } _ => {} } unsafe { tcsetattr(0, 0, &mut oldt); } return 0; }
int main(void) { /* Initialize terminal settings */ tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); srand(time(NULL)); memset(&game, 0, sizeof(game)); do_newblock(); do_newblock(); do_draw(); while (1) { int found_valid_key, direction, value; do { found_valid_key = 1; direction = D_INVALID; value = getchar(); switch (value) { case 'h': case 'a': direction = D_LEFT; break; case 'l': case 'd': direction = D_RIGHT; break; case 'j': case 's': direction = D_DOWN; break; case 'k': case 'w': direction = D_UP; break; case 'q': goto game_quit; break; case 27: if (getchar() == 91) { value = getchar(); switch (value) { case 65: direction = D_UP; break; case 66: direction = D_DOWN; break; case 67: direction = D_RIGHT; break; case 68: direction = D_LEFT; break; default: found_valid_key = 0; break; } } break; default: found_valid_key = 0; break; } } while (!found_valid_key); do_tick(direction); if (game.have_moved != 0){ do_newblock(); } do_draw(); switch (do_check_end_condition()) { case -1: goto game_lose; case 1: goto game_win; case 0: break; } } if (0) game_lose: printf("You lose!\n"); goto game_quit; if (0) game_win: printf("You win!\n"); goto game_quit; if (0) game_quit: /* Restore terminal settings */ tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return 0; }
82
pub extern "C" fn do_check_end_condition() -> i32 { let mut ret: i32 = -1; let mut x: i32 = 0; unsafe { while x < 4 { let mut y: i32 = 0; while y < 4 { if values[game.grid[x as usize][y as usize] as usize] == 2048 { return 1; } if game.grid[x as usize][y as usize] == 0 || (x + 1) < 4 && game.grid[x as usize][y as usize] == game.grid[(x + 1i32) as usize][y as usize] || (y + 1) < 4 && game.grid[x as usize][y as usize] == game.grid[x as usize][(y + 1i32) as usize] { ret = 0; } y += 1; y; } x += 1; x; } } return ret; }
int do_check_end_condition(void) { int ret = -1; for (int x = 0; x < 4; ++x) { for (int y = 0; y < 4; ++y) { if (values[game.grid[x][y]] == 2048) return 1; if (!game.grid[x][y] || ((x + 1 < 4) && (game.grid[x][y] == game.grid[x + 1][y])) || ((y + 1 < 4) && (game.grid[x][y] == game.grid[x][y + 1]))) ret = 0; } } return ret; }
83
pub extern "C" fn do_draw() { unsafe { print!("\x1B[2J\x1B[HScore: {}", game.total_score); if game.score_last_move != 0 { print!(" (+{})", game.score_last_move); } } print!("\n"); let mut i: i32 = 0; while i < 25 { print!("-"); i += 1; i; } print!("\n"); let mut y: i32 = 0; unsafe { while y < 4 { print!("|"); let mut x: i32 = 0; while x < 4 { if game.grid[x as usize][y as usize] != 0 { print!( "\x1B[7m\x1B[{0:}m{2:1$} \x1B[0m|", build_str_from_raw_ptr( colors[game.grid[x as usize][y as usize] as usize] as *mut u8 ), 4, values[game.grid[x as usize][y as usize] as usize] ); } else { print!("{1:0$} |", 4, "\0"); } x += 1; x; } print!("\n"); y += 1; y; } } let mut i_0: i32 = 0; while i_0 < 25 { print!("-"); i_0 += 1; i_0; } print!("\n"); }
void do_draw(void) { printf("\033[2J\033[HScore: %ld", game.total_score); if (game.score_last_move) printf(" (+%ld)", game.score_last_move); printf("\n"); for (int i = 0; i < 25; ++i) printf("-"); printf("\n"); for (int y = 0; y < 4; ++y) { printf("|"); for (int x = 0; x < 4; ++x) { if (game.grid[x][y]) printf("\033[7m\033[%sm%*zd \033[0m|", colors[game.grid[x][y]], 4, values[game.grid[x][y]]); else printf("%*s |", 4, ""); } printf("\n"); } for (int i = 0; i < 25; ++i) { printf("-"); } printf("\n"); }
84
pub extern "C" fn ord(mut v: i8) -> i32 { return v as i32 - '0' as i32; }
int ord(char v) { return v-'0'; }
85
pub extern "C" fn printTable(mut tbl: Table, mut fout: *mut FILE, mut colFmts: *mut *const i8) { unsafe { let mut row: i32 = 0; let mut col: i32 = 0; row = 0; while row < (*tbl).n_rows { fprintf(fout, b" \0" as *const u8 as *const i8); col = 0; while col < (*tbl).n_cols { fprintf( fout, *colFmts.offset(col as isize), *(*((*tbl).rows).offset(row as isize)).offset(col as isize), ); col += 1; col; } fprintf(fout, b"\n\0" as *const u8 as *const i8); row += 1; row; } fprintf(fout, b"\n\0" as *const u8 as *const i8); } }
void printTable( Table tbl, FILE *fout, const char *colFmts[]) { int row, col; for (row=0; row<tbl->n_rows; row++) { fprintf(fout, " "); for(col=0; col<tbl->n_cols; col++) { fprintf(fout, colFmts[col], tbl->rows[row][col]); } fprintf(fout, "\n"); } fprintf(fout, "\n"); }
86
pub extern "C" fn CmprRows(mut aa: *const libc::c_void, mut bb: *const libc::c_void) -> i32 { unsafe { let mut rA: *mut String_0 = *(aa as *const *mut String_0); let mut rB: *mut String_0 = *(bb as *const *mut String_0); let mut sortCol: i32 = sortSpec.column; let mut left: String_0 = if sortSpec.reversed != 0 { *rB.offset(sortCol as isize) } else { *rA.offset(sortCol as isize) }; let mut right: String_0 = if sortSpec.reversed != 0 { *rA.offset(sortCol as isize) } else { *rB.offset(sortCol as isize) }; return (sortSpec.compare).expect("non-null function pointer")(left, right); } }
int CmprRows( const void *aa, const void *bb) { String *rA = *(String *const *)aa; String *rB = *(String *const *)bb; int sortCol = sortSpec.column; String left = sortSpec.reversed ? rB[sortCol] : rA[sortCol]; String right = sortSpec.reversed ? rA[sortCol] : rB[sortCol]; return sortSpec.compare( left, right ); }
87
pub unsafe extern "C" fn sortTable(mut tbl: Table, mut argSpec: *const i8, mut args: ...) -> i32 { let mut vl: ::core::ffi::VaListImpl; let mut p: *const i8 = 0 as *const i8; let mut c: i32 = 0; sortSpec.compare = Some(strcmp as unsafe extern "C" fn(*const i8, *const i8) -> i32); sortSpec.column = 0; sortSpec.reversed = 0; vl = args.clone(); if !argSpec.is_null() { p = argSpec; while *p != 0 { match *p as i32 { 111 => { sortSpec.compare = ::core::mem::transmute(vl.arg::<*mut unsafe extern "C" fn( String_0, String_0, ) -> i32>()); } 99 => { c = vl.arg::<i32>(); if 0 <= c && c < (*tbl).n_cols { sortSpec.column = c; } } 114 => { sortSpec.reversed = (0 != vl.arg::<i32>()) as i32; } _ => {} } p = p.offset(1); p; } } qsort( (*tbl).rows as *mut libc::c_void, (*tbl).n_rows as u64, ::core::mem::size_of::<*mut String_0>() as u64, Some(CmprRows as unsafe extern "C" fn(*const libc::c_void, *const libc::c_void) -> i32), ); return 0; }
int sortTable(Table tbl, const char* argSpec,... ) { va_list vl; const char *p; int c; sortSpec.compare = &strcmp; sortSpec.column = 0; sortSpec.reversed = 0; va_start(vl, argSpec); if (argSpec) for (p=argSpec; *p; p++) { switch (*p) { case 'o': sortSpec.compare = va_arg(vl,CompareFctn); break; case 'c': c = va_arg(vl,int); if ( 0<=c && c<tbl->n_cols) sortSpec.column = c; break; case 'r': sortSpec.reversed = (0!=va_arg(vl,int)); break; } } va_end(vl); qsort( tbl->rows, tbl->n_rows, sizeof(String *), CmprRows); return 0; }
88
pub extern "C" fn cmprStrgs(mut s1: String_0, mut s2: String_0) -> i32 { unsafe { let mut p1: *const i8 = s1; let mut p2: *const i8 = s2; let mut mrk1: *const i8 = 0 as *const i8; let mut mrk2: *const i8 = 0 as *const i8; while tolower(*p1 as i32) == tolower(*p2 as i32) && *p1 as i32 != 0 { p1 = p1.offset(1); p1; p2 = p2.offset(1); p2; } if *(*__ctype_b_loc()).offset(*p1 as i32 as isize) as i32 & _ISdigit as i32 != 0 && *(*__ctype_b_loc()).offset(*p2 as i32 as isize) as i32 & _ISdigit as i32 != 0 { let mut v1: i64 = 0; let mut v2: i64 = 0; if *p1 as i32 == '0' as i32 || *p2 as i32 == '0' as i32 { while p1 > s1 { p1 = p1.offset(-1); p1; p2 = p2.offset(-1); p2; if *p1 as i32 != '0' as i32 { break; } } if *(*__ctype_b_loc()).offset(*p1 as i32 as isize) as i32 & _ISdigit as i32 == 0 { p1 = p1.offset(1); p1; p2 = p2.offset(1); p2; } } mrk1 = p1; mrk2 = p2; v1 = 0; while *(*__ctype_b_loc()).offset(*p1 as i32 as isize) as i32 & _ISdigit as i32 != 0 { v1 = 10 * v1 + ord(*p1) as i64; p1 = p1.offset(1); p1; } v2 = 0; while *(*__ctype_b_loc()).offset(*p2 as i32 as isize) as i32 & _ISdigit as i32 != 0 { v2 = 10 * v2 + ord(*p2) as i64; p2 = p2.offset(1); p2; } if v1 == v2 { return (p2.offset_from(mrk2) as i64 - p1.offset_from(mrk1) as i64) as i32; } return (v1 - v2) as i32; } if tolower(*p1 as i32) != tolower(*p2 as i32) { return tolower(*p1 as i32) - tolower(*p2 as i32); } p1 = s1; p2 = s2; while *p1 as i32 == *p2 as i32 && *p1 as i32 != 0 { p1 = p1.offset(1); p1; p2 = p2.offset(1); p2; } return *p1 as i32 - *p2 as i32; } }
int cmprStrgs(String s1, String s2) { const char *p1 = s1; const char *p2 = s2; const char *mrk1, *mrk2; while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++; } if (isdigit(*p1) && isdigit(*p2)) { long v1, v2; if ((*p1 == '0') ||(*p2 == '0')) { while (p1 > s1) { p1--; p2--; if (*p1 != '0') break; } if (!isdigit(*p1)) { p1++; p2++; } } mrk1 = p1; mrk2 = p2; v1 = 0; while(isdigit(*p1)) { v1 = 10*v1+ord(*p1); p1++; } v2 = 0; while(isdigit(*p2)) { v2 = 10*v2+ord(*p2); p2++; } if (v1 == v2) return(p2-mrk2)-(p1-mrk1); return v1 - v2; } if (tolower(*p1) != tolower(*p2)) return (tolower(*p1) - tolower(*p2)); for(p1=s1, p2=s2; (*p1 == *p2) && *p1; p1++, p2++); return (*p1 -*p2); }
89
fn main() -> i32 { let mut colFmts: [*const i8; 3] = [ b" %-5.5s\0" as *const u8 as *const i8, b" %-5.5s\0" as *const u8 as *const i8, b" %-9.9s\0" as *const u8 as *const i8, ]; let mut r1: [String_0; 3] = [ b"a101\0" as *const u8 as *const i8, b"red\0" as *const u8 as *const i8, b"Java\0" as *const u8 as *const i8, ]; let mut r2: [String_0; 3] = [ b"ab40\0" as *const u8 as *const i8, b"gren\0" as *const u8 as *const i8, b"Smalltalk\0" as *const u8 as *const i8, ]; let mut r3: [String_0; 3] = [ b"ab9\0" as *const u8 as *const i8, b"blue\0" as *const u8 as *const i8, b"Fortran\0" as *const u8 as *const i8, ]; let mut r4: [String_0; 3] = [ b"ab09\0" as *const u8 as *const i8, b"ylow\0" as *const u8 as *const i8, b"Python\0" as *const u8 as *const i8, ]; let mut r5: [String_0; 3] = [ b"ab1a\0" as *const u8 as *const i8, b"blak\0" as *const u8 as *const i8, b"Factor\0" as *const u8 as *const i8, ]; let mut r6: [String_0; 3] = [ b"ab1b\0" as *const u8 as *const i8, b"brwn\0" as *const u8 as *const i8, b"C Sharp\0" as *const u8 as *const i8, ]; let mut r7: [String_0; 3] = [ b"Ab1b\0" as *const u8 as *const i8, b"pink\0" as *const u8 as *const i8, b"Ruby\0" as *const u8 as *const i8, ]; let mut r8: [String_0; 3] = [ b"ab1\0" as *const u8 as *const i8, b"orng\0" as *const u8 as *const i8, b"Scheme\0" as *const u8 as *const i8, ]; let mut rows: [*mut String_0; 8] = [ r1.as_mut_ptr(), r2.as_mut_ptr(), r3.as_mut_ptr(), r4.as_mut_ptr(), r5.as_mut_ptr(), r6.as_mut_ptr(), r7.as_mut_ptr(), r8.as_mut_ptr(), ]; let mut table: sTable = sTable { rows: 0 as *mut *mut String_0, n_rows: 0, n_cols: 0, }; table.rows = rows.as_mut_ptr(); table.n_rows = 8; table.n_cols = 3; unsafe { sortTable(&mut table as *mut sTable, b"\0" as *const u8 as *const i8); } print!("sort on col 0, ascending\n"); unsafe { printTable(&mut table, stdout, colFmts.as_mut_ptr()); sortTable( &mut table as *mut sTable, b"ro\0" as *const u8 as *const i8, 1, Some(cmprStrgs as unsafe extern "C" fn(String_0, String_0) -> i32), ); } print!("sort on col 0, reverse.special\n"); unsafe { printTable(&mut table, stdout, colFmts.as_mut_ptr()); sortTable( &mut table as *mut sTable, b"c\0" as *const u8 as *const i8, 1, ); } print!("sort on col 1, ascending\n"); unsafe { printTable(&mut table, stdout, colFmts.as_mut_ptr()); sortTable( &mut table as *mut sTable, b"cr\0" as *const u8 as *const i8, 2, 1, ); } print!("sort on col 2, reverse\n"); unsafe { printTable(&mut table, stdout, colFmts.as_mut_ptr()); } return 0; }
int main() { const char *colFmts[] = {" %-5.5s"," %-5.5s"," %-9.9s"}; String r1[] = { "a101", "red", "Java" }; String r2[] = { "ab40", "gren", "Smalltalk" }; String r3[] = { "ab9", "blue", "Fortran" }; String r4[] = { "ab09", "ylow", "Python" }; String r5[] = { "ab1a", "blak", "Factor" }; String r6[] = { "ab1b", "brwn", "C Sharp" }; String r7[] = { "Ab1b", "pink", "Ruby" }; String r8[] = { "ab1", "orng", "Scheme" }; String *rows[] = { r1, r2, r3, r4, r5, r6, r7, r8 }; struct sTable table; table.rows = rows; table.n_rows = 8; table.n_cols = 3; sortTable(&table, ""); printf("sort on col 0, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "ro", 1, &cmprStrgs); printf("sort on col 0, reverse.special\n"); printTable(&table, stdout, colFmts); sortTable(&table, "c", 1); printf("sort on col 1, ascending\n"); printTable(&table, stdout, colFmts); sortTable(&table, "cr", 2, 1); printf("sort on col 2, reverse\n"); printTable(&table, stdout, colFmts); return 0; }
90
fn main(mut argc: i32, mut argv: *mut *mut i8) -> i32 { unsafe { let mut filename: *const i8 = b"sierpinski_arrowhead.svg\0" as *const u8 as *const i8; if argc == 2 { filename = *argv.offset(1 as isize); } let mut out: *mut FILE = fopen(filename, b"w\0" as *const u8 as *const i8); if out.is_null() { perror(filename); return 1; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return 0; } }
int main(int argc, char** argv) { const char* filename = "sierpinski_arrowhead.svg"; if (argc == 2) filename = argv[1]; FILE* out = fopen(filename, "w"); if (!out) { perror(filename); return EXIT_FAILURE; } write_sierpinski_arrowhead(out, 600, 8); fclose(out); return EXIT_SUCCESS; }
91
pub extern "C" fn write_sierpinski_arrowhead(mut out: *mut FILE, mut size: i32, mut order: i32) { unsafe { let margin: f64 = 20.0f64; let side: f64 = size as f64 - 2.0f64 * margin; let mut cursor: cursor_t = cursor_t { x: 0., y: 0., angle: 0, }; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5f64 * size as f64 + 0.25f64 * sqrt(3 as f64) * side; if order & 1 != 0 { turn(&mut cursor, -60); } fprintf( out, b"<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n\0" as *const u8 as *const i8, size, size, ); fprintf( out, b"<rect width='100%%' height='100%%' fill='white'/>\n\0" as *const u8 as *const i8, ); fprintf( out, b"<path stroke-width='1' stroke='black' fill='none' d='\0" as *const u8 as *const i8, ); fprintf( out, b"M%g,%g\n\0" as *const u8 as *const i8, cursor.x, cursor.y, ); curve(out, order, side, &mut cursor, 60); fprintf(out, b"'/>\n</svg>\n\0" as *const u8 as *const i8); } }
void write_sierpinski_arrowhead(FILE* out, int size, int order) { const double margin = 20.0; const double side = size - 2.0 * margin; cursor_t cursor; cursor.angle = 0; cursor.x = margin; cursor.y = 0.5 * size + 0.25 * sqrt(3) * side; if ((order & 1) != 0) turn(&cursor, -60); fprintf(out, "<svg xmlns='http://www.w3.org/2000/svg' width='%d' height='%d'>\n", size, size); fprintf(out, "<rect width='100%%' height='100%%' fill='white'/>\n"); fprintf(out, "<path stroke-width='1' stroke='black' fill='none' d='"); fprintf(out, "M%g,%g\n", cursor.x, cursor.y); curve(out, order, side, &cursor, 60); fprintf(out, "'/>\n</svg>\n"); }
92
pub extern "C" fn curve( mut out: *mut FILE, mut order: i32, mut length: f64, mut cursor: *mut cursor_t, mut angle: i32, ) { unsafe { if order == 0 { draw_line(out, cursor, length); } else { curve(out, order - 1, length / 2 as f64, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length / 2 as f64, cursor, angle); turn(cursor, angle); curve(out, order - 1, length / 2 as f64, cursor, -angle); }; } }
void curve(FILE* out, int order, double length, cursor_t* cursor, int angle) { if (order == 0) { draw_line(out, cursor, length); } else { curve(out, order - 1, length/2, cursor, -angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, angle); turn(cursor, angle); curve(out, order - 1, length/2, cursor, -angle); } }
93
pub extern "C" fn turn(mut cursor: *mut cursor_t, mut angle: i32) { unsafe { (*cursor).angle = ((*cursor).angle + angle) % 360; } }
void turn(cursor_t* cursor, int angle) { cursor->angle = (cursor->angle + angle) % 360; }
94
pub extern "C" fn draw_line(mut out: *mut FILE, mut cursor: *mut cursor_t, mut length: f64) { unsafe { let mut theta: f64 = 3.14159265358979323846f64 * (*cursor).angle as f64 / 180.0f64; (*cursor).x += length * cos(theta); (*cursor).y += length * sin(theta); fprintf( out, b"L%g,%g\n\0" as *const u8 as *const i8, (*cursor).x, (*cursor).y, ); } }
void draw_line(FILE* out, cursor_t* cursor, double length) { double theta = (M_PI * cursor->angle)/180.0; cursor->x += length * cos(theta); cursor->y += length * sin(theta); fprintf(out, "L%g,%g\n", cursor->x, cursor->y); }
95
fn main() -> i32 { let mut p1: i32 = 0; p1 = 2; while p1 < 62 { carmichael3(p1); p1 += 1; p1; } return 0; }
int main(void) { int p1; for (p1 = 2; p1 < 62; ++p1) carmichael3(p1); return 0; }
96
pub extern "C" fn is_prime(mut n: u32) -> i32 { if n <= 3 { return (n > 1) as i32; } else if n.wrapping_rem(2) == 0 || n.wrapping_rem(3) == 0 { return 0; } else { let mut i: u32 = 0; i = 5; while i.wrapping_mul(i) <= n { if n.wrapping_rem(i) == 0 || n.wrapping_rem(i.wrapping_add(2)) == 0 { return 0; } i = i.wrapping_add(6); } return 1; }; }
int is_prime(unsigned int n) { if (n <= 3) { return n > 1; } else if (!(n % 2) || !(n % 3)) { return 0; } else { unsigned int i; for (i = 5; i*i <= n; i += 6) if (!(n % i) || !(n % (i + 2))) return 0; return 1; } }
97
pub extern "C" fn carmichael3(mut p1: i32) { if is_prime(p1 as u32) == 0 { return; } let mut h3: i32 = 0; let mut d: i32 = 0; let mut p2: i32 = 0; let mut p3: i32 = 0; h3 = 1; while h3 < p1 { d = 1; while d < h3 + p1 { if (h3 + p1) * (p1 - 1) % d == 0 && (-p1 * p1 % h3 + h3) % h3 == d % h3 { p2 = 1 + (p1 - 1) * (h3 + p1) / d; if !(is_prime(p2 as u32) == 0) { p3 = 1 + p1 * p2 / h3; if !(is_prime(p3 as u32) == 0 || p2 * p3 % (p1 - 1) != 1) { print!("{} {} {}\n", p1, p2, p3); } } } d += 1; d; } h3 += 1; h3; } }
void carmichael3(int p1) { if (!is_prime(p1)) return; int h3, d, p2, p3; for (h3 = 1; h3 < p1; ++h3) { for (d = 1; d < h3 + p1; ++d) { if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { p2 = 1 + ((p1 - 1) * (h3 + p1)/d); if (!is_prime(p2)) continue; p3 = 1 + (p1 * p2 / h3); if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; printf("%d %d %d\n", p1, p2, p3); } } } }
98
pub extern "C" fn myopenimage(mut in_0: *const i8) -> i32 { unsafe { static mut handle: i32 = 0; fprintf( stderr, b"internal openimage opens %s...\n\0" as *const u8 as *const i8, in_0, ); let fresh0 = handle; handle = handle + 1; return fresh0; } }
int myopenimage(const char *in) { static int handle=0; fprintf(stderr, "internal openimage opens %s...\n", in); return handle++; }
99