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