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.Collections.Generic;
8 using System.Linq;
9 using System.Text;
10 using Antmicro.Renode.Utilities;
11 
12 namespace Antmicro.Renode.Core.USB
13 {
14     public class USBString : DescriptorProvider
15     {
USBString()16         static USBString()
17         {
18             Empty = new USBString(string.Empty, 0);
19             strings = new List<USBString>();
20         }
21 
FromString(string s)22         public static USBString FromString(string s)
23         {
24             if(string.IsNullOrWhiteSpace(s))
25             {
26                 return Empty;
27             }
28 
29             var usbString = strings.FirstOrDefault(x => x.Value == s);
30             if(usbString == null)
31             {
32                 usbString = new USBString(s, checked((byte)(strings.Count + 1)));
33                 strings.Add(usbString);
34             }
35 
36             return usbString;
37         }
38 
FromId(int id)39         public static USBString FromId(int id)
40         {
41             if(id <= 0 || id > strings.Count)
42             {
43                 return null;
44             }
45             return strings[id - 1];
46         }
47 
GetSupportedLanguagesDescriptor()48         public static BitStream GetSupportedLanguagesDescriptor()
49         {
50             // for now we hardcode just one language
51             return new BitStream()
52                 .Append(4)
53                 .Append((byte)DescriptorType.String)
54                 .Append((short)LanguageCode.EnglishUnitedStates);
55         }
56 
57         public static USBString Empty { get; }
58 
59         private static List<USBString> strings;
60 
61         public byte Index { get; }
62         public string Value { get; }
63 
64         public override int DescriptorLength => 2 + Encoding.Unicode.GetByteCount(Value);
65 
USBString(string value, byte id)66         protected USBString(string value, byte id) : base((byte)DescriptorType.String)
67         {
68             Value = value;
69             Index = id;
70         }
71 
FillDescriptor(BitStream buffer)72         protected override void FillDescriptor(BitStream buffer)
73         {
74             var stringAsUnicodeBytes = Encoding.Unicode.GetBytes(Value);
75             foreach(var b in stringAsUnicodeBytes)
76             {
77                 buffer.Append(b);
78             }
79         }
80 
81         public enum LanguageCode : short
82         {
83             EnglishUnitedStates = 0x0409
84         }
85     }
86 }