Sync with Haxe std library (remove some overrides)

This commit is contained in:
Joshua Granick
2018-04-26 11:47:41 -07:00
parent 19bbf4edd6
commit 5596a09c79
7 changed files with 172 additions and 1086 deletions

View File

@@ -1,351 +0,0 @@
/*
* Copyright (C)2005-2012 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe;
/**
Elements return by `CallStack` methods.
**/
enum StackItem {
CFunction;
Module( m : String );
FilePos( s : Null<StackItem>, file : String, line : Int );
Method( classname : String, method : String );
LocalFunction( ?v : Int );
}
/**
Get informations about the call stack.
**/
class CallStack {
#if js
static var lastException:js.Error;
static function getStack(e:js.Error):Array<StackItem> {
if (e == null) return [];
// https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
var oldValue = (untyped Error).prepareStackTrace;
(untyped Error).prepareStackTrace = function (error, callsites :Array<Dynamic>) {
var stack = [];
for (site in callsites) {
if (wrapCallSite != null) site = wrapCallSite(site);
var method = null;
var fullName :String = site.getFunctionName();
if (fullName != null) {
var idx = fullName.lastIndexOf(".");
if (idx >= 0) {
var className = fullName.substr(0, idx);
var methodName = fullName.substr(idx+1);
method = Method(className, methodName);
}
}
stack.push(FilePos(method, site.getFileName(), site.getLineNumber()));
}
return stack;
}
var a = makeStack(e.stack);
(untyped Error).prepareStackTrace = oldValue;
return a;
}
// support for source-map-support module
@:noCompletion
public static var wrapCallSite:Dynamic->Dynamic;
#end
/**
Return the call stack elements, or an empty array if not available.
**/
public static function callStack() : Array<StackItem> {
#if neko
var a = makeStack(untyped __dollar__callstack());
a.shift(); // remove Stack.callStack()
return a;
#elseif flash
var a = makeStack( new flash.errors.Error().getStackTrace() );
a.shift(); // remove Stack.callStack()
return a;
#elseif php
return makeStack("%s");
#elseif cpp
var s:Array<String> = untyped __global__.__hxcpp_get_call_stack(true);
return makeStack(s);
#elseif js
try {
throw new js.Error();
} catch( e : Dynamic ) {
var a = getStack(e);
a.shift(); // remove Stack.callStack()
return a;
}
#elseif java
var stack = [];
for ( el in java.lang.Thread.currentThread().getStackTrace() ) {
var className = el.getClassName();
var methodName = el.getMethodName();
var fileName = el.getFileName();
var lineNumber = el.getLineNumber();
var method = Method( className, methodName );
if ( fileName != null || lineNumber >= 0 ) {
stack.push( FilePos( method, fileName, lineNumber ) );
}
else {
stack.push( method );
}
}
stack.shift();
stack.shift();
stack.pop();
return stack;
#elseif cs
return makeStack(new cs.system.diagnostics.StackTrace(1, true));
#elseif python
var stack = [];
var infos = python.lib.Traceback.extract_stack();
infos.pop();
infos.reverse();
for (elem in infos)
stack.push(FilePos(null, elem._1, elem._2));
return stack;
#else
return []; // Unsupported
#end
}
/**
Return the exception stack : this is the stack elements between
the place the last exception was thrown and the place it was
caught, or an empty array if not available.
**/
#if cpp @:noStack #end /* Do not mess up the exception stack */
public static function exceptionStack() : Array<StackItem> {
#if neko
return makeStack(untyped __dollar__excstack());
#elseif as3
return new Array();
#elseif flash
var err : flash.errors.Error = untyped flash.Boot.lastError;
if( err == null ) return new Array();
var a = makeStack( err.getStackTrace() );
var c = callStack();
var i = c.length - 1;
while( i > 0 ) {
if( Std.string(a[a.length-1]) == Std.string(c[i]) )
a.pop();
else
break;
i--;
}
return a;
#elseif php
return makeStack("%e");
#elseif cpp
var s:Array<String> = untyped __global__.__hxcpp_get_exception_stack();
return makeStack(s);
#elseif java
var stack = [];
for ( el in java.internal.Exceptions.currentException().getStackTrace() ) {
var className = el.getClassName();
var methodName = el.getMethodName();
var fileName = el.getFileName();
var lineNumber = el.getLineNumber();
var method = Method( className, methodName );
if ( fileName != null || lineNumber >= 0 ) {
stack.push( FilePos( method, fileName, lineNumber ) );
}
else {
stack.push( method );
}
}
// stack.shift();
stack.shift();
stack.pop();
return stack;
#elseif cs
return makeStack(new cs.system.diagnostics.StackTrace(cs.internal.Exceptions.exception, true));
#elseif python
var stack = [];
var exc = python.lib.Sys.exc_info();
if (exc._3 != null)
{
var infos = python.lib.Traceback.extract_tb(exc._3);
infos.reverse();
for (elem in infos)
stack.push(FilePos(null, elem._1, elem._2));
}
return stack;
#elseif js
return untyped __define_feature__("haxe.CallStack.exceptionStack", getStack(lastException));
#else
return []; // Unsupported
#end
}
/**
Returns a representation of the stack as a printable string.
**/
public static function toString( stack : Array<StackItem> ) {
var b = new StringBuf();
#if cpp
stack = stack.copy ();
stack.reverse();
#end
for( s in stack ) {
b.add("\nCalled from ");
itemToString(b,s);
}
return b.toString();
}
private static function itemToString( b : StringBuf, s ) {
switch( s ) {
case CFunction:
b.add("a C function");
case Module(m):
b.add("module ");
b.add(m);
case FilePos(s,file,line):
if( s != null ) {
itemToString(b,s);
b.add(" (");
}
b.add(file);
b.add(" line ");
b.add(line);
if( s != null ) b.add(")");
case Method(cname,meth):
b.add(cname);
b.add(".");
b.add(meth);
case LocalFunction(n):
b.add("local function #");
b.add(n);
}
}
#if cpp @:noStack #end /* Do not mess up the exception stack */
private static function makeStack(s #if cs : cs.system.diagnostics.StackTrace #end) {
#if neko
var a = new Array();
var l = untyped __dollar__asize(s);
var i = 0;
while( i < l ) {
var x = s[i++];
if( x == null )
a.unshift(CFunction);
else if( untyped __dollar__typeof(x) == __dollar__tstring )
a.unshift(Module(new String(x)));
else
a.unshift(FilePos(null,new String(untyped x[0]),untyped x[1]));
}
return a;
#elseif flash
var a = new Array();
var r = ~/at ([^\/]+?)\$?(\/[^\(]+)?\(\)(\[(.*?):([0-9]+)\])?/;
var rlambda = ~/^MethodInfo-([0-9]+)$/g;
while( r.match(s) ) {
var cl = r.matched(1).split("::").join(".");
var meth = r.matched(2);
var item;
if( meth == null ) {
if( rlambda.match(cl) )
item = LocalFunction(Std.parseInt(rlambda.matched(1)));
else
item = Method(cl,"new");
} else
item = Method(cl,meth.substr(1));
if( r.matched(3) != null )
item = FilePos( item, r.matched(4), Std.parseInt(r.matched(5)) );
a.push(item);
s = r.matchedRight();
}
return a;
#elseif php
if (!untyped __call__("isset", __var__("GLOBALS", s)))
return [];
var a : Array<String> = untyped __var__("GLOBALS", s);
var m = [];
for( i in 0...a.length - ((s == "%s") ? 2 : 0)) {
var d = a[i].split("::");
m.unshift(Method(d[0],d[1]));
}
return m;
#elseif cpp
var stack : Array<String> = s;
var m = new Array<StackItem>();
for(func in stack) {
var words = func.split("::");
if (words.length==0)
m.push(CFunction)
else if (words.length==2)
m.push(Method(words[0],words[1]));
else if (words.length==4)
m.push(FilePos( Method(words[0],words[1]),words[2],Std.parseInt(words[3])));
}
return m;
#elseif js
if (s == null) {
return [];
} else if ((untyped __js__("typeof"))(s) == "string") {
// Return the raw lines in browsers that don't support prepareStackTrace
var stack : Array<String> = s.split("\n");
if( stack[0] == "Error" ) stack.shift();
var m = [];
var rie10 = ~/^ at ([A-Za-z0-9_. ]+) \(([^)]+):([0-9]+):([0-9]+)\)$/;
for( line in stack ) {
if( rie10.match(line) ) {
var path = rie10.matched(1).split(".");
var meth = path.pop();
var file = rie10.matched(2);
var line = Std.parseInt(rie10.matched(3));
m.push(FilePos( meth == "Anonymous function" ? LocalFunction() : meth == "Global code" ? null : Method(path.join("."),meth), file, line ));
} else
m.push(Module(StringTools.trim(line))); // A little weird, but better than nothing
}
return m;
} else {
return cast s;
}
#elseif cs
var stack = [];
for (i in 0...s.FrameCount)
{
var frame = s.GetFrame(i);
var m = frame.GetMethod();
var method = StackItem.Method(m.ReflectedType.ToString(), m.Name);
var fileName = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber();
if (fileName != null || lineNumber >= 0)
stack.push(FilePos(method, fileName, lineNumber));
else
stack.push(method);
}
return stack;
#else
return null;
#end
}
}

View File

@@ -1,417 +0,0 @@
/*
* Copyright (C)2005-2016 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe;
private enum TemplateExpr {
OpVar( v : String );
OpExpr( expr : Void -> Dynamic );
OpIf( expr : Void -> Dynamic, eif : TemplateExpr, eelse : TemplateExpr );
OpStr( str : String );
OpBlock( l : List<TemplateExpr> );
OpForeach( expr : Void -> Dynamic, loop : TemplateExpr );
OpMacro( name : String, params : List<TemplateExpr> );
}
private typedef Token = {
var s : Bool;
var p : String;
var l : Array<String>;
}
private typedef ExprToken = {
var s : Bool;
var p : String;
}
/**
Template provides a basic templating mechanism to replace values in a source
String, and to have some basic logic.
A complete documentation of the supported syntax is available at:
<http://haxe.org/manual/std-template.html>
**/
class Template {
static var splitter = ~/(::[A-Za-z0-9_ ()&|!+=\/><*."-]+::|\$\$([A-Za-z0-9_-]+)\()/;
static var expr_splitter = ~/(\(|\)|[ \r\n\t]*"[^"]*"[ \r\n\t]*|[!+=\/><*.&|-]+)/;
static var expr_trim = ~/^[ ]*([^ ]+)[ ]*$/;
static var expr_int = ~/^[0-9]+$/;
static var expr_float = ~/^([+-]?)(?=\d|,\d)\d*(,\d*)?([Ee]([+-]?\d+))?$/;
/**
Global replacements which are used across all Template instances. This
has lower priority than the context argument of execute().
**/
public static var globals : Dynamic = {};
var expr : TemplateExpr;
var context : Dynamic;
var macros : Dynamic;
var stack : List<Dynamic>;
var buf : StringBuf;
/**
Creates a new Template instance from `str`.
`str` is parsed into tokens, which are stored for internal use. This
means that multiple execute() operations on a single Template instance
are more efficient than one execute() operations on multiple Template
instances.
If `str` is null, the result is unspecified.
**/
public function new( str : String ) {
var tokens = parseTokens(str);
expr = parseBlock(tokens);
if( !tokens.isEmpty() )
throw "Unexpected '"+tokens.first().s+"'";
}
/**
Executes `this` Template, taking into account `context` for
replacements and `macros` for callback functions.
If `context` has a field 'name', its value replaces all occurrences of
::name:: in the Template. Otherwise Template.globals is checked instead,
If 'name' is not a field of that either, ::name:: is replaced with null.
If `macros` has a field 'name', all occurrences of $$name(args) are
replaced with the result of calling that field. The first argument is
always the resolve() method, followed by the given arguments.
If `macros` has no such field, the result is unspecified.
If `context` is null, the result is unspecified. If `macros` is null,
no macros are used.
**/
public function execute( context : Dynamic, ?macros : Dynamic ):String {
this.macros = if( macros == null ) {} else macros;
this.context = context;
stack = new List();
buf = new StringBuf();
run(expr);
return buf.toString();
}
function resolve( v : String ) : Dynamic {
if( v == "__current__" )
return context;
var value = Reflect.getProperty(context, v);
if( value != null || Reflect.hasField(context,v) )
return value;
for( ctx in stack ) {
value = Reflect.getProperty(ctx,v);
if( value != null || Reflect.hasField(ctx,v) )
return value;
}
return Reflect.field(globals,v);
}
function parseTokens( data : String ) {
var tokens = new List<Token>();
while( splitter.match(data) ) {
var p = splitter.matchedPos();
if( p.pos > 0 )
tokens.add({ p : data.substr(0,p.pos), s : true, l : null });
// : ?
if( data.charCodeAt(p.pos) == 58 ) {
tokens.add({ p : data.substr(p.pos + 2,p.len - 4), s : false, l : null });
data = splitter.matchedRight();
continue;
}
// macro parse
var parp = p.pos + p.len;
var npar = 1;
var params = [];
var part = "";
while( true ) {
var c = data.charCodeAt(parp);
parp++;
if( c == 40 ) {
npar++;
} else if( c == 41 ) {
npar--;
if (npar <= 0) break;
} else if( c == null ){
throw "Unclosed macro parenthesis";
}
if ( c == 44 && npar == 1) {
params.push(part);
part = "";
} else {
part += String.fromCharCode(c);
}
}
params.push(part);
tokens.add({ p : splitter.matched(2), s : false, l : params });
data = data.substr(parp,data.length - parp);
}
if( data.length > 0 )
tokens.add({ p : data, s : true, l : null });
return tokens;
}
function parseBlock( tokens : List<Token> ) {
var l = new List();
while( true ) {
var t = tokens.first();
if( t == null )
break;
if( !t.s && (t.p == "end" || t.p == "else" || t.p.substr(0,7) == "elseif ") )
break;
l.add(parse(tokens));
}
if( l.length == 1 )
return l.first();
return OpBlock(l);
}
function parse( tokens : List<Token> ) {
var t = tokens.pop();
var p = t.p;
if( t.s )
return OpStr(p);
// macro
if( t.l != null ) {
var pe = new List();
for( p in t.l )
pe.add(parseBlock(parseTokens(p)));
return OpMacro(p,pe);
}
// 'end' , 'else', 'elseif' can't be found here
if( p.substr(0,3) == "if " ) {
p = p.substr(3,p.length - 3);
var e = parseExpr(p);
var eif = parseBlock(tokens);
var t = tokens.first();
var eelse;
if( t == null )
throw "Unclosed 'if'";
if( t.p == "end" ) {
tokens.pop();
eelse = null;
} else if( t.p == "else" ) {
tokens.pop();
eelse = parseBlock(tokens);
t = tokens.pop();
if( t == null || t.p != "end" )
throw "Unclosed 'else'";
} else { // elseif
t.p = t.p.substr(4,t.p.length - 4);
eelse = parse(tokens);
}
return OpIf(e,eif,eelse);
}
if( p.substr(0,8) == "foreach " ) {
p = p.substr(8,p.length - 8);
var e = parseExpr(p);
var efor = parseBlock(tokens);
var t = tokens.pop();
if( t == null || t.p != "end" )
throw "Unclosed 'foreach'";
return OpForeach(e,efor);
}
if( expr_splitter.match(p) )
return OpExpr(parseExpr(p));
return OpVar(p);
}
function parseExpr( data : String ) {
var l = new List<ExprToken>();
var expr = data;
while( expr_splitter.match(data) ) {
var p = expr_splitter.matchedPos();
var k = p.pos + p.len;
if( p.pos != 0 )
l.add({ p : data.substr(0,p.pos), s : true });
var p = expr_splitter.matched(0);
l.add({ p : p, s : p.indexOf('"') >= 0 });
data = expr_splitter.matchedRight();
}
if( data.length != 0 )
l.add({ p : data, s : true });
var e:Void->Dynamic;
try {
e = makeExpr(l);
if( !l.isEmpty() )
throw l.first().p;
} catch( s : String ) {
throw "Unexpected '"+s+"' in "+expr;
}
return function() {
try {
return e();
} catch( exc : Dynamic ) {
throw "Error : "+Std.string(exc)+" in "+expr;
}
}
}
function makeConst( v : String ) : Void -> Dynamic {
expr_trim.match(v);
v = expr_trim.matched(1);
if( v.charCodeAt(0) == 34 ) {
var str = v.substr(1,v.length-2);
return function() return str;
}
if( expr_int.match(v) ) {
var i = Std.parseInt(v);
return function() { return i; };
}
if( expr_float.match(v) ) {
var f = Std.parseFloat(v);
return function() { return f; };
}
var me = this;
return function() { return me.resolve(v); };
}
function makePath( e : Void -> Dynamic, l : List<ExprToken> ) {
var p = l.first();
if( p == null || p.p != "." )
return e;
l.pop();
var field = l.pop();
if( field == null || !field.s )
throw field.p;
var f = field.p;
expr_trim.match(f);
f = expr_trim.matched(1);
return makePath(function() { return Reflect.field(e(),f); },l);
}
function makeExpr( l ) {
return makePath(makeExpr2(l),l);
}
function makeExpr2( l : List<ExprToken> ) : Void -> Dynamic {
var p = l.pop();
if( p == null )
throw "<eof>";
if( p.s )
return makeConst(p.p);
switch( p.p ) {
case "(":
var e1:Dynamic = makeExpr(l);
var p = l.pop();
if( p == null || p.s )
throw p;
if( p.p == ")" )
return e1;
var e2:Dynamic = makeExpr(l);
var p2 = l.pop();
if( p2 == null || p2.p != ")" )
throw p2;
return switch( p.p ) {
case "+": function() { return cast e1() + e2(); };
case "-": function() { return cast e1() - e2(); };
case "*": function() { return cast e1() * e2(); };
case "/": function() { return cast e1() / e2(); };
case ">": function() { return cast e1() > e2(); };
case "<": function() { return cast e1() < e2(); };
case ">=": function() { return cast e1() >= e2(); };
case "<=": function() { return cast e1() <= e2(); };
case "==": function() { return cast e1() == e2(); };
case "!=": function() { return cast e1() != e2(); };
case "&&": function() { return cast e1() && e2(); };
case "||": function() { return cast e1() || e2(); };
default: throw "Unknown operation "+p.p;
}
case "!":
var e : Void->Dynamic = makeExpr(l);
return function() {
var v : Dynamic = e();
return (v == null || v == false);
};
case "-":
var e = makeExpr(l);
return function() { return -e(); };
}
throw p.p;
}
function run( e : TemplateExpr ) {
switch( e ) {
case OpVar(v):
buf.add(Std.string(resolve(v)));
case OpExpr(e):
buf.add(Std.string(e()));
case OpIf(e,eif,eelse):
var v : Dynamic = e();
if( v == null || v == false ) {
if( eelse != null ) run(eelse);
} else
run(eif);
case OpStr(str):
buf.add(str);
case OpBlock(l):
for( e in l )
run(e);
case OpForeach(e,loop):
var v : Dynamic = e();
try {
var x : Dynamic = v.iterator();
if( x.hasNext == null ) throw null;
v = x;
} catch( e : Dynamic ) try {
if( v.hasNext == null ) throw null;
} catch( e : Dynamic ) {
throw "Cannot iter on " + v;
}
stack.push(context);
var v : Iterator<Dynamic> = v;
for( ctx in v ) {
context = ctx;
run(loop);
}
context = stack.pop();
case OpMacro(m,params):
var v : Dynamic = Reflect.field(macros,m);
var pl = new Array<Dynamic>();
var old = buf;
pl.push(resolve);
for( p in params ) {
switch( p ) {
case OpVar(v): pl.push(resolve(v));
default:
buf = new StringBuf();
run(p);
pl.push(buf.toString());
}
}
buf = old;
try {
buf.add(Std.string(Reflect.callMethod(macros,v,pl)));
} catch( e : Dynamic ) {
var plstr = try pl.join(",") catch( e : Dynamic ) "???";
var msg = "Macro call "+m+"("+plstr+") failed ("+Std.string(e)+")";
#if neko
neko.Lib.rethrow(msg);
#else
throw msg;
#end
}
}
}
}

View File

@@ -5,7 +5,7 @@ package haxe;
// Original haxe.Timer class
/*
* Copyright (C)2005-2013 Haxe Foundation
* Copyright (C)2005-2018 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
@@ -177,14 +177,14 @@ class Timer {
#elseif (neko || php)
return Sys.time();
#elseif js
return js.Browser.window.performance.now () / 1000;
return Date.now().getTime() / 1000;
#elseif cpp
return untyped __global__.__time_stamp();
#elseif python
return Sys.cpuTime();
#elseif sys
return Sys.time();
#else
return 0;
#end

View File

@@ -1,91 +0,0 @@
/*
* Copyright (C)2005-2012 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
/**
Hash methods for Hmac calculation.
*/
enum HashMethod {
MD5;
SHA1;
SHA256;
}
/**
Calculates a Hmac of the given Bytes using a HashMethod.
*/
class Hmac {
var method : HashMethod;
var blockSize : Int;
var length : Int;
public function new( hashMethod : HashMethod ) {
method = hashMethod;
blockSize = switch ( hashMethod ) {
case MD5, SHA1, SHA256: 64;
}
length = switch ( hashMethod ) {
case MD5: 16;
case SHA1: 20;
case SHA256: 32;
}
}
inline function doHash( b : haxe.io.Bytes ) : haxe.io.Bytes {
return switch ( method ) {
case MD5: Md5.make(b);
case SHA1: Sha1.make(b);
case SHA256: Sha256.make(b);
}
}
function nullPad( s : haxe.io.Bytes, chunkLen : Int ) : haxe.io.Bytes {
var r = chunkLen - (s.length % chunkLen);
if(r == chunkLen && s.length != 0)
return s;
var sb = new haxe.io.BytesBuffer();
sb.add(s);
for(x in 0...r)
sb.addByte(0);
return sb.getBytes();
}
public function make( key : haxe.io.Bytes, msg : haxe.io.Bytes ) : haxe.io.Bytes {
if(key.length > blockSize) {
key = doHash(key);
}
key = nullPad(key, blockSize);
var Ki = new haxe.io.BytesBuffer();
var Ko = new haxe.io.BytesBuffer();
for (i in 0...key.length) {
Ko.addByte(key.get(i) ^ 0x5c);
Ki.addByte(key.get(i) ^ 0x36);
}
// hash(Ko + hash(Ki + message))
Ki.add(msg);
Ko.add(doHash(Ki.getBytes()));
return doHash(Ko.getBytes());
}
}

View File

@@ -1,195 +0,0 @@
/*
* Copyright (C)2005-2012 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.crypto;
/**
Creates a Sha256 of a String.
*/
class Sha256 {
public static function encode( s:String ) : String {
#if php
return untyped __call__("hash", "sha256", s);
#else
var sh = new Sha256();
var h = sh.doEncode(str2blks(s), s.length*8);
return sh.hex(h);
#end
}
public static function make( b : haxe.io.Bytes ) : haxe.io.Bytes {
#if php
return haxe.io.Bytes.ofData(untyped __call__("hash", "sha256", b.getData(), true));
#else
var h = new Sha256().doEncode(bytes2blks(b), b.length*8);
var out = haxe.io.Bytes.alloc(32);
var p = 0;
for( i in 0...8 ) {
out.set(p++,h[i]>>>24);
out.set(p++,(h[i]>>16)&0xFF);
out.set(p++,(h[i]>>8)&0xFF);
out.set(p++,h[i]&0xFF);
}
return out;
#end
}
public function new() {
}
function doEncode( m : Array<Int>, l : Int ) : Array<Int> {
var K : Array<Int> = [
0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,
0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,
0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,
0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,
0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,
0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,
0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,
0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,
0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,
0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,
0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,
0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,
0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2
];
var HASH : Array<Int> = [
0x6A09E667,0xBB67AE85,0x3C6EF372,0xA54FF53A,
0x510E527F,0x9B05688C,0x1F83D9AB,0x5BE0CD19
];
var W = new Array<Int>();
W[64] = 0;
var a:Int,b:Int,c:Int,d:Int,e:Int,f:Int,g:Int,h:Int;
var T1, T2;
m[l >> 5] |= 0x80 << (24 - l % 32);
m[((l + 64 >> 9) << 4) + 15] = l;
var i : Int = 0;
while ( i < m.length ) {
a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
for ( j in 0...64 ) {
if (j < 16)
W[j] = m[j + i];
else
W[j] = safeAdd(safeAdd(safeAdd(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
T1 = safeAdd(safeAdd(safeAdd(safeAdd(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
T2 = safeAdd(Sigma0256(a), Maj(a, b, c));
h = g; g = f; f = e; e = safeAdd(d, T1); d = c; c = b; b = a; a = safeAdd(T1, T2);
}
HASH[0] = safeAdd(a, HASH[0]);
HASH[1] = safeAdd(b, HASH[1]);
HASH[2] = safeAdd(c, HASH[2]);
HASH[3] = safeAdd(d, HASH[3]);
HASH[4] = safeAdd(e, HASH[4]);
HASH[5] = safeAdd(f, HASH[5]);
HASH[6] = safeAdd(g, HASH[6]);
HASH[7] = safeAdd(h, HASH[7]);
i += 16;
}
return HASH;
}
/*
Convert a string to a sequence of 16-word blocks, stored as an array.
Append padding bits and the length, as described in the SHA1 standard.
*/
static function str2blks( s :String ) : Array<Int> {
var nblk = ((s.length + 8) >> 6) + 1;
var blks = new Array<Int>();
for (i in 0...nblk*16)
blks[i] = 0;
for (i in 0...s.length){
var p = i >> 2;
blks[p] |= s.charCodeAt(i) << (24 - ((i & 3) << 3));
}
var i = s.length;
var p = i >> 2;
blks[p] |= 0x80 << (24 - ((i & 3) << 3));
blks[nblk * 16 - 1] = s.length * 8;
return blks;
}
static function bytes2blks( b : haxe.io.Bytes ) : Array<Int> {
var nblk = ((b.length + 8) >> 6) + 1;
var blks = new Array<Int>();
for (i in 0...nblk*16)
blks[i] = 0;
for (i in 0...b.length){
var p = i >> 2;
blks[p] |= b.get(i) << (24 - ((i & 3) << 3));
}
var i = b.length;
var p = i >> 2;
blks[p] |= 0x80 << (24 - ((i & 3) << 3));
blks[nblk * 16 - 1] = b.length * 8;
return blks;
}
function S(X, n) {
return ( X >>> n ) | (X << (32 - n));
}
function R(X, n) {
return ( X >>> n );
}
function Ch(x, y, z) {
return ((x & y) ^ ((~x) & z));
}
function Maj(x, y, z) {
return ((x & y) ^ (x & z) ^ (y & z));
}
function Sigma0256(x) {
return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
}
function Sigma1256(x) {
return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
}
function Gamma0256(x) {
return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
}
function Gamma1256(x) {
return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
}
function safeAdd(x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function hex( a : Array<Int> ){
var str = "";
for( num in a ) {
str += StringTools.hex(num, 8);
}
return str.toLowerCase();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright (C)2005-2016 Haxe Foundation
* Copyright (C)2005-2018 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
@@ -19,7 +19,7 @@
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package haxe.io; #if !js
package haxe.io; #if (!hl && !js)
#if cpp
@@ -53,8 +53,6 @@ class Bytes {
return untyped $sget(b,pos);
#elseif flash
return b[pos];
#elseif php
return b.get(pos);
#elseif cpp
return untyped b[pos];
#elseif java
@@ -71,8 +69,6 @@ class Bytes {
untyped $sset(b,pos,v);
#elseif flash
b[pos] = v;
#elseif php
b.set(pos, v);
#elseif cpp
untyped b[pos] = v;
#elseif java
@@ -92,8 +88,6 @@ class Bytes {
#end
#if neko
try untyped $sblit(b,pos,src.b,srcpos,len) catch( e : Dynamic ) throw Error.OutsideBounds;
#elseif php
b.blit(pos, src.b, srcpos, len);
#elseif flash
b.position = pos;
if( len > 0 ) b.writeBytes(src.b,srcpos,len);
@@ -102,7 +96,7 @@ class Bytes {
#elseif cs
cs.system.Array.Copy(src.b, srcpos, b, pos, len);
#elseif python
python.Syntax.pythonCode("self.b[{0}:{0}+{1}] = src.b[srcpos:srcpos+{1}]", pos, len);
python.Syntax.code("self.b[{0}:{0}+{1}] = src.b[srcpos:srcpos+{1}]", pos, len);
#elseif cpp
b.blit(pos, src.b, srcpos, len);
#else
@@ -151,8 +145,6 @@ class Bytes {
var b2 = new flash.utils.ByteArray();
b.readBytes(b2,0,len);
return new Bytes(len,b2);
#elseif php
return new Bytes(len, b.sub(pos, len));
#elseif java
var newarr = new java.NativeArray(len);
java.lang.System.arraycopy(b, pos, newarr, 0, len);
@@ -197,8 +189,6 @@ class Bytes {
b1.endian = flash.utils.Endian.LITTLE_ENDIAN;
b2.endian = flash.utils.Endian.LITTLE_ENDIAN;
return length - other.length;
#elseif php
return b.compare(other.b);
//#elseif cs
//TODO: memcmp if unsafe flag is on
#elseif cpp
@@ -326,7 +316,7 @@ class Bytes {
public inline function getInt32( pos : Int ) : Int {
#if neko_v21
return untyped $sget32(b, pos, false);
#elseif (php || python)
#elseif python
var v = get(pos) | (get(pos + 1) << 8) | (get(pos + 2) << 16) | (get(pos+3) << 24);
return if( v & 0x80000000 != 0 ) v | 0x80000000 else v;
#elseif lua
@@ -375,8 +365,6 @@ class Bytes {
#elseif flash
b.position = pos;
return b.readUTFBytes(len);
#elseif php
return b.getString(pos, len);
#elseif cpp
var result:String="";
untyped __global__.__hxcpp_string_of_bytes(b,result,pos,len);
@@ -388,7 +376,7 @@ class Bytes {
return new String(b, pos, len, "UTF-8")
catch (e:Dynamic) throw e;
#elseif python
return python.Syntax.pythonCode("self.b[{0}:{0}+{1}].decode('UTF-8','replace')", pos, len);
return python.Syntax.code("self.b[{0}:{0}+{1}].decode('UTF-8','replace')", pos, len);
#elseif lua
var begin = cast(Math.min(pos,b.length),Int);
var end = cast(Math.min(pos+len,b.length),Int);
@@ -435,8 +423,6 @@ class Bytes {
#elseif flash
b.position = 0;
return b.toString();
#elseif php
return b.toString();
#elseif cs
return cs.system.text.Encoding.UTF8.GetString(b, 0, length);
#elseif java
@@ -475,8 +461,6 @@ class Bytes {
var b = new flash.utils.ByteArray();
b.length = length;
return new Bytes(length,b);
#elseif php
return new Bytes(length, BytesData.alloc(length));
#elseif cpp
var a = new BytesData();
if (length>0) cpp.NativeArray.setSize(a, length);
@@ -503,9 +487,6 @@ class Bytes {
var b = new flash.utils.ByteArray();
b.writeUTFBytes(s);
return new Bytes(b.length,b);
#elseif php
var x = BytesData.ofString(s);
return new Bytes(x.length, x);
#elseif cpp
var a = new BytesData();
untyped __global__.__hxcpp_bytes_of_string(a,s);
@@ -562,8 +543,6 @@ class Bytes {
return new Bytes(b.length,b);
#elseif neko
return new Bytes(untyped __dollar__ssize(b),b);
#elseif php
return new Bytes(b.length, b);
#elseif cs
return new Bytes(b.Length,b);
#else
@@ -580,8 +559,6 @@ class Bytes {
return untyped __dollar__sget(b,pos);
#elseif flash
return b[pos];
#elseif php
return b.get(pos);
#elseif cpp
return untyped b.unsafeGet(pos);
#elseif java
@@ -594,7 +571,7 @@ class Bytes {
}
#else
#elseif js
#if !nodejs
@@ -830,4 +807,165 @@ class Bytes {
}
#elseif hl
@:coreApi
class Bytes {
public var length(default,null) : Int;
var b : hl.Bytes;
function new(b:hl.Bytes,length:Int) : Void {
this.b = b;
this.length = length;
}
inline function out(pos:Int) : Bool {
return (pos:UInt) >= (length : UInt);
}
inline function outRange(pos:Int,len:Int) : Bool {
return pos < 0 || len < 0 || ((pos+len):UInt) > (length : UInt);
}
public function get( pos : Int ) : Int {
return if( out(pos) ) 0 else b[pos];
}
public function set( pos : Int, v : Int ) : Void {
if( out(pos) ) throw Error.OutsideBounds;
b[pos] = v;
}
public function blit( pos : Int, src : Bytes, srcpos : Int, len : Int ) : Void {
if( outRange(pos, len) || src.outRange(srcpos,len) ) throw Error.OutsideBounds;
b.blit(pos, src.b, srcpos, len);
}
public function fill( pos : Int, len : Int, value : Int ) : Void {
if( outRange(pos,len) ) throw Error.OutsideBounds;
b.fill(pos, len, value);
}
public function sub( pos : Int, len : Int ) : Bytes {
if( outRange(pos,len) ) throw Error.OutsideBounds;
return new Bytes(b.sub(pos, len), len);
}
public function compare( other : Bytes ) : Int {
var len = length < other.length ? length : other.length;
var r = b.compare(0, other.b, 0, len);
if( r == 0 )
r = length - other.length;
return r;
}
public function getDouble( pos : Int ) : Float {
return if( out(pos + 7) ) 0. else b.getF64(pos);
}
public function getFloat( pos : Int ) : Float {
return if( out(pos + 3) ) 0. else b.getF32(pos);
}
public function setDouble( pos : Int, v : Float ) : Void {
if( out(pos + 7) ) throw Error.OutsideBounds;
b.setF64(pos, v);
}
public function setFloat( pos : Int, v : Float ) : Void {
if( out(pos + 3) ) throw Error.OutsideBounds;
b.setF32(pos, v);
}
public inline function getUInt16( pos : Int ) : Int {
return if( out(pos + 1) ) 0 else b.getUI16(pos);
}
public inline function setUInt16( pos : Int, v : Int ) : Void {
if( out(pos + 1) ) throw Error.OutsideBounds;
b.setUI16(pos, v);
}
public function getInt32( pos : Int ) : Int {
return if( out(pos + 3) ) 0 else b.getI32(pos);
}
public function getInt64( pos : Int ) : haxe.Int64 {
if( out(pos + 7) )
return haxe.Int64.ofInt(0);
return haxe.Int64.make(b.getI32(pos+4), b.getI32(pos));
}
public function setInt32( pos : Int, v : Int ) : Void {
if( out(pos + 3) ) throw Error.OutsideBounds;
b.setI32(pos, v);
}
public inline function setInt64( pos : Int, v : haxe.Int64 ) : Void {
setInt32(pos + 4, v.high);
setInt32(pos, v.low);
}
public function getString( pos : Int, len : Int ) : String {
if( outRange(pos,len) ) throw Error.OutsideBounds;
var b = new hl.Bytes(len + 1);
b.blit(0, this.b, pos, len);
b[len] = 0;
return @:privateAccess String.fromUTF8(b);
}
@:deprecated("readString is deprecated, use getString instead")
@:noCompletion
public inline function readString(pos:Int, len:Int):String {
return getString(pos, len);
}
public function toString() : String {
return getString(0,length);
}
public function toHex() : String {
var s = new StringBuf();
var chars = [];
var str = "0123456789abcdef";
for( i in 0...str.length )
chars.push(str.charCodeAt(i));
for( i in 0...length ) {
var c = get(i);
s.addChar(chars[c >> 4]);
s.addChar(chars[c & 15]);
}
return s.toString();
}
public inline function getData() : BytesData {
return new haxe.io.BytesData(b,length);
}
public static function alloc( length : Int ) : Bytes {
var b = new hl.Bytes(length);
b.fill(0, length, 0);
return new Bytes(b,length);
}
public static function ofString( s : String ) : Bytes @:privateAccess {
var size = 0;
var b = s.bytes.utf16ToUtf8(0, size);
return new Bytes(b,size);
}
public static function ofData( b : BytesData ) : Bytes {
return new Bytes(b.bytes,b.length);
}
public inline static function fastGet( b : BytesData, pos : Int ) : Int {
return b[pos];
}
}
#end

View File

@@ -19,6 +19,8 @@ abstract Bytes(HaxeBytes) from HaxeBytes to HaxeBytes {
#if js
this = new HaxeBytes (bytesData);
#elseif hl
this = new HaxeBytes (bytesData, length);
#else
this = new HaxeBytes (length, bytesData);
#end