shoot, this was missing from earlier commits. lost some state.

This commit is contained in:
bunnie 2022-03-07 14:00:19 +08:00
parent 54e491840d
commit b464c8e661
12 changed files with 2687 additions and 0 deletions

View file

@ -0,0 +1,24 @@
[package]
name = "ffi-test"
version = "0.1.0"
authors = ["bunnie <bunnie@kosagi.com>"]
edition = "2018"
description = "FFI test integration"
# Dependency policy: fully specify dependencies to the minor version number
[dependencies]
xous = { path = "../../xous-rs" }
log-server = { path = "../log-server" }
ticktimer-server = { path = "../ticktimer-server" }
xous-names = { path = "../xous-names" }
log = "0.4.14"
num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
susres = {path = "../susres"}
ffi-sys = {path = "sys"}
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}
[features]
default = []

View file

@ -0,0 +1,7 @@
pub(crate) const SERVER_NAME_FFITEST: &str = "_FfiTest Server_";
#[allow(dead_code)]
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
pub(crate) enum Opcode {
Quit
}

View file

@ -0,0 +1,132 @@
#![cfg_attr(target_os = "none", no_std)]
#![allow(nonstandard_style)]
pub type c_char = i8;
pub type c_schar = i8;
pub type c_uchar = u8;
pub type c_short = i16;
pub type c_ushort = u16;
pub type c_int = i32;
pub type c_uint = u32;
pub type c_long = i32;
pub type c_ulong = u32;
pub type c_longlong = i64;
pub type c_ulonglong = u64;
pub type c_float = f32;
pub type c_double = f64;
pub type c_void = core::ffi::c_void;
extern "C" {
pub fn add_one(a: i32) -> i32;
}
extern "C" {
pub fn malloc_test() -> i32;
}
static mut PUTC_BUF: Vec::<u8> = Vec::new();
#[export_name = "libc_putchar"]
pub unsafe extern "C" fn libc_putchar(
c: c_char,
) {
let char = c as u8;
if char != 0xa && char != 0xd {
PUTC_BUF.push(char);
} else {
let s = String::from_utf8_lossy(&PUTC_BUF);
log::info!("ffi-test: {}", s);
PUTC_BUF.clear();
}
}
static mut C_HEAP: Vec::<Vec::<u8>> = Vec::new();
#[export_name = "malloc"]
pub unsafe extern "C" fn malloc(
size: c_uint
) -> *mut c_void {
// note: we might need to use `Pin` to keep the data from moving around in the heap, if we see weird behavior
// happening
let checked_size = if size == 0 {
1 // at least 1 element so we can get a pointer to pass back
} else {
size
};
let mut alloc: Vec::<u8> = Vec::with_capacity(checked_size as usize);
for _ in 0..checked_size {
alloc.push(0);
}
let ptr = alloc.as_mut_ptr();
// store a reference to the allocated vector, under the theory that this keeps it from going out of scope
C_HEAP.push(alloc);
log::info!("allocated: {:x}({})#{}", ptr as usize, size, C_HEAP.len());
ptr as *mut c_void
}
#[export_name = "free"]
pub unsafe extern "C" fn free(
ptr: *mut c_void
) {
let mut region_index: Option<usize> = None;
for (index, region) in C_HEAP.iter().enumerate() {
if region.as_ptr() as usize == ptr as usize {
region_index = Some(index);
break;
}
}
match region_index {
Some(index) => {
let mut removed = C_HEAP.remove(index);
log::info!("free success: {:x}({})#{}", ptr as usize, removed.len(), C_HEAP.len());
removed.clear();
}
None => {
log::info!("free failed, debug! Requested free: {:x}", ptr as usize);
for region in C_HEAP.iter() {
log::info!(" {:x}({})", region.as_ptr() as usize, region.len());
}
}
}
}
#[export_name = "realloc"]
pub unsafe extern "C" fn realloc(
ptr: *mut c_void,
size: c_uint
) -> *mut c_void {
let mut region_index: Option<usize> = None;
for (index, region) in C_HEAP.iter().enumerate() {
if region.as_ptr() as usize == ptr as usize {
region_index = Some(index);
break;
}
}
match region_index {
Some(index) => {
log::info!("realloc/free success: {:x}", ptr as usize);
let mut old = C_HEAP.remove(index);
old.clear();
let checked_size = if size == 0 {
1 // at least 1 element so we have a pointer we can pass back
} else {
size
};
let mut alloc: Vec::<u8> = Vec::with_capacity(checked_size as usize);
let ret_ptr = alloc.as_mut_ptr();
for (&src, dst) in old.iter().zip(alloc.iter_mut()) {
*dst = src;
}
C_HEAP.push(alloc);
log::info!("realloc/allocated: {:x}", ret_ptr as usize);
ret_ptr as *mut c_void
}
None => {
log::info!("realloc failed, debug! Requested realloc: {:x}({})", ptr as usize, size);
for region in C_HEAP.iter() {
log::info!(" {:x}({})", region.as_ptr() as usize, region.len());
}
return ::core::ptr::null::<c_void>() as *mut c_void
}
}
}

View file

@ -0,0 +1,33 @@
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use xous::{CID, send_message};
use num_traits::ToPrimitive;
pub struct FfiTest {
conn: CID,
}
impl FfiTest {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_FFITEST).expect("Can't connect to FfiTest server");
Ok(FfiTest {
conn
})
}
}
use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for FfiTest {
fn drop(&mut self) {
// the connection to the server side must be reference counted, so that multiple instances of this object within
// a single process do not end up de-allocating the CID on other threads before they go out of scope.
// Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object".
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();}
}
// if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance),
// de-allocate those items here. They don't need a reference count because they are object-specific
}
}

View file

@ -0,0 +1,64 @@
#![cfg_attr(target_os = "none", no_std)]
#![cfg_attr(target_os = "none", no_main)]
extern crate ffi_sys;
mod api;
use api::*;
pub mod bindings;
pub use bindings::*;
use num_traits::FromPrimitive;
use utralib::utra::ticktimer;
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Trace);
log::info!("my PID is {}", xous::process::id());
log::info!("creating xns");
let xns = xous_names::XousNames::new().unwrap();
let mut a = 0;
for _ in 0..5 {
a = unsafe{add_one(a)};
log::info!("ffi test: {}", a);
}
log::info!("malloc test result: {}", unsafe{malloc_test()});
log::info!("registering with xns");
let ffitest_sid = xns.register_name(api::SERVER_NAME_FFITEST, None).expect("can't register server");
log::trace!("registered with NS -- {:?}", ffitest_sid);
// spawn a small thread that keeps the watchdog timer from firing and lets us know other things didn't crash
std::thread::spawn({
move || {
let tt = ticktimer_server::Ticktimer::new().unwrap();
let mut state = 0;
loop {
tt.sleep_ms(2500).unwrap();
log::info!("keepalive {}", state);
state += 1;
}
}
});
loop {
let msg = xous::receive_message(ffitest_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::Quit) => {
break
}
_ => {
log::info!("couldn't convert opcode {:?}", msg);
}
}
}
// clean up our program
log::trace!("main loop exit, destroying servers");
xns.unregister_server(ffitest_sid).unwrap();
xous::destroy_server(ffitest_sid).unwrap();
log::trace!("quitting");
xous::terminate_process(0)
}

View file

@ -0,0 +1,12 @@
[package]
name = "ffi-sys"
version = "0.1.0"
authors = ["bunnie <bunnie@kosagi.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[build-dependencies]
cc = "1.0"

View file

@ -0,0 +1,40 @@
extern crate cc;
use std::env::set_var;
fn main() {
set_var("CC", "riscv64-unknown-elf-gcc"); // set the compiler to what's installed on the system
let espeak_srcs = vec![
"ffi/ffi.c",
"ffi/libc.c",
"ffi/scanf.c",
];
let espeak_includes = vec![
"./",
// "espeak-ng/src",
// "espeak-ng/src/include/compat",
// "espeak-ng/src/include/espeak",
// "espeak-ng/src/include/espeak-ng",
// "espeak-ng/src/ucd-tools/src/include",
// "espeak-ng/src/include",
];
let mut base_config = cc::Build::new();
base_config.target("riscv32imac-unknown-none-elf");
for inc in espeak_includes {
base_config.include(inc);
}
base_config.include("C:\\Users\\bunnie\\riscv64\\riscv64-unknown-elf\\include");
base_config.include("C:\\Users\\bunnie\\riscv64\\riscv64-unknown-elf\\include\\sys");
base_config.include("C:\\Users\\bunnie\\riscv64\\riscv64-unknown-elf\\include\\machine");
base_config.include("C:\\Users\\bunnie\\riscv64\\riscv64-unknown-elf\\include\\bits");
for src in espeak_srcs {
base_config.file(src);
}
base_config.define("XOUS", None);
base_config.define("NO_STD", None);
base_config.compile("libffi.a");
}

View file

@ -0,0 +1,61 @@
#include <stdio.h>
#include "libc.h"
int add_one(int a) {
printf("ffi adding one to %d\n\r", a);
return a + 1;
}
/* returns an array of arrays of char*, all of which NULL */
char ***alloc_matrix(unsigned rows, unsigned columns) {
char ***matrix = malloc(rows * sizeof(char **));
unsigned row = 0;
unsigned column = 0;
if (!matrix) return NULL;
for (row = 0; row < rows; row++) {
matrix[row] = calloc(columns, sizeof(char *));
if (!matrix[row]) return NULL;
for (column = 0; column < columns; column++) {
matrix[row][column] = NULL;
}
}
return matrix;
}
/* deallocates an array of arrays of char*, calling free() on each */
void free_matrix(char ***matrix, unsigned rows, unsigned columns) {
unsigned row = 0;
unsigned column = 0;
for (row = 0; row < rows; row++) {
for (column = 0; column < columns; column++) {
printf("column %d row %d\n", column, row);
free(matrix[row][column]);
}
free(matrix[row]);
}
free(matrix);
}
int malloc_test() {
int i;
int randomnumber;
int size = 32;
void *p[size];
for (i = 0; i < size; i++) {
randomnumber = rand() % 10;
p[i] = malloc(32 * 32 * randomnumber);
}
for (i = size-1; i >= 0; i--) {
free(p[i]);
}
/*
int x = 6;
char *** matrix = alloc_matrix(x, x);
if (matrix == NULL) return 1;
free_matrix(matrix, x, x);
*/
return (0);
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,49 @@
#include <stdint.h>
#include <stddef.h>
wchar_t *wcschr(const wchar_t *s, wchar_t c);
size_t wcslen(const wchar_t *s);
char *strstr(const char *s, const char *find);
char* strcpy(char *, const char *);
char* strchr(const char *, int);
int strcmp(const char *, const char *);
char* strcat(char *, const char *);
char* strdup(const char *);
char* strncpy(char *, const char *, size_t);
int atoi(const char *);
int memcmp(const void *, const void *, size_t);
void * memcpy (void *dest, const void *src, size_t len);
void * memset (void *dest, int val, size_t len);
size_t strlen(const char *);
#define sprintf sprintf_
int sprintf_(char* buffer, const char* format, ...);
#define snprintf snprintf_
int snprintf_(char* buffer, size_t count, const char* format, ...);
#define printf printf_
int printf_(const char* format, ...);
char *strtok(char *s, const char *delim);
int sscanf(const char *, const char *, ...);
char *strtok_r(char *s, const char *delim, char **last);
intmax_t strtoimax(const char *nptr, char **endptr, int base);
unsigned long strtoul(const char *nptr, char **endptr, int base);
long strtol(const char *nptr, char **endptr, int base);
void bcopy(const void *src0, void *dst0, size_t length);
// this is a lie, we don't have an errno, but we always return...something.
int* __errno(void);
extern void* malloc(size_t);
void* calloc(size_t, size_t);
extern void* realloc(void *, size_t);
extern void free(void *);
extern void libc_putchar(char c);
void _putchar(char c);
#define RAND_MAX 0x7fffffff
long rand(void);

View file

@ -0,0 +1,578 @@
#include "libc.h"
#include <stddef.h>
#include <sys/cdefs.h>
#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include <sys/param.h>
#define BUF 32 /* Maximum length of numeric string. */
/*
* Flags used during conversion.
*/
#define LONG 0x01 /* l: long or double */
#define SHORT 0x04 /* h: short */
#define SUPPRESS 0x08 /* *: suppress assignment */
#define POINTER 0x10 /* p: void * (as hex) */
#define NOSKIP 0x20 /* [ or c: do not skip blanks */
#define LONGLONG 0x400 /* ll: long long (+ deprecated q: quad) */
#define SHORTSHORT 0x4000 /* hh: char */
#define UNSIGNED 0x8000 /* %[oupxX] conversions */
/*
* The following are used in numeric conversions only:
* SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point;
* SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral.
*/
#define SIGNOK 0x40 /* +/- is (still) legal */
#define NDIGITS 0x80 /* no digits detected */
#define DPTOK 0x100 /* (float) decimal point is still legal */
#define EXPOK 0x200 /* (float) exponent (e+3, etc) still legal */
#define PFXOK 0x100 /* 0x prefix is (still) legal */
#define NZDIGITS 0x200 /* no zero digits detected */
/*
* Conversion types.
*/
#define CT_CHAR 0 /* %c conversion */
#define CT_CCL 1 /* %[...] conversion */
#define CT_STRING 2 /* %s conversion */
#define CT_INT 3 /* %[dioupxX] conversion */
static const unsigned char *__sccl(char *, const unsigned char *);
int vsscanf(const char *inp, char const *fmt0, va_list ap);
int
sscanf(const char *ibuf, const char *fmt, ...)
{
va_list ap;
int ret;
va_start(ap, fmt);
ret = vsscanf(ibuf, fmt, ap);
va_end(ap);
return(ret);
}
int
vsscanf(const char *inp, char const *fmt0, va_list ap)
{
int inr;
const unsigned char *fmt = (const unsigned char *)fmt0;
int c; /* character from format, or conversion */
size_t width; /* field width, or 0 */
char *p; /* points into all kinds of strings */
int n; /* handy integer */
int flags; /* flags as defined above */
char *p0; /* saves original value of p when necessary */
int nassigned; /* number of fields assigned */
int nconversions; /* number of conversions */
int nread; /* number of characters consumed from fp */
int base; /* base argument to conversion function */
char ccltab[256]; /* character class table for %[...] */
char buf[BUF]; /* buffer for numeric conversions */
/* `basefix' is used to avoid `if' tests in the integer scanner */
static short basefix[17] =
{ 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
inr = strlen(inp);
nassigned = 0;
nconversions = 0;
nread = 0;
base = 0; /* XXX just to keep gcc happy */
for (;;) {
c = *fmt++;
if (c == 0)
return (nassigned);
if (isspace(c)) {
while (inr > 0 && isspace(*inp))
nread++, inr--, inp++;
continue;
}
if (c != '%')
goto literal;
width = 0;
flags = 0;
/*
* switch on the format. continue if done;
* break once format type is derived.
*/
again: c = *fmt++;
switch (c) {
case '%':
literal:
if (inr <= 0)
goto input_failure;
if (*inp != c)
goto match_failure;
inr--, inp++;
nread++;
continue;
case '*':
flags |= SUPPRESS;
goto again;
case 'l':
if (flags & LONG) {
flags &= ~LONG;
flags |= LONGLONG;
} else
flags |= LONG;
goto again;
case 'q':
flags |= LONGLONG; /* not quite */
goto again;
case 'h':
if (flags & SHORT) {
flags &= ~SHORT;
flags |= SHORTSHORT;
} else
flags |= SHORT;
goto again;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
width = width * 10 + c - '0';
goto again;
/*
* Conversions.
*/
case 'd':
c = CT_INT;
base = 10;
break;
case 'i':
c = CT_INT;
base = 0;
break;
case 'o':
c = CT_INT;
flags |= UNSIGNED;
base = 8;
break;
case 'u':
c = CT_INT;
flags |= UNSIGNED;
base = 10;
break;
case 'X':
case 'x':
flags |= PFXOK; /* enable 0x prefixing */
c = CT_INT;
flags |= UNSIGNED;
base = 16;
break;
case 's':
c = CT_STRING;
break;
case '[':
fmt = __sccl(ccltab, fmt);
flags |= NOSKIP;
c = CT_CCL;
break;
case 'c':
flags |= NOSKIP;
c = CT_CHAR;
break;
case 'p': /* pointer format is like hex */
flags |= POINTER | PFXOK;
c = CT_INT;
flags |= UNSIGNED;
base = 16;
break;
}
/*
* We have a conversion that requires input.
*/
if (inr <= 0)
goto input_failure;
/*
* Consume leading white space, except for formats
* that suppress this.
*/
if ((flags & NOSKIP) == 0) {
while (isspace(*inp)) {
nread++;
if (--inr > 0)
inp++;
else
goto input_failure;
}
/*
* Note that there is at least one character in
* the buffer, so conversions that do not set NOSKIP
* can no longer result in an input failure.
*/
}
/*
* Do the conversion.
*/
switch (c) {
case CT_CHAR:
/* scan arbitrary characters (sets NOSKIP) */
if (width == 0)
width = 1;
if (flags & SUPPRESS) {
size_t sum = 0;
for (;;) {
if ((n = inr) < (int)width) {
sum += n;
width -= n;
inp += n;
if (sum == 0)
goto input_failure;
break;
} else {
sum += width;
inr -= width;
inp += width;
break;
}
}
nread += sum;
} else {
bcopy(inp, va_arg(ap, char *), width);
inr -= width;
inp += width;
nread += width;
nassigned++;
}
nconversions++;
break;
case CT_CCL:
/* scan a (nonempty) character class (sets NOSKIP) */
if (width == 0)
width = (size_t)~0; /* `infinity' */
/* take only those things in the class */
if (flags & SUPPRESS) {
n = 0;
while (ccltab[(unsigned char)*inp]) {
n++, inr--, inp++;
if (--width == 0)
break;
if (inr <= 0) {
if (n == 0)
goto input_failure;
break;
}
}
if (n == 0)
goto match_failure;
} else {
p0 = p = va_arg(ap, char *);
while (ccltab[(unsigned char)*inp]) {
inr--;
*p++ = *inp++;
if (--width == 0)
break;
if (inr <= 0) {
if (p == p0)
goto input_failure;
break;
}
}
n = p - p0;
if (n == 0)
goto match_failure;
*p = 0;
nassigned++;
}
nread += n;
nconversions++;
break;
case CT_STRING:
/* like CCL, but zero-length string OK, & no NOSKIP */
if (width == 0)
width = (size_t)~0;
if (flags & SUPPRESS) {
n = 0;
while (!isspace(*inp)) {
n++, inr--, inp++;
if (--width == 0)
break;
if (inr <= 0)
break;
}
nread += n;
} else {
p0 = p = va_arg(ap, char *);
while (!isspace(*inp)) {
inr--;
*p++ = *inp++;
if (--width == 0)
break;
if (inr <= 0)
break;
}
*p = 0;
nread += p - p0;
nassigned++;
}
nconversions++;
continue;
case CT_INT:
/* scan an integer as if by the conversion function */
#ifdef hardway
if (width == 0 || width > sizeof(buf) - 1)
width = sizeof(buf) - 1;
#else
/* size_t is unsigned, hence this optimisation */
if (--width > sizeof(buf) - 2)
width = sizeof(buf) - 2;
width++;
#endif
flags |= SIGNOK | NDIGITS | NZDIGITS;
for (p = buf; width; width--) {
c = *inp;
/*
* Switch on the character; `goto ok'
* if we accept it as a part of number.
*/
switch (c) {
/*
* The digit 0 is always legal, but is
* special. For %i conversions, if no
* digits (zero or nonzero) have been
* scanned (only signs), we will have
* base==0. In that case, we should set
* it to 8 and enable 0x prefixing.
* Also, if we have not scanned zero digits
* before this, do not turn off prefixing
* (someone else will turn it off if we
* have scanned any nonzero digits).
*/
case '0':
if (base == 0) {
base = 8;
flags |= PFXOK;
}
if (flags & NZDIGITS)
flags &= ~(SIGNOK|NZDIGITS|NDIGITS);
else
flags &= ~(SIGNOK|PFXOK|NDIGITS);
goto ok;
/* 1 through 7 always legal */
case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
base = basefix[base];
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* digits 8 and 9 ok iff decimal or hex */
case '8': case '9':
base = basefix[base];
if (base <= 8)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* letters ok iff hex */
case 'A': case 'B': case 'C':
case 'D': case 'E': case 'F':
case 'a': case 'b': case 'c':
case 'd': case 'e': case 'f':
/* no need to fix base here */
if (base <= 10)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* sign ok only as first character */
case '+': case '-':
if (flags & SIGNOK) {
flags &= ~SIGNOK;
goto ok;
}
break;
/* x ok iff flag still set & 2nd char */
case 'x': case 'X':
if (flags & PFXOK && p == buf + 1) {
base = 16; /* if %i */
flags &= ~PFXOK;
goto ok;
}
break;
}
/*
* If we got here, c is not a legal character
* for a number. Stop accumulating digits.
*/
break;
ok:
/*
* c is legal: store it and look at the next.
*/
*p++ = c;
if (--inr > 0)
inp++;
else
break; /* end of input */
}
/*
* If we had only a sign, it is no good; push
* back the sign. If the number ends in `x',
* it was [sign] '0' 'x', so push back the x
* and treat it as [sign] '0'.
*/
if (flags & NDIGITS) {
if (p > buf) {
inp--;
inr++;
}
goto match_failure;
}
c = ((unsigned char *)p)[-1];
if (c == 'x' || c == 'X') {
--p;
inp--;
inr++;
}
if ((flags & SUPPRESS) == 0) {
unsigned long res;
*p = 0;
if ((flags & UNSIGNED) == 0)
res = strtol(buf, (char **)NULL, base);
else
res = strtoul(buf, (char **)NULL, base);
if (flags & POINTER)
*va_arg(ap, void **) =
(void *)(uintptr_t)res;
else if (flags & SHORTSHORT)
*va_arg(ap, char *) = res;
else if (flags & SHORT)
*va_arg(ap, short *) = res;
else if (flags & LONG)
*va_arg(ap, long *) = res;
else
*va_arg(ap, int *) = res;
nassigned++;
}
nread += p - buf;
nconversions++;
break;
}
}
input_failure:
return (nconversions != 0 ? nassigned : -1);
match_failure:
return (nassigned);
}
/*
* Fill in the given table from the scanset at the given format
* (just after `['). Return a pointer to the character past the
* closing `]'. The table has a 1 wherever characters should be
* considered part of the scanset.
*/
static const unsigned char *
__sccl(char *tab, const unsigned char *fmt)
{
int c, n, v;
/* first `clear' the whole table */
c = *fmt++; /* first char hat => negated scanset */
if (c == '^') {
v = 1; /* default => accept */
c = *fmt++; /* get new first char */
} else
v = 0; /* default => reject */
/* XXX: Will not work if sizeof(tab*) > sizeof(char) */
memset((void *) tab, v, 256);
if (c == 0)
return (fmt - 1);/* format ended before closing ] */
/*
* Now set the entries corresponding to the actual scanset
* to the opposite of the above.
*
* The first character may be ']' (or '-') without being special;
* the last character may be '-'.
*/
v = 1 - v;
for (;;) {
tab[c] = v; /* take character c */
doswitch:
n = *fmt++; /* and examine the next */
switch (n) {
case 0: /* format ended too soon */
return (fmt - 1);
case '-':
/*
* A scanset of the form
* [01+-]
* is defined as `the digit 0, the digit 1,
* the character +, the character -', but
* the effect of a scanset such as
* [a-zA-Z0-9]
* is implementation defined. The V7 Unix
* scanf treats `a-z' as `the letters a through
* z', but treats `a-a' as `the letter a, the
* character -, and the letter a'.
*
* For compatibility, the `-' is not considerd
* to define a range if the character following
* it is either a close bracket (required by ANSI)
* or is not numerically greater than the character
* we just stored in the table (c).
*/
n = *fmt;
if (n == ']' || n < c) {
c = '-';
break; /* resume the for(;;) */
}
fmt++;
/* fill in the range */
do {
tab[++c] = v;
} while (c < n);
c = n;
/*
* Alas, the V7 Unix scanf also treats formats
* such as [a-c-e] as `the letters a through e'.
* This too is permitted by the standard....
*/
goto doswitch;
break;
case ']': /* end of scanset */
return (fmt);
default: /* just another character */
c = n;
break;
}
}
/* NOTREACHED */
}

View file

@ -0,0 +1,9 @@
#![allow(nonstandard_style)]
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}