1 /*
2  * Collie - An asynchronous event-driven network framework using Dlang development
3  *
4  * Copyright (C) 2015-2017  Shanghai Putao Technology Co., Ltd 
5  *
6  * Developer: putao's Dlang team
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 module collie.utils..string;
12 
13 import std.array;
14 import std..string;
15 import std.traits;
16 import std.range;
17 
18 void splitNameValue(TChar, Char, bool caseSensitive = true)(TChar[] data, in Char pDelim, in Char vDelim, 
19 	scope bool delegate(TChar[],TChar[]) callback) if(isSomeChar!(Unqual!TChar) && isSomeChar!(Unqual!Char) )
20 {
21 	enum size_t blen = 1;
22 	enum size_t elen = 1;
23 	const dchar pairDelim = pDelim;
24 	const dchar valueDelim = vDelim;
25 	
26 	mixin(TSplitNameValue!());
27 }
28 
29 void splitNameValue(TChar, Char,bool caseSensitive = true)(TChar[] data, const(Char)[] pairDelim, const(Char)[] valueDelim,
30 	scope bool delegate(TChar[],TChar[]) callback) if(isSomeChar!(Unqual!TChar) && isSomeChar!(Unqual!Char) )
31 {
32 	const size_t blen = pairDelim.length;
33 	const size_t elen = valueDelim.length;
34 	
35 	mixin(TSplitNameValue!());
36 	
37 }
38 
39 bool isSameIngnoreLowUp(TChar)(TChar[] s1,TChar[] s2) if(isSomeChar!(Unqual!TChar))
40 {
41 	import std.uni;
42 	if(s1.length != s2.length) return false;
43 	for(size_t i = 0; i < s1.length; ++i)
44 	{
45 		dchar c1 = toLower(s1[i]);
46 		dchar c2 = toLower(s2[i]);
47 		if(c1 != c2)
48 			return false;
49 	}
50 	return true;
51 }
52 
53 private:
54 template TSplitNameValue()
55 {
56 	enum TSplitNameValue = q{
57 		static if(caseSensitive)
58 			enum thecaseSensitive = CaseSensitive.yes;
59 		else
60 			enum thecaseSensitive = CaseSensitive.no;
61 		while(data.length > 0)
62 		{
63 			auto index = data.indexOf(pairDelim,thecaseSensitive);
64 			string keyValue;
65 			if(index < 0){
66 				keyValue = data;
67 				data.length = 0;
68 			} else {
69 				keyValue = data[0..index];
70 				data = data[(index + blen) .. $];
71 			}
72 			if(keyValue.length == 0)
73 				continue;
74 			auto valueDelimPos = keyValue.indexOf(valueDelim,thecaseSensitive);
75 			if(valueDelimPos < 0){
76 				if(!callback(keyValue,string.init))
77 					return;
78 			} else {
79 				auto name = keyValue[0..valueDelimPos];
80 				auto value = keyValue[(valueDelimPos + elen)..$];
81 				if(!callback(name,value))
82 					return;
83 			}
84 		}
85 	};
86 } 
87 
88 unittest
89 {
90 	import std.stdio;
91 	string hh = "ggujg=wee&ggg=ytgy&ggg0HH&hjkhk=00";
92 	string hh2 = "ggujg$=wee&$ggg=ytgy&$ggg0HH&hjkhk$=00";
93 	
94 	splitNameValue(hh,'&','=',(string key,string value){
95 			writeln("1.   ", key, "  ", value);
96 			return true;
97 		});
98 	
99 	splitNameValue(hh2,"&$","$=",(string key,string value){
100 			writeln("2.   ", key, "  ", value);
101 			return true;
102 		});
103 	
104 	writeln(isSameIngnoreLowUp("AAA12345", "aaa12345"));
105 }