// An implementation of a libc for the web. Basically, implementations of
// the various standard C libraries, that can be called from compiled code,
// and work using the actual JavaScript environment.
//
// We search the Library object when there is an external function. If the
// entry in the Library is a function, we insert it. If it is a string, we
// do another lookup in the library (a simple way to write a function once,
// if it can be called by different names). We also allow dependencies,
// using __deps. Initialization code to be run after allocating all
// global constants can be defined by __postset.
//
// Note that the full function name will be '_' + the name in the Library
// object. For convenience, the short name appears here. Note that if you add a
// new function with an '_', it will not be found.
var Library = {
// stdio.h
_scanString: function() {
// Supports %x, %4x, %d.%d
var str = Pointer_stringify(arguments[0]);
var stri = 0;
var fmt = Pointer_stringify(arguments[1]);
var fmti = 0;
var args = Array.prototype.slice.call(arguments, 2);
var argsi = 0;
var read = 0;
while (fmti < fmt.length) {
if (fmt[fmti] === '%') {
fmti++;
var max_ = parseInt(fmt[fmti]);
if (!isNaN(max_)) fmti++;
var type = fmt[fmti];
fmti++;
var curr = 0;
while ((curr < max_ || isNaN(max_)) && stri+curr < str.length) {
if ((type === 'd' && parseInt(str[stri+curr]) >= 0) ||
(type === 'x' && parseInt(str[stri+curr].replace(/[a-fA-F]/, 5)) >= 0)) {
curr++;
} else {
break;
}
}
if (curr === 0) { print("FAIL"); break; }
var text = str.substr(stri, curr);
stri += curr;
var value = type === 'd' ? parseInt(text) : eval('0x' + text);
{{{ makeSetValue('args[argsi]', '0', 'value', 'i32') }}}
argsi++;
read++;
} else { // not '%'
if (fmt[fmti] === str[stri]) {
fmti++;
stri++;
} else {
break;
}
}
}
return read; // XXX Possibly we should return EOF (-1) sometimes
},
sscanf: '_scanString',
_formatString__deps: ['STDIO'],
_formatString: function() {
function isFloatArg(type) {
return String.fromCharCode(type) in Runtime.set('f', 'e', 'g');
}
var cStyle = false;
var textIndex = arguments[0];
var argIndex = 1;
if (textIndex < 0) {
cStyle = true;
textIndex = -textIndex;
argIndex = arguments[1];
} else