WireEnd functionality split into ReadEnd and ReadWriteEnd
[Mograsim.git] / era.mi / src / era / mi / logic / wires / Wire.java
1 package era.mi.logic.wires;
2
3 import static era.mi.logic.types.Bit.U;
4 import static era.mi.logic.types.Bit.Z;
5
6 import java.util.ArrayList;
7 import java.util.List;
8
9 import era.mi.logic.Simulation;
10 import era.mi.logic.types.Bit;
11 import era.mi.logic.types.BitVector;
12 import era.mi.logic.types.BitVector.BitVectorMutator;
13
14 /**
15  * Represents an array of wires that can store n bits of information.
16  * 
17  * @author Fabian Stemmler
18  *
19  */
20 public class Wire
21 {
22         private BitVector values;
23         public final int travelTime;
24         private List<ReadEnd> attached = new ArrayList<ReadEnd>();
25         public final int length;
26         private List<ReadWriteEnd> inputs = new ArrayList<ReadWriteEnd>();
27
28         public Wire(int length, int travelTime)
29         {
30                 if (length < 1)
31                         throw new IllegalArgumentException(
32                                         String.format("Tried to create an array of wires with length %d, but a length of less than 1 makes no sense.", length));
33                 this.length = length;
34                 this.travelTime = travelTime;
35                 initValues();
36         }
37
38         private void initValues()
39         {
40                 values = U.toVector(length);
41         }
42
43         private void recalculateSingleInput()
44         {
45                 setNewValues(inputs.get(0).getInputValues());
46         }
47
48         private void recalculateMultipleInputs()
49         {
50                 BitVectorMutator mutator = BitVectorMutator.empty();
51                 for (ReadWriteEnd wireArrayEnd : inputs)
52                         mutator.join(wireArrayEnd.getInputValues());
53                 setNewValues(mutator.get());
54         }
55
56         private void setNewValues(BitVector newValues)
57         {
58                 if (values.equals(newValues))
59                         return;
60                 BitVector oldValues = values;
61                 values = newValues;
62                 notifyObservers(oldValues);
63         }
64
65         private void recalculate()
66         {
67                 switch (inputs.size())
68                 {
69                 case 0:
70                         return;
71                 case 1:
72                         recalculateSingleInput();
73                         break;
74                 default:
75                         recalculateMultipleInputs();
76                 }
77         }
78
79         /**
80          * The {@link Wire} is interpreted as an unsigned integer with n bits.
81          * 
82          * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the same
83          *         value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
84          * 
85          * @author Fabian Stemmler
86          */
87         public boolean hasNumericValue()
88         {
89                 for (Bit b : values)
90                 {
91                         if (b != Bit.ZERO && b != Bit.ONE)
92                                 return false;
93                 }
94                 return true;
95         }
96
97         /**
98          * The {@link Wire} is interpreted as an unsigned integer with n bits.
99          * 
100          * @return The unsigned value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
101          * 
102          * @author Fabian Stemmler
103          */
104         public long getUnsignedValue()
105         {
106                 long val = 0;
107                 long mask = 1;
108                 for (Bit bit : values)
109                 {
110                         switch (bit)
111                         {
112                         default:
113                         case Z:
114                         case X:
115                                 return 0; // TODO: Proper handling for getUnsignedValue(), if not all bits are 1 or 0;
116                         case ONE:
117                                 val |= mask;
118                                 break;
119                         case ZERO:
120                         }
121                         mask = mask << 1;
122                 }
123                 return val;
124         }
125
126         /**
127          * The {@link Wire} is interpreted as a signed integer with n bits.
128          * 
129          * @return The signed value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
130          * 
131          * @author Fabian Stemmler
132          */
133         public long getSignedValue()
134         {
135                 long val = getUnsignedValue();
136                 long mask = 1 << (length - 1);
137                 if ((mask & val) != 0)
138                 {
139                         int shifts = 64 - length;
140                         return (val << shifts) >> shifts;
141                 }
142                 return val;
143         }
144
145         public Bit getValue()
146         {
147                 return getValue(0);
148         }
149
150         public Bit getValue(int index)
151         {
152                 return values.getBit(index);
153         }
154
155         public BitVector getValues(int start, int end)
156         {
157                 return values.subVector(start, end);
158         }
159
160         public BitVector getValues()
161         {
162                 return values;
163         }
164
165         /**
166          * Adds an {@link WireObserver}, who will be notified when the value of the {@link Wire} is updated.
167          * 
168          * @param ob The {@link WireObserver} to be notified of changes.
169          * @return true if the given {@link WireObserver} was not already registered, false otherwise
170          * 
171          * @author Fabian Stemmler
172          */
173         private void attachEnd(ReadEnd end)
174         {
175                 attached.add(end);
176         }
177
178         private void detachEnd(ReadEnd end)
179         {
180                 attached.remove(end);
181         }
182
183         private void notifyObservers(BitVector oldValues)
184         {
185                 for (ReadEnd o : attached)
186                         o.update(oldValues);
187         }
188
189         /**
190          * Create and register a {@link ReadWriteEnd} object, which is tied to this {@link Wire}. This {@link ReadWriteEnd} can be written to.
191          */
192         public ReadWriteEnd createEnd()
193         {
194                 return new ReadWriteEnd();
195         }
196
197         /**
198          * Create a {@link ReadEnd} object, which is tied to this {@link Wire}. This {@link ReadEnd} cannot be written to.
199          */
200         public ReadEnd createReadOnlyEnd()
201         {
202                 return new ReadEnd();
203         }
204
205         private void registerInput(ReadWriteEnd toRegister)
206         {
207                 inputs.add(toRegister);
208         }
209
210         /**
211          * A {@link ReadEnd} feeds a constant signal into the {@link Wire} it is tied to. The combination of all inputs determines the
212          * {@link Wire}s final value. X dominates all other inputs Z does not affect the final value, unless there are no other inputs than Z 0
213          * and 1 turn into X when they are mixed
214          * 
215          * @author Fabian Stemmler
216          */
217         public class ReadEnd
218         {
219                 private List<WireObserver> observers = new ArrayList<WireObserver>();
220
221                 private ReadEnd()
222                 {
223                         super();
224                         Wire.this.attachEnd(this);
225                 }
226
227                 public void update(BitVector oldValues)
228                 {
229                         for (WireObserver ob : observers)
230                                 ob.update(this, oldValues);
231                 }
232
233                 /**
234                  * Included for convenient use on {@link Wire}s of length 1.
235                  * 
236                  * @return The value of bit 0.
237                  * 
238                  * @author Fabian Stemmler
239                  */
240                 public Bit getValue()
241                 {
242                         return Wire.this.getValue();
243                 }
244
245                 /**
246                  * @param index Index of the requested bit.
247                  * @return The value of the indexed bit.
248                  * 
249                  * @author Fabian Stemmler
250                  */
251                 public Bit getValue(int index)
252                 {
253                         return Wire.this.getValue(index);
254                 }
255
256                 /**
257                  * @param index Index of the requested bit.
258                  * @return The value of the indexed bit.
259                  * 
260                  * @author Fabian Stemmler
261                  */
262                 public BitVector getValues()
263                 {
264                         return Wire.this.getValues();
265                 }
266
267                 /**
268                  * @param start Start of the wanted segment. (inclusive)
269                  * @param end   End of the wanted segment. (exclusive)
270                  * @return The values of the segment of {@link Bit}s indexed.
271                  * 
272                  * @author Fabian Stemmler
273                  */
274                 public BitVector getValues(int start, int end)
275                 {
276                         return Wire.this.getValues(start, end);
277                 }
278
279                 /**
280                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
281                  * 
282                  * @return <code>true</code> if all bits are either <code>Bit.ONE</code> or <code>Bit.ZERO</code> (they do not all have to have the
283                  *         same value), not <code>Bit.X</code> or <code>Bit.Z</code>. <code>false</code> is returned otherwise.
284                  * 
285                  * @author Fabian Stemmler
286                  */
287                 public boolean hasNumericValue()
288                 {
289                         return Wire.this.hasNumericValue();
290                 }
291
292                 /**
293                  * The {@link Wire} is interpreted as an unsigned integer with n bits.
294                  * 
295                  * @return The unsigned value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
296                  * 
297                  * @author Fabian Stemmler
298                  */
299                 public long getUnsignedValue()
300                 {
301                         return Wire.this.getUnsignedValue();
302                 }
303
304                 /**
305                  * The {@link Wire} is interpreted as a signed integer with n bits.
306                  * 
307                  * @return The signed value of the {@link Wire}'s bits, where value 0 corresponds with 2^0, value 1 is 2^1 and so on.
308                  * 
309                  * @author Fabian Stemmler
310                  */
311                 public long getSignedValue()
312                 {
313                         return Wire.this.getSignedValue();
314                 }
315
316                 @Override
317                 public String toString()
318                 {
319                         return Wire.this.toString();
320                 }
321
322                 public void close()
323                 {
324                         inputs.remove(this);
325                         detachEnd(this);
326                         recalculate();
327                 }
328
329                 public int length()
330                 {
331                         return length;
332                 }
333
334                 public boolean addObserver(WireObserver ob)
335                 {
336                         return observers.add(ob);
337                 }
338
339                 public Wire getWire()
340                 {
341                         return Wire.this;
342                 }
343         }
344
345         public class ReadWriteEnd extends ReadEnd
346         {
347                 private boolean open;
348                 private BitVector inputValues;
349
350                 private ReadWriteEnd()
351                 {
352                         super();
353                         open = true;
354                         initValues();
355                         registerInput(this);
356                 }
357
358                 private void initValues()
359                 {
360                         inputValues = U.toVector(length);
361                 }
362
363                 /**
364                  * Sets the wires values. This takes up time, as specified by the {@link Wire}s travel time.
365                  * 
366                  * @param newValues The new values the wires should take on.
367                  * 
368                  * @author Fabian Stemmler
369                  */
370                 public void feedSignals(Bit... newValues)
371                 {
372                         feedSignals(BitVector.of(newValues));
373                 }
374
375                 public void feedSignals(BitVector newValues)
376                 {
377                         if (newValues.length() != length)
378                                 throw new IllegalArgumentException(
379                                                 String.format("Attempted to input %d bits instead of %d bits.", newValues.length(), length));
380                         if (!open)
381                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
382                         Simulation.TIMELINE.addEvent(e -> setValues(newValues), travelTime);
383                 }
384
385                 /**
386                  * Sets values of a subarray of wires. This takes up time, as specified by the {@link Wire}s travel time.
387                  * 
388                  * @param bitVector   The new values the wires should take on.
389                  * @param startingBit The first index of the subarray of wires.
390                  * 
391                  * @author Fabian Stemmler
392                  */
393                 public void feedSignals(int startingBit, BitVector bitVector)
394                 {
395                         if (!open)
396                                 throw new RuntimeException("Attempted to write to closed WireArrayEnd.");
397                         Simulation.TIMELINE.addEvent(e -> setValues(startingBit, bitVector), travelTime);
398                 }
399
400                 private void setValues(int startingBit, BitVector newValues)
401                 {
402                         // index check covered in equals
403                         if (!inputValues.equalsWithOffset(newValues, startingBit))
404                         {
405                                 Bit[] vals = inputValues.getBits();
406                                 System.arraycopy(newValues.getBits(), 0, vals, startingBit, newValues.length());
407                                 inputValues = BitVector.of(vals);
408                                 Wire.this.recalculate();
409                         }
410                 }
411
412                 private void setValues(BitVector newValues)
413                 {
414                         if (inputValues.equals(newValues))
415                                 return;
416                         inputValues = newValues;
417                         Wire.this.recalculate();
418                 }
419
420                 /**
421                  * @return The value (of bit 0) the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
422                  */
423                 public Bit getInputValue()
424                 {
425                         return getInputValue(0);
426                 }
427
428                 /**
429                  * @return The value which the {@link ReadEnd} is currently feeding into the associated {@link Wire} at the indexed {@link Bit}.
430                  */
431                 public Bit getInputValue(int index)
432                 {
433                         return inputValues.getBit(index);
434                 }
435
436                 /**
437                  * @return A copy (safe to modify) of the values the {@link ReadEnd} is currently feeding into the associated {@link Wire}.
438                  */
439                 public BitVector getInputValues()
440                 {
441                         return getInputValues(0, length);
442                 }
443
444                 public BitVector getInputValues(int start, int end)
445                 {
446                         return inputValues.subVector(start, end);
447                 }
448
449                 /**
450                  * {@link ReadEnd} now feeds Z into the associated {@link Wire}.
451                  */
452                 public void clearSignals()
453                 {
454                         feedSignals(Z.toVector(length));
455                 }
456
457                 public BitVector wireValuesExcludingMe()
458                 {
459                         BitVectorMutator mutator = BitVectorMutator.empty();
460                         for (ReadWriteEnd wireEnd : inputs)
461                         {
462                                 if (wireEnd == this)
463                                         continue;
464                                 mutator.join(wireEnd.inputValues);
465                         }
466                         return mutator.get();
467                 }
468
469                 @Override
470                 public String toString()
471                 {
472                         return inputValues.toString();
473                 }
474         }
475
476         @Override
477         public String toString()
478         {
479                 return String.format("wire 0x%08x value: %s inputs: %s", hashCode(), values, inputs);
480                 // Arrays.toString(values), inputs.stream().map(i -> Arrays.toString(i.inputValues)).reduce((s1, s2) -> s1 + s2)
481         }
482
483         public static ReadEnd[] extractEnds(Wire[] w)
484         {
485                 ReadEnd[] inputs = new ReadEnd[w.length];
486                 for (int i = 0; i < w.length; i++)
487                         inputs[i] = w[i].createEnd();
488                 return inputs;
489         }
490 }