Bläddra i källkod

added Base64.urlEncode/urlDecode

Nicolas Cannasse 6 år sedan
förälder
incheckning
4c7577e0d8
1 ändrade filer med 23 tillägg och 0 borttagningar
  1. 23 0
      std/haxe/crypto/Base64.hx

+ 23 - 0
std/haxe/crypto/Base64.hx

@@ -29,6 +29,9 @@ class Base64 {
 	public static var CHARS(default,null) = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 	public static var BYTES(default,null) = haxe.io.Bytes.ofString(CHARS);
 
+	public static var URL_CHARS(default,null) = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
+	public static var URL_BYTES(default,null) = haxe.io.Bytes.ofString(URL_CHARS);
+
 	public static function encode( bytes : haxe.io.Bytes, complement = true ) : String {
 		var str = new BaseCode(BYTES).encodeBytes(bytes).toString();
 		if( complement )
@@ -49,4 +52,24 @@ class Base64 {
 		return new BaseCode(BYTES).decodeBytes(haxe.io.Bytes.ofString(str));
 	}
 
+	public static function urlEncode( bytes : haxe.io.Bytes, complement = false ) : String {
+		var str = new BaseCode(URL_BYTES).encodeBytes(bytes).toString();
+		if( complement )
+			switch (bytes.length % 3) {
+			case 1:
+				str += "==";
+			case 2:
+				str += "=";
+			default:
+			}
+		return str;
+	}
+
+	public static function urlEncode( str : String, complement = false ) : haxe.io.Bytes {
+		if( complement )
+			while( str.charCodeAt(str.length-1) == "=".code )
+				str = str.substr(0,-1);
+		return new BaseCode(URL_BYTES).decodeBytes(haxe.io.Bytes.ofString(str));
+	}
+
 }