1 //
2 // Copyright (c) 2010-2018 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System;
8 using System.Collections.Generic;
9 using System.Linq;
10 
11 namespace Antmicro.Renode.Peripherals.Wireless.IEEE802_15_4
12 {
13     public class Address
14     {
Address(AddressingMode mode)15         public Address(AddressingMode mode)
16         {
17             if(mode != AddressingMode.ShortAddress && mode != AddressingMode.ExtendedAddress)
18             {
19                 throw new ArgumentException("Unsupported addressing mode");
20             }
21 
22             Bytes = new byte[mode.GetBytesLength()];
23         }
24 
Address(ArraySegment<byte> source)25         public Address(ArraySegment<byte> source)
26         {
27             if(source.Count != 2 && source.Count != 8)
28             {
29                 throw new ArgumentException("Unsupported address length");
30             }
31 
32             Bytes = source;
33         }
34 
Address(byte[] source)35         public Address(byte[] source)
36         {
37             if(source.Length != 2 && source.Length != 8)
38             {
39                 throw new ArgumentException("Unsupported address length");
40             }
41 
42             Bytes = source;
43         }
44 
SetByte(byte value, int offset)45         public void SetByte(byte value, int offset)
46         {
47             if(offset < 0 || offset >= Bytes.Count)
48             {
49                 throw new ArgumentOutOfRangeException();
50             }
51 
52             Bytes[offset] = value;
53         }
54 
GetHashCode()55         public override int GetHashCode()
56         {
57             return Bytes.GetHashCode();
58         }
59 
Equals(object obj)60         public override bool Equals(object obj)
61         {
62             var objAsAddress = obj as Address;
63             if(objAsAddress == null)
64             {
65                 return false;
66             }
67 
68             return objAsAddress.Bytes.SequenceEqual(Bytes);
69         }
70 
GetValue()71         public ulong GetValue()
72         {
73             switch(Bytes.Count)
74             {
75                 case 2:
76                     return (ulong)BitConverter.ToUInt16(Bytes.ToArray(), 0);
77                 case 8:
78                     return BitConverter.ToUInt64(Bytes.ToArray(), 0);
79                 default:
80                     throw new ArgumentException();
81             }
82         }
83 
84         public IList<byte> Bytes { get; private set; }
85         public bool IsShortBroadcast { get { return Bytes.Count == 2 && Bytes.All(x => x == 0xFF); } }
86     }
87 }
88 
89