]> git.proxmox.com Git - rustc.git/blob - src/test/run-pass/variadic-ffi.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / test / run-pass / variadic-ffi.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 #![feature(libc, std_misc)]
13
14 extern crate libc;
15
16 use std::ffi::{CStr, CString};
17 use libc::{c_char, c_int};
18
19
20 extern {
21 fn sprintf(s: *mut c_char, format: *const c_char, ...) -> c_int;
22 }
23
24 unsafe fn check<T, F>(expected: &str, f: F) where F: FnOnce(*mut c_char) -> T {
25 let mut x = [0 as c_char; 50];
26 f(&mut x[0] as *mut c_char);
27 assert_eq!(expected.as_bytes(), CStr::from_ptr(x.as_ptr()).to_bytes());
28 }
29
30 pub fn main() {
31
32 unsafe {
33 // Call with just the named parameter
34 let c = CString::new(&b"Hello World\n"[..]).unwrap();
35 check("Hello World\n", |s| sprintf(s, c.as_ptr()));
36
37 // Call with variable number of arguments
38 let c = CString::new(&b"%d %f %c %s\n"[..]).unwrap();
39 check("42 42.500000 a %d %f %c %s\n\n", |s| {
40 sprintf(s, c.as_ptr(), 42, 42.5f64, 'a' as c_int, c.as_ptr());
41 });
42
43 // Make a function pointer
44 let x: unsafe extern fn(*mut c_char, *const c_char, ...) -> c_int = sprintf;
45
46 // A function that takes a function pointer
47 unsafe fn call(p: unsafe extern fn(*mut c_char, *const c_char, ...) -> c_int) {
48 // Call with just the named parameter
49 let c = CString::new(&b"Hello World\n"[..]).unwrap();
50 check("Hello World\n", |s| sprintf(s, c.as_ptr()));
51
52 // Call with variable number of arguments
53 let c = CString::new(&b"%d %f %c %s\n"[..]).unwrap();
54 check("42 42.500000 a %d %f %c %s\n\n", |s| {
55 sprintf(s, c.as_ptr(), 42, 42.5f64, 'a' as c_int, c.as_ptr());
56 });
57 }
58
59 // Pass sprintf directly
60 call(sprintf);
61
62 // Pass sprintf indirectly
63 call(x);
64 }
65
66 }