1 /*
2  * Hunt - A redis client library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11  
12 module hunt.redis.Tuple;
13 
14 import hunt.redis.util.ByteArrayComparator;
15 import hunt.redis.util.SafeEncoder;
16 
17 import hunt.util.ArrayHelper;
18 
19 import hunt.Double;
20 import hunt.util.Common;
21 import hunt.util.Comparator;
22 
23 import std.conv;
24 
25 class Tuple : Comparable!(Tuple) {
26     private const(ubyte)[] element;
27     private double score;
28 
29     this(string element, double score) {
30         this(SafeEncoder.encode(element), score);
31     }
32 
33     this(const(ubyte)[] element, double score) {
34         this.element = element;
35         this.score = score;
36     }
37 
38     override size_t toHash() @trusted nothrow {
39         int prime = 31;
40         int result = 1;
41         result = prime * result;
42         if (null != element) {
43             foreach (byte b; element) {
44                 result = prime * result + b;
45             }
46         }
47         // FIXME: Needing refactor or cleanup -@zxp at 7/17/2019, 11:17:51 AM
48         // 
49         long temp = cast(long)score; // Double.doubleToLongBits(score);
50         result = prime * result + cast(int)(temp ^ (temp >>> 32));
51         return result;
52     }
53 
54     override bool opEquals(Object obj) {
55         if (obj is null)
56             return false;
57         if (obj is this)
58             return true;
59 
60         Tuple other = cast(Tuple) obj;
61         if (other is null)
62             return false;
63         if (element != other.element)
64             return false;
65         return score == other.score;
66     }
67 
68     override int opCmp(Tuple other) {
69         return compare(this, other);
70     }
71     alias opCmp = Object.opCmp;
72 
73     static int compare(Tuple t1, Tuple t2) {
74         int compScore = hunt.util.Comparator.compare(t1.score, t2.score);
75         if (compScore != 0)
76             return compScore;
77 
78         return t1.element == t2.element;
79     }
80 
81     string getElement() {
82         return SafeEncoder.encode(element);
83     }
84 
85     const(ubyte)[] getBinaryElement() {
86         return element;
87     }
88 
89     double getScore() {
90         return score;
91     }
92 
93     override string toString() {
94         return "[" ~ cast(string)element ~ "," ~ score.to!string ~ "]";
95     }
96 }