bitswitch 0.0.1 → 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
data/README.md CHANGED
@@ -15,7 +15,7 @@ Usage could be for security, or settings, or more.
15
15
 
16
16
  ## Todo
17
17
 
18
- * Add support for labeling bits
18
+ * Think about new stuff to add in.
19
19
 
20
20
  ## Copyright
21
21
 
@@ -1,27 +1,97 @@
1
1
  class BitSwitch
2
- def initialize(n = 0)
2
+
3
+ def initialize(n = 0, labels = {})
4
+
5
+ if n.is_a?(Hash)
6
+
7
+ # Set default values
8
+ @labels = {}
9
+ @val = 0
10
+
11
+ # Loop through the hash and set the switches
12
+ i=0; n.each do |label, tf|
13
+ self[i] = tf ? 1 : 0
14
+ @labels[i] = label
15
+ i += 1
16
+ end
17
+
18
+ # Return the BitSwitch object
19
+ return self
20
+ end
21
+
22
+ # Set labels and initial number
23
+ @labels = labels
3
24
  @val = n
4
25
  end
5
26
 
27
+ # Set a bit
6
28
  def []=(bit, val)
7
29
  val = val > 0
30
+
31
+ # If a string representation of a bit was provided get the numerical
32
+ bit = @labels.invert[bit] if bit.is_a?(String)
33
+
34
+ # If nil return false
35
+ return false if bit.nil?
8
36
 
37
+ # Set/Unset the bits
9
38
  @val |= 2 ** bit if val
10
39
  @val &= ~(2 ** bit) if !val && self[bit]
40
+
41
+ # Return self
42
+ return self
11
43
  end
12
44
 
45
+ # Check a bit status
13
46
  def [](bit)
47
+
48
+ # If a string representation of a bit was provided get the numerical
49
+ bit = @labels.invert[bit] if bit.is_a?(String)
50
+
51
+ # If nil return false
52
+ return false if bit.nil?
53
+
54
+ # Check if the bit it set
14
55
  (2 ** bit) & @val > 0
15
56
  end
16
57
 
58
+ # Set an integer
17
59
  def set=(n)
18
60
  return false unless n.is_a?(Fixnum)
19
61
  @val = n
20
62
  end
63
+
64
+ def labels=(hash = {}, reset = false)
65
+
66
+ # If reset is false then merge the labels
67
+ return @labels.merge(hash) unless reset
68
+
69
+ # Set a whole new label hash
70
+ @labels = hash
71
+ end
21
72
 
73
+ # Convert to integer
22
74
  def to_i
23
75
  @val
24
76
  end
77
+
78
+ # Convert to hash
79
+ def to_hash
80
+
81
+ # Raise an error if no labels are set
82
+ raise StandardError, "No labels were set!" if @labels.empty?
83
+
84
+ # Prepare new hash
85
+ serialized = Hash.new
86
+
87
+ # Loop through the labels
88
+ @labels.each do |bit, label|
89
+ serialized[label] = self[bit]
90
+ end
91
+
92
+ # Return the serialized BitSwitch
93
+ serialized
94
+ end
25
95
  end
26
96
 
27
97
  class Fixnum
@@ -1,3 +1,3 @@
1
1
  module Bitswitch
2
- VERSION = "0.0.1"
2
+ VERSION = "0.0.2"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bitswitch
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.0.2
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors: