diff options
| author | Luke Pulverenti <luke.pulverenti@gmail.com> | 2017-07-07 23:12:21 -0400 |
|---|---|---|
| committer | Luke Pulverenti <luke.pulverenti@gmail.com> | 2017-07-07 23:12:21 -0400 |
| commit | 0d10dfe4718dc6875a20fc7c0c3d0b8b982cf3d8 (patch) | |
| tree | ed2715c5fec56ad665379d4f4d694985bb8de4e7 /Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen | |
| parent | a30e22c3a2eb9d7460f5a98d4e9eb946201b9658 (diff) | |
update sharpcifs
Diffstat (limited to 'Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen')
54 files changed, 3063 insertions, 3454 deletions
diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs index 45e7e21449..2868a840ad 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/AbstractMap.cs @@ -6,159 +6,146 @@ using System.Linq; namespace SharpCifs.Util.Sharpen { public abstract class AbstractMap<T, TU> : IDictionary<T, TU> - { - public virtual void Clear() - { - EntrySet().Clear(); - } - - public virtual bool ContainsKey(object name) - { - return EntrySet().Any(p => p.Key.Equals((T)name)); - } - - public abstract ICollection<KeyValuePair<T, TU>> EntrySet(); - - public virtual TU Get(object key) - { - return EntrySet().Where(p => p.Key.Equals(key)).Select(p => p.Value).FirstOrDefault(); - } - - protected virtual IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator() - { - return EntrySet().GetEnumerator(); - } - - public virtual bool IsEmpty() - { - return !EntrySet().Any(); - } - - public virtual TU Put(T key, TU value) - { - throw new NotSupportedException(); - } - - public virtual TU Remove(object key) - { - Iterator<TU> iterator = EntrySet() as Iterator<TU>; - if (iterator == null) - { - throw new NotSupportedException(); - } - while (iterator.HasNext()) - { - TU local = iterator.Next(); - if (local.Equals((T)key)) - { - iterator.Remove(); - return local; - } - } - return default(TU); - } - - void ICollection<KeyValuePair<T, TU>>.Add(KeyValuePair<T, TU> item) - { - Put(item.Key, item.Value); - } - - bool ICollection<KeyValuePair<T, TU>>.Contains(KeyValuePair<T, TU> item) - { - throw new NotImplementedException(); - } - - void ICollection<KeyValuePair<T, TU>>.CopyTo(KeyValuePair<T, TU>[] array, int arrayIndex) - { - EntrySet().CopyTo(array, arrayIndex); - } - - bool ICollection<KeyValuePair<T, TU>>.Remove(KeyValuePair<T, TU> item) - { - Remove(item.Key); - return true; - } - - void IDictionary<T, TU>.Add(T key, TU value) - { - Put(key, value); - } - - bool IDictionary<T, TU>.ContainsKey(T key) - { - return ContainsKey(key); - } - - bool IDictionary<T, TU>.Remove(T key) - { - if (ContainsKey(key)) - { - Remove(key); - return true; - } - return false; - } - - bool IDictionary<T, TU>.TryGetValue(T key, out TU value) - { - if (ContainsKey(key)) - { - value = Get(key); - return true; - } - value = default(TU); - return false; - } - - IEnumerator<KeyValuePair<T, TU>> IEnumerable<KeyValuePair<T, TU>>.GetEnumerator() - { - return InternalGetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return InternalGetEnumerator(); - } - - public virtual int Count - { - get { return EntrySet().Count; } - } - - public TU this[T key] - { - get { return Get(key); } - set { Put(key, value); } - } - - public virtual IEnumerable<T> Keys - { - get { return EntrySet().Select(p => p.Key); } - } - - int ICollection<KeyValuePair<T, TU>>.Count - { - get { return Count; } - } - - bool ICollection<KeyValuePair<T, TU>>.IsReadOnly - { - get { return false; } - } - - ICollection<T> IDictionary<T, TU>.Keys - { - get { return Keys.ToList(); } - } - - ICollection<TU> IDictionary<T, TU>.Values - { - get { return Values.ToList(); } - } - - public virtual IEnumerable<TU> Values - { - get { return EntrySet().Select(p => p.Value); } - } - } + { + public virtual void Clear () + { + EntrySet ().Clear (); + } + + public virtual bool ContainsKey (object name) + { + return EntrySet ().Any (p => p.Key.Equals ((T)name)); + } + + public abstract ICollection<KeyValuePair<T, TU>> EntrySet (); + + public virtual TU Get (object key) + { + return EntrySet ().Where (p => p.Key.Equals (key)).Select (p => p.Value).FirstOrDefault (); + } + + protected virtual IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator () + { + return EntrySet ().GetEnumerator (); + } + + public virtual bool IsEmpty () + { + return !EntrySet ().Any (); + } + + public virtual TU Put (T key, TU value) + { + throw new NotSupportedException (); + } + + public virtual TU Remove (object key) + { + Iterator<TU> iterator = EntrySet () as Iterator<TU>; + if (iterator == null) { + throw new NotSupportedException (); + } + while (iterator.HasNext ()) { + TU local = iterator.Next (); + if (local.Equals ((T)key)) { + iterator.Remove (); + return local; + } + } + return default(TU); + } + + void ICollection<KeyValuePair<T, TU>>.Add (KeyValuePair<T, TU> item) + { + Put (item.Key, item.Value); + } + + bool ICollection<KeyValuePair<T, TU>>.Contains (KeyValuePair<T, TU> item) + { + throw new NotImplementedException (); + } + + void ICollection<KeyValuePair<T, TU>>.CopyTo (KeyValuePair<T, TU>[] array, int arrayIndex) + { + EntrySet ().CopyTo (array, arrayIndex); + } + + bool ICollection<KeyValuePair<T, TU>>.Remove (KeyValuePair<T, TU> item) + { + Remove (item.Key); + return true; + } + + void IDictionary<T, TU>.Add (T key, TU value) + { + Put (key, value); + } + + bool IDictionary<T, TU>.ContainsKey (T key) + { + return ContainsKey (key); + } + + bool IDictionary<T, TU>.Remove (T key) + { + if (ContainsKey (key)) { + Remove (key); + return true; + } + return false; + } + + bool IDictionary<T, TU>.TryGetValue (T key, out TU value) + { + if (ContainsKey (key)) { + value = Get (key); + return true; + } + value = default(TU); + return false; + } + + IEnumerator<KeyValuePair<T, TU>> IEnumerable<KeyValuePair<T, TU>>.GetEnumerator () + { + return InternalGetEnumerator (); + } + + IEnumerator IEnumerable.GetEnumerator () + { + return InternalGetEnumerator (); + } + + public virtual int Count { + get { return EntrySet ().Count; } + } + + public TU this[T key] { + get { return Get (key); } + set { Put (key, value); } + } + + public virtual IEnumerable<T> Keys { + get { return EntrySet ().Select (p => p.Key); } + } + + int ICollection<KeyValuePair<T, TU>>.Count { + get { return Count; } + } + + bool ICollection<KeyValuePair<T, TU>>.IsReadOnly { + get { return false; } + } + + ICollection<T> IDictionary<T, TU>.Keys { + get { return Keys.ToList (); } + } + + ICollection<TU> IDictionary<T, TU>.Values { + get { return Values.ToList (); } + } + + public virtual IEnumerable<TU> Values { + get { return EntrySet ().Select (p => p.Value); } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs index 4771f4fa5d..b3a0a85fa8 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Arrays.cs @@ -5,57 +5,55 @@ using System.Linq; namespace SharpCifs.Util.Sharpen { public class Arrays - { - public static List<T> AsList<T>(params T[] array) - { - return array.ToList(); - } - - public static bool Equals<T>(T[] a1, T[] a2) - { - if (a1.Length != a2.Length) - { - return false; - } - return !a1.Where((t, i) => !t.Equals(a2[i])).Any(); - } - - public static void Fill<T>(T[] array, T val) - { - Fill(array, 0, array.Length, val); - } - - public static void Fill<T>(T[] array, int start, int end, T val) - { - for (int i = start; i < end; i++) - { - array[i] = val; - } - } - - public static void Sort(string[] array) - { - Array.Sort(array, (s1, s2) => string.CompareOrdinal(s1, s2)); - } - - public static void Sort<T>(T[] array) - { - Array.Sort(array); - } - - public static void Sort<T>(T[] array, IComparer<T> c) - { - Array.Sort(array, c); - } - - public static void Sort<T>(T[] array, int start, int count) - { - Array.Sort(array, start, count); - } - - public static void Sort<T>(T[] array, int start, int count, IComparer<T> c) - { - Array.Sort(array, start, count, c); - } - } + { + public static List<T> AsList<T> (params T[] array) + { + return array.ToList (); + } + + public static bool Equals<T> (T[] a1, T[] a2) + { + if (a1.Length != a2.Length) { + return false; + } + return !a1.Where((t, i) => !t.Equals(a2[i])).Any(); + } + + public static void Fill<T> (T[] array, T val) + { + Fill (array, 0, array.Length, val); + } + + public static void Fill<T> (T[] array, int start, int end, T val) + { + for (int i = start; i < end; i++) { + array[i] = val; + } + } + + public static void Sort (string[] array) + { + Array.Sort (array, (s1,s2) => string.CompareOrdinal (s1,s2)); + } + + public static void Sort<T> (T[] array) + { + Array.Sort (array); + } + + public static void Sort<T> (T[] array, IComparer<T> c) + { + Array.Sort (array, c); + } + + public static void Sort<T> (T[] array, int start, int count) + { + Array.Sort (array, start, count); + } + + public static void Sort<T> (T[] array, int start, int count, IComparer<T> c) + { + Array.Sort (array, start, count, c); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs index 4f29b0e9bf..b3824b0d2c 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedReader.cs @@ -3,9 +3,9 @@ using System.IO; namespace SharpCifs.Util.Sharpen { public class BufferedReader : StreamReader - { - public BufferedReader(InputStreamReader r) : base(r.BaseStream) - { - } - } + { + public BufferedReader (InputStreamReader r) : base(r.BaseStream) + { + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs index b55dbae24f..64a45915ad 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/BufferedWriter.cs @@ -28,31 +28,31 @@ using System.IO; namespace SharpCifs.Util.Sharpen { - public class BufferedWriter - { - StreamWriter _writer; - - public BufferedWriter(StreamWriter w) - { - _writer = w; - } - - public void Write(string s) - { - _writer.Write(s); - } - - public void NewLine() - { - _writer.WriteLine(); - } - - public void Close() - { + public class BufferedWriter + { + StreamWriter _writer; + + public BufferedWriter (StreamWriter w) + { + _writer = w; + } + + public void Write (string s) + { + _writer.Write (s); + } + + public void NewLine () + { + _writer.WriteLine (); + } + + public void Close () + { //Stream.`Close` method deleted - //_writer.Close (); + //_writer.Close (); _writer.Dispose(); } - } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs index 55b7c69c23..76ca2dc956 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharBuffer.cs @@ -1,19 +1,19 @@ namespace SharpCifs.Util.Sharpen { internal class CharBuffer : CharSequence - { - internal string Wrapped; + { + internal string Wrapped; - public override string ToString() - { - return Wrapped; - } + public override string ToString () + { + return Wrapped; + } - public static CharBuffer Wrap(string str) - { - CharBuffer buffer = new CharBuffer(); - buffer.Wrapped = str; - return buffer; - } - } + public static CharBuffer Wrap (string str) + { + CharBuffer buffer = new CharBuffer (); + buffer.Wrapped = str; + return buffer; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs index 52d5e4710c..fa2acf7bdc 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/CharSequence.cs @@ -2,31 +2,31 @@ using System.Text; namespace SharpCifs.Util.Sharpen { - public class CharSequence - { - public static implicit operator CharSequence(string str) - { - return new StringCharSequence(str); - } - - public static implicit operator CharSequence(StringBuilder str) - { - return new StringCharSequence(str.ToString()); - } - } - - class StringCharSequence : CharSequence - { - string _str; - - public StringCharSequence(string str) - { - this._str = str; - } - - public override string ToString() - { - return _str; - } - } + public class CharSequence + { + public static implicit operator CharSequence (string str) + { + return new StringCharSequence (str); + } + + public static implicit operator CharSequence (StringBuilder str) + { + return new StringCharSequence (str.ToString ()); + } + } + + class StringCharSequence: CharSequence + { + string _str; + + public StringCharSequence (string str) + { + this._str = str; + } + + public override string ToString () + { + return _str; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs index 0a531c66cb..4432e62fb0 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Collections.cs @@ -5,47 +5,45 @@ using System.Collections.ObjectModel; namespace SharpCifs.Util.Sharpen { internal static class Collections<T> - { - static readonly IList<T> Empty = new T[0]; - public static IList<T> EmptySet - { - get { return Empty; } - } - - } - - public static class Collections - { - public static bool AddAll<T>(ICollection<T> list, IEnumerable toAdd) - { - foreach (T t in toAdd) - list.Add(t); - return true; - } - - public static TV Remove<TK, TV>(IDictionary<TK, TV> map, TK toRemove) where TK : class - { - TV local; - if (map.TryGetValue(toRemove, out local)) - { - map.Remove(toRemove); - return local; - } - return default(TV); - } - - - public static T[] ToArray<T>(ICollection<T> list) - { - T[] array = new T[list.Count]; - list.CopyTo(array, 0); - return array; - } + { + static readonly IList<T> Empty = new T [0]; + public static IList<T> EmptySet { + get { return Empty; } + } + + } + + public static class Collections + { + public static bool AddAll<T> (ICollection<T> list, IEnumerable toAdd) + { + foreach (T t in toAdd) + list.Add (t); + return true; + } + + public static TV Remove<TK, TV> (IDictionary<TK, TV> map, TK toRemove) where TK : class + { + TV local; + if (map.TryGetValue (toRemove, out local)) { + map.Remove (toRemove); + return local; + } + return default(TV); + } + + + public static T[] ToArray<T> (ICollection<T> list) + { + T[] array = new T[list.Count]; + list.CopyTo (array, 0); + return array; + } public static T[] ToArray<T>(List<object> list) { T[] array = new T[list.Count]; - for (int c = 0; c < list.Count; c++) + for(int c = 0; c < list.Count; c++) { array[c] = (T)list[c]; } @@ -54,97 +52,95 @@ namespace SharpCifs.Util.Sharpen } - public static TU[] ToArray<T, TU>(ICollection<T> list, TU[] res) where T : TU - { - if (res.Length < list.Count) - res = new TU[list.Count]; - - int n = 0; - foreach (T t in list) - res[n++] = t; - - if (res.Length > list.Count) - res[list.Count] = default(T); - return res; - } - - public static IDictionary<TK, TV> EmptyMap<TK, TV>() - { - return new Dictionary<TK, TV>(); - } - - public static IList<T> EmptyList<T>() - { - return Collections<T>.EmptySet; - } - - public static ICollection<T> EmptySet<T>() - { - return Collections<T>.EmptySet; - } - - public static IList<T> NCopies<T>(int n, T elem) - { - List<T> list = new List<T>(n); - while (n-- > 0) - { - list.Add(elem); - } - return list; - } - - public static void Reverse<T>(IList<T> list) - { - int end = list.Count - 1; - int index = 0; - while (index < end) - { - T tmp = list[index]; - list[index] = list[end]; - list[end] = tmp; - ++index; - --end; - } - } - - public static ICollection<T> Singleton<T>(T item) - { - List<T> list = new List<T>(1); - list.Add(item); - return list; - } - - public static IList<T> SingletonList<T>(T item) - { - List<T> list = new List<T>(1); - list.Add(item); - return list; - } - - public static IList<T> SynchronizedList<T>(IList<T> list) - { - return new SynchronizedList<T>(list); - } - - public static ICollection<T> UnmodifiableCollection<T>(ICollection<T> list) - { - return list; - } - - public static IList<T> UnmodifiableList<T>(IList<T> list) - { - return new ReadOnlyCollection<T>(list); - } - - public static ICollection<T> UnmodifiableSet<T>(ICollection<T> list) - { - return list; - } - - public static IDictionary<TK, TV> UnmodifiableMap<TK, TV>(IDictionary<TK, TV> dict) - { - return dict; - } + public static TU[] ToArray<T,TU> (ICollection<T> list, TU[] res) where T:TU + { + if (res.Length < list.Count) + res = new TU [list.Count]; + + int n = 0; + foreach (T t in list) + res [n++] = t; + + if (res.Length > list.Count) + res [list.Count] = default (T); + return res; + } + + public static IDictionary<TK,TV> EmptyMap<TK,TV> () + { + return new Dictionary<TK,TV> (); + } + + public static IList<T> EmptyList<T> () + { + return Collections<T>.EmptySet; + } + + public static ICollection<T> EmptySet<T> () + { + return Collections<T>.EmptySet; + } + + public static IList<T> NCopies<T> (int n, T elem) + { + List<T> list = new List<T> (n); + while (n-- > 0) { + list.Add (elem); + } + return list; + } + + public static void Reverse<T> (IList<T> list) + { + int end = list.Count - 1; + int index = 0; + while (index < end) { + T tmp = list [index]; + list [index] = list [end]; + list [end] = tmp; + ++index; + --end; + } + } + + public static ICollection<T> Singleton<T> (T item) + { + List<T> list = new List<T> (1); + list.Add (item); + return list; + } + + public static IList<T> SingletonList<T> (T item) + { + List<T> list = new List<T> (1); + list.Add (item); + return list; + } + + public static IList<T> SynchronizedList<T> (IList<T> list) + { + return new SynchronizedList<T> (list); + } + + public static ICollection<T> UnmodifiableCollection<T> (ICollection<T> list) + { + return list; + } + + public static IList<T> UnmodifiableList<T> (IList<T> list) + { + return new ReadOnlyCollection<T> (list); + } + + public static ICollection<T> UnmodifiableSet<T> (ICollection<T> list) + { + return list; + } + + public static IDictionary<TK,TV> UnmodifiableMap<TK,TV> (IDictionary<TK,TV> dict) + { + return dict; + } } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs index c719446e8a..7f464ad362 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ConcurrentHashMap.cs @@ -3,131 +3,120 @@ using System.Collections.Generic; namespace SharpCifs.Util.Sharpen { internal class ConcurrentHashMap<T, TU> : AbstractMap<T, TU>, IConcurrentMap<T, TU> - { - private Dictionary<T, TU> _table; - - public ConcurrentHashMap() - { - _table = new Dictionary<T, TU>(); - } - - public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) - { - _table = new Dictionary<T, TU>(initialCapacity); - } - - public override void Clear() - { - lock (_table) - { - _table = new Dictionary<T, TU>(); - } - } - - public override bool ContainsKey(object name) - { - return _table.ContainsKey((T)name); - } - - public override ICollection<KeyValuePair<T, TU>> EntrySet() - { - return this; - } - - public override TU Get(object key) - { - TU local; - _table.TryGetValue((T)key, out local); - return local; - } - - protected override IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator() - { - return _table.GetEnumerator(); - } - - public override bool IsEmpty() - { - return _table.Count == 0; - } - - public override TU Put(T key, TU value) - { - lock (_table) - { - TU old = Get(key); - Dictionary<T, TU> newTable = new Dictionary<T, TU>(_table); - newTable[key] = value; - _table = newTable; - return old; - } - } - - public TU PutIfAbsent(T key, TU value) - { - lock (_table) - { - if (!ContainsKey(key)) - { - Dictionary<T, TU> newTable = new Dictionary<T, TU>(_table); - newTable[key] = value; - _table = newTable; - return value; - } - return Get(key); - } - } - - public override TU Remove(object key) - { - lock (_table) - { - TU old = Get((T)key); - Dictionary<T, TU> newTable = new Dictionary<T, TU>(_table); - newTable.Remove((T)key); - _table = newTable; - return old; - } - } - - public bool Remove(object key, object value) - { - lock (_table) - { - if (ContainsKey(key) && value.Equals(Get(key))) - { - Dictionary<T, TU> newTable = new Dictionary<T, TU>(_table); - newTable.Remove((T)key); - _table = newTable; - return true; - } - return false; - } - } - - public bool Replace(T key, TU oldValue, TU newValue) - { - lock (_table) - { - if (ContainsKey(key) && oldValue.Equals(Get(key))) - { - Dictionary<T, TU> newTable = new Dictionary<T, TU>(_table); - newTable[key] = newValue; - _table = newTable; - return true; - } - return false; - } - } - - public override IEnumerable<T> Keys - { - get { return _table.Keys; } - } - - public override IEnumerable<TU> Values - { - get { return _table.Values; } - } - } + { + private Dictionary<T, TU> _table; + + public ConcurrentHashMap () + { + _table = new Dictionary<T, TU> (); + } + + public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel) + { + _table = new Dictionary<T, TU> (initialCapacity); + } + + public override void Clear () + { + lock (_table) { + _table = new Dictionary<T, TU> (); + } + } + + public override bool ContainsKey (object name) + { + return _table.ContainsKey ((T)name); + } + + public override ICollection<KeyValuePair<T, TU>> EntrySet () + { + return this; + } + + public override TU Get (object key) + { + TU local; + _table.TryGetValue ((T)key, out local); + return local; + } + + protected override IEnumerator<KeyValuePair<T, TU>> InternalGetEnumerator () + { + return _table.GetEnumerator (); + } + + public override bool IsEmpty () + { + return _table.Count == 0; + } + + public override TU Put (T key, TU value) + { + lock (_table) { + TU old = Get (key); + Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table); + newTable[key] = value; + _table = newTable; + return old; + } + } + + public TU PutIfAbsent (T key, TU value) + { + lock (_table) { + if (!ContainsKey (key)) { + Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table); + newTable[key] = value; + _table = newTable; + return value; + } + return Get (key); + } + } + + public override TU Remove (object key) + { + lock (_table) { + TU old = Get ((T)key); + Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table); + newTable.Remove ((T)key); + _table = newTable; + return old; + } + } + + public bool Remove (object key, object value) + { + lock (_table) { + if (ContainsKey (key) && value.Equals (Get (key))) { + Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table); + newTable.Remove ((T)key); + _table = newTable; + return true; + } + return false; + } + } + + public bool Replace (T key, TU oldValue, TU newValue) + { + lock (_table) { + if (ContainsKey (key) && oldValue.Equals (Get (key))) { + Dictionary<T, TU> newTable = new Dictionary<T, TU> (_table); + newTable[key] = newValue; + _table = newTable; + return true; + } + return false; + } + } + + public override IEnumerable<T> Keys { + get { return _table.Keys; } + } + + public override IEnumerable<TU> Values { + get { return _table.Values; } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs index 7fa9b75b2b..9a3b7ec4a3 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/DateFormat.cs @@ -3,35 +3,35 @@ using System.Globalization; namespace SharpCifs.Util.Sharpen { - public abstract class DateFormat - { - public const int Default = 2; - - public static DateFormat GetDateTimeInstance(int dateStyle, int timeStyle) - { - return GetDateTimeInstance(dateStyle, timeStyle, CultureInfo.CurrentCulture); - } - - public static DateFormat GetDateTimeInstance(int dateStyle, int timeStyle, CultureInfo aLocale) - { - return new SimpleDateFormat(aLocale.DateTimeFormat.FullDateTimePattern, aLocale); - } - - TimeZoneInfo _timeZone; - - public abstract DateTime Parse(string value); - - public TimeZoneInfo GetTimeZone() - { - return _timeZone; - } - - public void SetTimeZone(TimeZoneInfo timeZone) - { - this._timeZone = timeZone; - } - - public abstract string Format(DateTime time); - } + public abstract class DateFormat + { + public const int Default = 2; + + public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle) + { + return GetDateTimeInstance (dateStyle, timeStyle, CultureInfo.CurrentCulture); + } + + public static DateFormat GetDateTimeInstance (int dateStyle, int timeStyle, CultureInfo aLocale) + { + return new SimpleDateFormat (aLocale.DateTimeFormat.FullDateTimePattern, aLocale); + } + + TimeZoneInfo _timeZone; + + public abstract DateTime Parse (string value); + + public TimeZoneInfo GetTimeZone () + { + return _timeZone; + } + + public void SetTimeZone (TimeZoneInfo timeZone) + { + this._timeZone = timeZone; + } + + public abstract string Format (DateTime time); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs index e6fbdd411e..f8efdde2a7 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/EnumeratorWrapper.cs @@ -4,55 +4,52 @@ using System.Collections.Generic; namespace SharpCifs.Util.Sharpen { internal class EnumeratorWrapper<T> : Iterator<T> - { - object _collection; - IEnumerator<T> _e; - T _lastVal; - bool _more; - bool _copied; + { + object _collection; + IEnumerator<T> _e; + T _lastVal; + bool _more; + bool _copied; - public EnumeratorWrapper(object collection, IEnumerator<T> e) - { - this._e = e; - this._collection = collection; - _more = e.MoveNext(); - } + public EnumeratorWrapper (object collection, IEnumerator<T> e) + { + this._e = e; + this._collection = collection; + _more = e.MoveNext (); + } - public override bool HasNext() - { - return _more; - } + public override bool HasNext () + { + return _more; + } - public override T Next() - { - if (!_more) - throw new NoSuchElementException(); - _lastVal = _e.Current; - _more = _e.MoveNext(); - return _lastVal; - } + public override T Next () + { + if (!_more) + throw new NoSuchElementException (); + _lastVal = _e.Current; + _more = _e.MoveNext (); + return _lastVal; + } - public override void Remove() - { - ICollection<T> col = _collection as ICollection<T>; - if (col == null) - { - throw new NotSupportedException(); - } - if (_more && !_copied) - { - // Read the remaining elements, since the current enumerator - // will be invalid after removing the element - List<T> remaining = new List<T>(); - do - { - remaining.Add(_e.Current); - } while (_e.MoveNext()); - _e = remaining.GetEnumerator(); - _e.MoveNext(); - _copied = true; - } - col.Remove(_lastVal); - } - } + public override void Remove () + { + ICollection<T> col = _collection as ICollection<T>; + if (col == null) { + throw new NotSupportedException (); + } + if (_more && !_copied) { + // Read the remaining elements, since the current enumerator + // will be invalid after removing the element + List<T> remaining = new List<T> (); + do { + remaining.Add (_e.Current); + } while (_e.MoveNext ()); + _e = remaining.GetEnumerator (); + _e.MoveNext (); + _copied = true; + } + col.Remove (_lastVal); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs index 4fd8e3bfa2..ec88b28496 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Exceptions.cs @@ -28,191 +28,190 @@ using System; namespace SharpCifs.Util.Sharpen { - public class VirtualMachineError : Error - { - } - - public class StackOverflowError : VirtualMachineError - { - } - - public class BrokenBarrierException : Exception - { - } - - internal class BufferUnderflowException : Exception - { - } - - public class CharacterCodingException : Exception - { - } - - public class DataFormatException : Exception - { - } - - public class EofException : Exception - { - public EofException() - { - } - - public EofException(string msg) : base(msg) - { - } - } - - public class Error : Exception - { - public Error() - { - } - - public Error(Exception ex) : base("Runtime Exception", ex) - { - } - - public Error(string msg) : base(msg) - { - } - - public Error(string msg, Exception ex) : base(msg, ex) - { - } - } - - public class ExecutionException : Exception - { - public ExecutionException(Exception inner) : base("Execution failed", inner) - { - } - } - - public class InstantiationException : Exception - { - } - - public class InterruptedIoException : Exception - { - public InterruptedIoException(string msg) : base(msg) - { - } - } - - public class MissingResourceException : Exception - { - } - - public class NoSuchAlgorithmException : Exception - { - } - - public class NoSuchElementException : Exception - { - } - - internal class NoSuchMethodException : Exception - { - } - - internal class OverlappingFileLockException : Exception - { - } - - public class ParseException : Exception - { - public ParseException() - { - } - - public ParseException(string msg, int errorOffset) - : base(string.Format("Msg: {0}. Error Offset: {1}", msg, errorOffset)) - { - } - } - - public class RuntimeException : Exception - { - public RuntimeException() - { - } - - public RuntimeException(Exception ex) : base("Runtime Exception", ex) - { - } - - public RuntimeException(string msg) : base(msg) - { - } - - public RuntimeException(string msg, Exception ex) : base(msg, ex) - { - } - } - - internal class StringIndexOutOfBoundsException : Exception - { - } - - public class UnknownHostException : Exception - { - public UnknownHostException() - { - } - - public UnknownHostException(string message) : base(message) - { - - } - - public UnknownHostException(Exception ex) : base("Host not found", ex) - { - } - } - - public class UnsupportedEncodingException : Exception - { - } - - internal class UriSyntaxException : Exception - { - public UriSyntaxException(string s, string msg) : base(s + " " + msg) - { - } - } - - internal class ZipException : Exception - { - } - - public class GitException : Exception - { - } - - public class ConnectException : Exception - { - public ConnectException(string msg) : base(msg) - { - } - } - - class KeyManagementException : Exception - { - } - - class IllegalCharsetNameException : Exception - { - public IllegalCharsetNameException(string msg) : base(msg) - { - } - } - - class UnsupportedCharsetException : Exception - { - public UnsupportedCharsetException(string msg) : base(msg) - { - } - } + public class VirtualMachineError : Error + { + } + + public class StackOverflowError : VirtualMachineError + { + } + + public class BrokenBarrierException : Exception + { + } + + internal class BufferUnderflowException : Exception + { + } + + public class CharacterCodingException : Exception + { + } + + public class DataFormatException : Exception + { + } + + public class EofException : Exception + { + public EofException () + { + } + + public EofException (string msg) : base(msg) + { + } + } + + public class Error : Exception + { + public Error () + { + } + + public Error (Exception ex) : base("Runtime Exception", ex) + { + } + + public Error (string msg) : base(msg) + { + } + + public Error (string msg, Exception ex) : base(msg, ex) + { + } + } + + public class ExecutionException : Exception + { + public ExecutionException (Exception inner): base ("Execution failed", inner) + { + } + } + + public class InstantiationException : Exception + { + } + + public class InterruptedIoException : Exception + { + public InterruptedIoException (string msg) : base(msg) + { + } + } + + public class MissingResourceException : Exception + { + } + + public class NoSuchAlgorithmException : Exception + { + } + + public class NoSuchElementException : Exception + { + } + + internal class NoSuchMethodException : Exception + { + } + + internal class OverlappingFileLockException : Exception + { + } + + public class ParseException : Exception + { + public ParseException () + { + } + + public ParseException (string msg, int errorOffset) : base(string.Format ("Msg: {0}. Error Offset: {1}", msg, errorOffset)) + { + } + } + + public class RuntimeException : Exception + { + public RuntimeException () + { + } + + public RuntimeException (Exception ex) : base("Runtime Exception", ex) + { + } + + public RuntimeException (string msg) : base(msg) + { + } + + public RuntimeException (string msg, Exception ex) : base(msg, ex) + { + } + } + + internal class StringIndexOutOfBoundsException : Exception + { + } + + public class UnknownHostException : Exception + { + public UnknownHostException () + { + } + + public UnknownHostException(string message) : base(message) + { + + } + + public UnknownHostException (Exception ex): base ("Host not found", ex) + { + } + } + + public class UnsupportedEncodingException : Exception + { + } + + internal class UriSyntaxException : Exception + { + public UriSyntaxException (string s, string msg) : base(s + " " + msg) + { + } + } + + internal class ZipException : Exception + { + } + + public class GitException : Exception + { + } + + public class ConnectException: Exception + { + public ConnectException (string msg): base (msg) + { + } + } + + class KeyManagementException: Exception + { + } + + class IllegalCharsetNameException: Exception + { + public IllegalCharsetNameException (string msg): base (msg) + { + } + } + + class UnsupportedCharsetException: Exception + { + public UnsupportedCharsetException (string msg): base (msg) + { + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs index 17f4971a04..1716adef7a 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Extensions.cs @@ -5,14 +5,12 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net; -using System.Net.NetworkInformation; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; - //using Windows.Networking; //using Windows.Networking.Sockets; @@ -73,7 +71,7 @@ namespace SharpCifs.Util.Sharpen public static int BitCount(int val) { - uint num = (uint) val; + uint num = (uint)val; int count = 0; for (int i = 0; i < 32; i++) { @@ -126,9 +124,10 @@ namespace SharpCifs.Util.Sharpen public static Encoding GetEncoding(string name) { - //Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + // Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); try { + Encoding e = Encoding.GetEncoding(name.Replace('_', '-')); if (e is UTF8Encoding) return new UTF8Encoding(false, true); @@ -205,32 +204,12 @@ namespace SharpCifs.Util.Sharpen public static int GetOffset(this TimeZoneInfo tzone, long date) { - return (int) tzone.GetUtcOffset(MillisToDateTimeOffset(date, 0).DateTime).TotalMilliseconds; - } - - public static InputStream GetResourceAsStream(this Type type, string name) - { - //Type.`Assembly` property deleted - //string str2 = type.Assembly.GetName().Name + ".resources"; - string str2 = type.GetTypeInfo().Assembly.GetName().Name + ".resources"; - string[] textArray1 = {str2, ".", type.Namespace, ".", name}; - string str = string.Concat(textArray1); - - //Type.`Assembly` property deleted - //Stream manifestResourceStream = type.Assembly.GetManifestResourceStream(str); - Stream manifestResourceStream = type.GetTypeInfo().Assembly.GetManifestResourceStream(str); - if (manifestResourceStream == null) - { - return null; - } - return InputStream.Wrap(manifestResourceStream); + return (int)tzone.GetUtcOffset(MillisToDateTimeOffset(date, 0).DateTime).TotalMilliseconds; } public static long GetTime(this DateTime dateTime) { - return - new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero) - .ToMillisecondsSinceEpoch(); + return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch(); } public static void InitCause(this Exception ex, Exception cause) @@ -266,7 +245,7 @@ namespace SharpCifs.Util.Sharpen public static Iterator<T> Iterator<T>(this IEnumerable<T> col) { return new EnumeratorWrapper<T>(col, col.GetEnumerator()); - } + } public static T Last<T>(this ICollection<T> col) { @@ -291,28 +270,27 @@ namespace SharpCifs.Util.Sharpen public static DateTime CreateDate(long milliSecondsSinceEpoch) { - long num = EpochTicks + (milliSecondsSinceEpoch*10000); + long num = EpochTicks + (milliSecondsSinceEpoch * 10000); return new DateTime(num); } public static DateTime CreateDateFromUTC(long milliSecondsSinceEpoch) { - long num = EpochTicks + (milliSecondsSinceEpoch*10000); + long num = EpochTicks + (milliSecondsSinceEpoch * 10000); return new DateTime(num, DateTimeKind.Utc); } - public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, - long offsetMinutes) + public static DateTimeOffset MillisToDateTimeOffset(long milliSecondsSinceEpoch, long offsetMinutes) { TimeSpan offset = TimeSpan.FromMinutes(offsetMinutes); - long num = EpochTicks + (milliSecondsSinceEpoch*10000); + long num = EpochTicks + (milliSecondsSinceEpoch * 10000); return new DateTimeOffset(num + offset.Ticks, offset); } public static int NumberOfLeadingZeros(int val) { - uint num = (uint) val; + uint num = (uint)val; int count = 0; while ((num & 0x80000000) == 0) { @@ -324,7 +302,7 @@ namespace SharpCifs.Util.Sharpen public static int NumberOfTrailingZeros(int val) { - uint num = (uint) val; + uint num = (uint)val; int count = 0; while ((num & 1) == 0) { @@ -375,7 +353,7 @@ namespace SharpCifs.Util.Sharpen { Regex rgx = new Regex(regex); - if (replacement.IndexOfAny(new[] {'\\', '$'}) != -1) + if (replacement.IndexOfAny(new[] { '\\', '$' }) != -1) { // Back references not yet supported StringBuilder sb = new StringBuilder(); @@ -394,13 +372,7 @@ namespace SharpCifs.Util.Sharpen return rgx.Replace(str, replacement); } - public static bool RegionMatches(this - string str, - bool ignoreCase, - int toOffset, - string other, - int ooffset, - int len) + public static bool RegionMatches(this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len) { if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length) return false; @@ -526,19 +498,14 @@ namespace SharpCifs.Util.Sharpen { if (dateTime.Kind != DateTimeKind.Utc) { - throw new ArgumentException( - "dateTime is expected to be expressed as a UTC DateTime", "dateTime"); + throw new ArgumentException("dateTime is expected to be expressed as a UTC DateTime", "dateTime"); } - return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), - TimeSpan.Zero).ToMillisecondsSinceEpoch(); + return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch(); } public static long ToMillisecondsSinceEpoch(this DateTimeOffset dateTimeOffset) { - return ( - ((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) - /TimeSpan.TicksPerMillisecond - ); + return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EpochTicks) / TimeSpan.TicksPerMillisecond); } public static string ToOctalString(int val) @@ -630,8 +597,8 @@ namespace SharpCifs.Util.Sharpen if (host == "0.0.0.0") { return IPAddress.Any; - } - + } + try { return IPAddress.Parse(host); @@ -639,47 +606,42 @@ namespace SharpCifs.Util.Sharpen catch (Exception ex) { return null; - } + } } public static IPAddress[] GetAddressesByName(string host) { - try - { - //get v4-address only - return System.Net.Dns.GetHostEntryAsync(host) - .GetAwaiter() - .GetResult() - .AddressList - .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork) - .ToArray(); - } - catch (Exception) - { - return null; - } - } - + //IReadOnlyList<EndpointPair> data = null; + + //try + //{ + // Task.Run(async () => + // { + // data = await DatagramSocket.GetEndpointPairsAsync(new HostName(host), "0"); + // }).Wait(); + //} + //catch (Exception ex) + //{ + // return null; + //} + + //return data != null + // ? data.Where(i => i.RemoteHostName.Type == HostNameType.Ipv4) + // .GroupBy(i => i.RemoteHostName.DisplayName) + // .Select(i => IPAddress.Parse(i.First().RemoteHostName.DisplayName)) + // .ToArray() + // : null; + + //get v4-address only + var entry = Task.Run(() => System.Net.Dns.GetHostEntryAsync(host)) + .GetAwaiter() + .GetResult(); + return entry.AddressList + .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork) + .ToArray(); - public static IPAddress[] GetLocalAddresses() - { - try - { - //get v4-address only - return NetworkInterface.GetAllNetworkInterfaces() - .SelectMany(i => i.GetIPProperties().UnicastAddresses) - .Select(ua => ua.Address) - .Where(addr => addr.AddressFamily == AddressFamily.InterNetwork - && !IPAddress.IsLoopback(addr)) - .ToArray(); - } - catch (Exception) - { - return null; - } } - public static string GetImplementationVersion(this Assembly asm) { return asm.GetName().Version.ToString(); @@ -705,11 +667,6 @@ namespace SharpCifs.Util.Sharpen return ((IPEndPoint)socket.LocalEndPoint).Port; } - public static IPAddress GetLocalInetAddress(this Socket socket) - { - return ((IPEndPoint)socket.LocalEndPoint).Address; - } - public static int GetPort(this Socket socket) { return ((IPEndPoint)socket.RemoteEndPoint).Port; @@ -721,16 +678,14 @@ namespace SharpCifs.Util.Sharpen } - /* - public static bool RemoveElement(this ArrayList list, object elem) + /*public static bool RemoveElement(this ArrayList list, object elem) { int i = list.IndexOf(elem); if (i == -1) return false; list.RemoveAt(i); return true; - } - */ + }*/ public static Semaphore CreateSemaphore(int count) { diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs index 6cebfcb945..25c5e06e07 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileInputStream.cs @@ -3,18 +3,18 @@ using System.IO; namespace SharpCifs.Util.Sharpen { public class FileInputStream : InputStream - { - public FileInputStream(FilePath file) : this(file.GetPath()) - { - } + { + public FileInputStream (FilePath file) : this(file.GetPath ()) + { + } - public FileInputStream(string file) - { - if (!File.Exists(file)) - { - throw new FileNotFoundException("File not found", file); - } - Wrapped = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - } - } + public FileInputStream (string file) + { + if (!File.Exists (file)) { + throw new FileNotFoundException ("File not found", file); + } + Wrapped = new FileStream (file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + } + + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs index 2e84e42c99..bf80294886 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileOutputStream.cs @@ -3,37 +3,31 @@ using System.IO; namespace SharpCifs.Util.Sharpen { internal class FileOutputStream : OutputStream - { - public FileOutputStream(FilePath file) : this(file.GetPath(), false) - { - } + { + public FileOutputStream (FilePath file): this (file.GetPath (), false) + { + } - public FileOutputStream(string file) : this(file, false) - { - } + public FileOutputStream (string file): this (file, false) + { + } - public FileOutputStream(FilePath file, bool append) : this(file.GetPath(), append) - { - } + public FileOutputStream (FilePath file, bool append) : this(file.GetPath (), append) + { + } - public FileOutputStream(string file, bool append) - { - try - { - if (append) - { - Wrapped = File.Open(file, FileMode.Append, FileAccess.Write); - } - else - { - Wrapped = File.Open(file, FileMode.Create, FileAccess.Write); - } - } - catch (DirectoryNotFoundException) - { - throw new FileNotFoundException("File not found: " + file); - } - } + public FileOutputStream (string file, bool append) + { + try { + if (append) { + Wrapped = File.Open (file, FileMode.Append, FileAccess.Write); + } else { + Wrapped = File.Open (file, FileMode.Create, FileAccess.Write); + } + } catch (DirectoryNotFoundException) { + throw new FileNotFoundException ("File not found: " + file); + } + } - } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs index 490c769372..1b2f5eddcd 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilePath.cs @@ -6,337 +6,308 @@ using System.Threading; namespace SharpCifs.Util.Sharpen { public class FilePath - { - private string _path; - private static long _tempCounter; - - public FilePath() - { - } - - public FilePath(string path) - : this((string)null, path) - { - - } - - public FilePath(FilePath other, string child) - : this((string)other, child) - { - - } - - public FilePath(string other, string child) - { - if (other == null) - { - _path = child; - } - else - { - while (!string.IsNullOrEmpty(child) - && (child[0] == Path.DirectorySeparatorChar - || child[0] == Path.AltDirectorySeparatorChar)) - child = child.Substring(1); - - if (!string.IsNullOrEmpty(other) - && other[other.Length - 1] == Path.VolumeSeparatorChar) - other += Path.DirectorySeparatorChar; - - _path = Path.Combine(other, child); - } - } - - public static implicit operator FilePath(string name) - { - return new FilePath(name); - } - - public static implicit operator string(FilePath filePath) - { - return filePath == null ? null : filePath._path; - } - - public override bool Equals(object obj) - { - FilePath other = obj as FilePath; - if (other == null) - return false; - return GetCanonicalPath() == other.GetCanonicalPath(); - } - - public override int GetHashCode() - { - return _path.GetHashCode(); - } - - public bool CreateNewFile() - { - try - { + { + private string _path; + private static long _tempCounter; + + public FilePath () + { + } + + public FilePath (string path) + : this ((string) null, path) + { + + } + + public FilePath (FilePath other, string child) + : this ((string) other, child) + { + + } + + public FilePath (string other, string child) + { + if (other == null) { + _path = child; + } else { + while (!string.IsNullOrEmpty(child) && (child[0] == Path.DirectorySeparatorChar || child[0] == Path.AltDirectorySeparatorChar)) + child = child.Substring (1); + + if (!string.IsNullOrEmpty(other) && other[other.Length - 1] == Path.VolumeSeparatorChar) + other += Path.DirectorySeparatorChar; + + _path = Path.Combine (other, child); + } + } + + public static implicit operator FilePath (string name) + { + return new FilePath (name); + } + + public static implicit operator string (FilePath filePath) + { + return filePath == null ? null : filePath._path; + } + + public override bool Equals (object obj) + { + FilePath other = obj as FilePath; + if (other == null) + return false; + return GetCanonicalPath () == other.GetCanonicalPath (); + } + + public override int GetHashCode () + { + return _path.GetHashCode (); + } + + public bool CreateNewFile () + { + try { //Stream.`Close` method deleted //File.Open (_path, FileMode.CreateNew).Close (); File.Open(_path, FileMode.CreateNew).Dispose(); return true; - } - catch - { - return false; - } - } - - public static FilePath CreateTempFile() - { - return new FilePath(Path.GetTempFileName()); - } - - public static FilePath CreateTempFile(string prefix, string suffix) - { - return CreateTempFile(prefix, suffix, null); - } - - public static FilePath CreateTempFile(string prefix, string suffix, FilePath directory) - { - string file; - if (prefix == null) - { - throw new ArgumentNullException("prefix"); - } - if (prefix.Length < 3) - { - throw new ArgumentException("prefix must have at least 3 characters"); - } - string str = (directory == null) ? Path.GetTempPath() : directory.GetPath(); - do - { - file = Path.Combine(str, prefix + Interlocked.Increment(ref _tempCounter) + suffix); - } while (File.Exists(file)); - - new FileOutputStream(file).Close(); - return new FilePath(file); - } - - - public void DeleteOnExit() - { - } - - - public FilePath GetAbsoluteFile() - { - return new FilePath(Path.GetFullPath(_path)); - } - - public string GetAbsolutePath() - { - return Path.GetFullPath(_path); - } - - public FilePath GetCanonicalFile() - { - return new FilePath(GetCanonicalPath()); - } - - public string GetCanonicalPath() - { - return Path.GetFullPath(_path); - } - - public string GetName() - { - return Path.GetFileName(_path); - } - - public FilePath GetParentFile() - { - return new FilePath(Path.GetDirectoryName(_path)); - } - - public string GetPath() - { - return _path; - } - - public bool IsAbsolute() - { - return Path.IsPathRooted(_path); - } - - public bool IsDirectory() - { + } catch { + return false; + } + } + + public static FilePath CreateTempFile () + { + return new FilePath (Path.GetTempFileName ()); + } + + public static FilePath CreateTempFile (string prefix, string suffix) + { + return CreateTempFile (prefix, suffix, null); + } + + public static FilePath CreateTempFile (string prefix, string suffix, FilePath directory) + { + string file; + if (prefix == null) { + throw new ArgumentNullException ("prefix"); + } + if (prefix.Length < 3) { + throw new ArgumentException ("prefix must have at least 3 characters"); + } + string str = (directory == null) ? Path.GetTempPath () : directory.GetPath (); + do { + file = Path.Combine (str, prefix + Interlocked.Increment (ref _tempCounter) + suffix); + } while (File.Exists (file)); + + new FileOutputStream (file).Close (); + return new FilePath (file); + } + + + public void DeleteOnExit () + { + } + + + public FilePath GetAbsoluteFile () + { + return new FilePath (Path.GetFullPath (_path)); + } + + public string GetAbsolutePath () + { + return Path.GetFullPath (_path); + } + + public FilePath GetCanonicalFile () + { + return new FilePath (GetCanonicalPath ()); + } + + public string GetCanonicalPath () + { + string p = Path.GetFullPath (_path); + p.TrimEnd (Path.DirectorySeparatorChar); + return p; + } + + public string GetName () + { + return Path.GetFileName (_path); + } + + public FilePath GetParentFile () + { + return new FilePath (Path.GetDirectoryName (_path)); + } + + public string GetPath () + { + return _path; + } + + public bool IsAbsolute () + { + return Path.IsPathRooted (_path); + } + + public bool IsDirectory () + { return false; // FileHelper.Instance.IsDirectory(this); - } + } - public bool IsFile() - { - return false; //FileHelper.Instance.IsFile (this); - } + public bool IsFile () + { + return false; //FileHelper.Instance.IsFile (this); + } - public long LastModified() - { + public long LastModified () + { return 0; // FileHelper.Instance.LastModified(this); - } + } - public long Length() - { + public long Length () + { return 0; // FileHelper.Instance.Length(this); - } - - public string[] List() - { - return List(null); - } - - public string[] List(IFilenameFilter filter) - { - try - { - if (IsFile()) - return null; - List<string> list = new List<string>(); - foreach (string filePth in Directory.GetFileSystemEntries(_path)) - { - string fileName = Path.GetFileName(filePth); - if ((filter == null) || filter.Accept(this, fileName)) - { - list.Add(fileName); - } - } - return list.ToArray(); - } - catch - { - return null; - } - } - - public FilePath[] ListFiles() - { - try - { - if (IsFile()) - return null; - List<FilePath> list = new List<FilePath>(); - foreach (string filePath in Directory.GetFileSystemEntries(_path)) - { - list.Add(new FilePath(filePath)); - } - return list.ToArray(); - } - catch - { - return null; - } - } - - static void MakeDirWritable(string dir) - { - //FileHelper.Instance.MakeDirWritable (dir); - } - - static void MakeFileWritable(string file) - { - //FileHelper.Instance.MakeFileWritable (file); - } - - public bool Mkdir() - { - try - { - if (Directory.Exists(_path)) - return false; - Directory.CreateDirectory(_path); - return true; - } - catch (Exception) - { - return false; - } - } - - public bool Mkdirs() - { - try - { - if (Directory.Exists(_path)) - return false; - Directory.CreateDirectory(_path); - return true; - } - catch - { - return false; - } - } - - public bool RenameTo(FilePath file) - { - return RenameTo(file._path); - } - - public bool RenameTo(string name) - { + } + + public string[] List () + { + return List (null); + } + + public string[] List (IFilenameFilter filter) + { + try { + if (IsFile ()) + return null; + List<string> list = new List<string> (); + foreach (string filePth in Directory.GetFileSystemEntries (_path)) { + string fileName = Path.GetFileName (filePth); + if ((filter == null) || filter.Accept (this, fileName)) { + list.Add (fileName); + } + } + return list.ToArray (); + } catch { + return null; + } + } + + public FilePath[] ListFiles () + { + try { + if (IsFile ()) + return null; + List<FilePath> list = new List<FilePath> (); + foreach (string filePath in Directory.GetFileSystemEntries (_path)) { + list.Add (new FilePath (filePath)); + } + return list.ToArray (); + } catch { + return null; + } + } + + static void MakeDirWritable (string dir) + { + //FileHelper.Instance.MakeDirWritable (dir); + } + + static void MakeFileWritable (string file) + { + //FileHelper.Instance.MakeFileWritable (file); + } + + public bool Mkdir () + { + try { + if (Directory.Exists (_path)) + return false; + Directory.CreateDirectory (_path); + return true; + } catch (Exception) { + return false; + } + } + + public bool Mkdirs () + { + try { + if (Directory.Exists (_path)) + return false; + Directory.CreateDirectory (_path); + return true; + } catch { + return false; + } + } + + public bool RenameTo (FilePath file) + { + return RenameTo (file._path); + } + + public bool RenameTo (string name) + { return false; // FileHelper.Instance.RenameTo(this, name); - } + } - public bool SetLastModified(long milis) - { + public bool SetLastModified (long milis) + { return false; // FileHelper.Instance.SetLastModified(this, milis); - } + } - public bool SetReadOnly() - { + public bool SetReadOnly () + { return false; // FileHelper.Instance.SetReadOnly(this); - } - - public Uri ToUri() - { - return new Uri(_path); - } - - // Don't change the case of this method, since ngit does reflection on it - public bool CanExecute() - { + } + + public Uri ToUri () + { + return new Uri (_path); + } + + // Don't change the case of this method, since ngit does reflection on it + public bool CanExecute () + { return false; // FileHelper.Instance.CanExecute(this); - } - - // Don't change the case of this method, since ngit does reflection on it - public bool SetExecutable(bool exec) - { + } + + // Don't change the case of this method, since ngit does reflection on it + public bool SetExecutable (bool exec) + { return false; // FileHelper.Instance.SetExecutable(this, exec); - } - - public string GetParent() - { - string p = Path.GetDirectoryName(_path); - if (string.IsNullOrEmpty(p) || p == _path) - return null; - return p; - } - - public override string ToString() - { - return _path; - } - - static internal string PathSeparator - { - get { return Path.PathSeparator.ToString(); } - } - - static internal char PathSeparatorChar - { - get { return Path.PathSeparator; } - } - - static internal char SeparatorChar - { - get { return Path.DirectorySeparatorChar; } - } - - static internal string Separator - { - get { return Path.DirectorySeparatorChar.ToString(); } - } - } + } + + public string GetParent () + { + string p = Path.GetDirectoryName (_path); + if (string.IsNullOrEmpty(p) || p == _path) + return null; + return p; + } + + public override string ToString () + { + return _path; + } + + static internal string PathSeparator { + get { return Path.PathSeparator.ToString (); } + } + + static internal char PathSeparatorChar { + get { return Path.PathSeparator; } + } + + static internal char SeparatorChar { + get { return Path.DirectorySeparatorChar; } + } + + static internal string Separator { + get { return Path.DirectorySeparatorChar.ToString (); } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs index 69fb83268e..7a0c1f90e1 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FileReader.cs @@ -1,13 +1,13 @@ namespace SharpCifs.Util.Sharpen { public class FileReader : InputStreamReader - { - //public FileReader (FilePath f) : base(f.GetPath ()) - //{ - //} + { + //public FileReader (FilePath f) : base(f.GetPath ()) + //{ + //} //path -> fileStream public FileReader(InputStream s) : base(s) - { + { } } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs index 3b2276303f..dfc0ba2641 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterInputStream.cs @@ -1,57 +1,57 @@ namespace SharpCifs.Util.Sharpen { public class FilterInputStream : InputStream - { - protected InputStream In; - - public FilterInputStream(InputStream s) - { - In = s; - } - - public override int Available() - { - return In.Available(); - } - - public override void Close() - { - In.Close(); - } - - public override void Mark(int readlimit) - { - In.Mark(readlimit); - } - - public override bool MarkSupported() - { - return In.MarkSupported(); - } - - public override int Read() - { - return In.Read(); - } - - public override int Read(byte[] buf) - { - return In.Read(buf); - } - - public override int Read(byte[] b, int off, int len) - { - return In.Read(b, off, len); - } - - public override void Reset() - { - In.Reset(); - } - - public override long Skip(long cnt) - { - return In.Skip(cnt); - } - } + { + protected InputStream In; + + public FilterInputStream (InputStream s) + { + In = s; + } + + public override int Available () + { + return In.Available (); + } + + public override void Close () + { + In.Close (); + } + + public override void Mark (int readlimit) + { + In.Mark (readlimit); + } + + public override bool MarkSupported () + { + return In.MarkSupported (); + } + + public override int Read () + { + return In.Read (); + } + + public override int Read (byte[] buf) + { + return In.Read (buf); + } + + public override int Read (byte[] b, int off, int len) + { + return In.Read (b, off, len); + } + + public override void Reset () + { + In.Reset (); + } + + public override long Skip (long cnt) + { + return In.Skip (cnt); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs index c2e7322fbd..4863105ed6 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/FilterOutputStream.cs @@ -1,37 +1,37 @@ namespace SharpCifs.Util.Sharpen { public class FilterOutputStream : OutputStream - { - protected OutputStream Out; + { + protected OutputStream Out; - public FilterOutputStream(OutputStream os) - { - Out = os; - } + public FilterOutputStream (OutputStream os) + { + Out = os; + } - public override void Close() - { - Out.Close(); - } + public override void Close () + { + Out.Close (); + } - public override void Flush() - { - Out.Flush(); - } + public override void Flush () + { + Out.Flush (); + } - public override void Write(byte[] b) - { - Out.Write(b); - } + public override void Write (byte[] b) + { + Out.Write (b); + } - public override void Write(int b) - { - Out.Write(b); - } + public override void Write (int b) + { + Out.Write (b); + } - public override void Write(byte[] b, int offset, int len) - { - Out.Write(b, offset, len); - } - } + public override void Write (byte[] b, int offset, int len) + { + Out.Write (b, offset, len); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs index 86c54265c6..c2c53485dc 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Hashtable.cs @@ -6,18 +6,15 @@ namespace SharpCifs.Util.Sharpen public class Hashtable : Dictionary<object, object> { public void Put(object key, object value) - { - if (this.ContainsKey(key)) - this[key] = value; - else - this.Add(key, value); + { + Add(key, value); } public object Get(object key) { - return this.ContainsKey(key) - ? this[key] - : null; + var m_key = Keys.SingleOrDefault(k => k.Equals(key)); + + return m_key != null ? this[m_key] : null; } } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs index b105875344..ace314eee4 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/HttpURLConnection.cs @@ -34,3 +34,4 @@ namespace SharpCifs.Util.Sharpen } } + diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs index 478e815729..d847cb497a 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ICallable.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { - internal interface ICallable<T> - { - T Call(); - } + internal interface ICallable<T> + { + T Call (); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs index 13773700cc..dead242443 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IConcurrentMap.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; namespace SharpCifs.Util.Sharpen { internal interface IConcurrentMap<T, TU> : IDictionary<T, TU> - { - TU PutIfAbsent(T key, TU value); - bool Remove(object key, object value); - bool Replace(T key, TU oldValue, TU newValue); - } + { + TU PutIfAbsent (T key, TU value); + bool Remove (object key, object value); + bool Replace (T key, TU oldValue, TU newValue); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs index ff3e9e7871..5f76c2ed57 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IExecutor.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { public interface IExecutor - { - void Execute(IRunnable runnable); - } + { + void Execute (IRunnable runnable); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs index 1b79ad8679..fe2eb6a3d6 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFilenameFilter.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { public interface IFilenameFilter - { - bool Accept(FilePath dir, string name); - } + { + bool Accept (FilePath dir, string name); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs index ce8cebd989..5215e45028 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IFuture.cs @@ -1,8 +1,8 @@ namespace SharpCifs.Util.Sharpen { internal interface IFuture<T> - { - bool Cancel(bool mayInterruptIfRunning); - T Get(); - } + { + bool Cancel (bool mayInterruptIfRunning); + T Get (); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs index 1897b91279..4a5e92f9b5 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IPrivilegedAction.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { - internal interface IPrivilegedAction<T> - { - T Run(); - } + internal interface IPrivilegedAction<T> + { + T Run (); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs index cb11d314a4..7f6ae5533d 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/IRunnable.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { public interface IRunnable - { - void Run(); - } + { + void Run (); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs index 33256e5db1..2f3f070b50 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStream.cs @@ -4,156 +4,147 @@ using System.IO; namespace SharpCifs.Util.Sharpen { public class InputStream : IDisposable - { - private long _mark; - protected Stream Wrapped; - protected Stream BaseStream; - - public static implicit operator InputStream(Stream s) - { - return Wrap(s); - } - - public static implicit operator Stream(InputStream s) - { - return s.GetWrappedStream(); - } - - public virtual int Available() - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Available(); - return 0; - } - - public virtual void Close() - { - if (Wrapped != null) - { + { + private long _mark; + protected Stream Wrapped; + protected Stream BaseStream; + + public static implicit operator InputStream (Stream s) + { + return Wrap (s); + } + + public static implicit operator Stream (InputStream s) + { + return s.GetWrappedStream (); + } + + public virtual int Available () + { + if (Wrapped is WrappedSystemStream) + return ((WrappedSystemStream)Wrapped).InputStream.Available (); + return 0; + } + + public virtual void Close () + { + if (Wrapped != null) { //Stream.`Close` method deleted - //Wrapped.Close(); + //Wrapped.Close (); Wrapped.Dispose(); } - } - - public void Dispose() - { - Close(); - } - - internal Stream GetWrappedStream() - { - // Always create a wrapper stream (not directly Wrapped) since the subclass - // may be overriding methods that need to be called when used through the Stream class - return new WrappedSystemStream(this); - } - - public virtual void Mark(int readlimit) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).InputStream.Mark(readlimit); - else - { - if (BaseStream is WrappedSystemStream) - ((WrappedSystemStream)BaseStream).OnMark(readlimit); - if (Wrapped != null) - _mark = Wrapped.Position; - } - } - - public virtual bool MarkSupported() - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.MarkSupported(); - return ((Wrapped != null) && Wrapped.CanSeek); - } - - public virtual int Read() - { - if (Wrapped == null) - { - throw new NotImplementedException(); - } - return Wrapped.ReadByte(); - } - - public virtual int Read(byte[] buf) - { - return Read(buf, 0, buf.Length); - } - - public virtual int Read(byte[] b, int off, int len) - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Read(b, off, len); - - if (Wrapped != null) - { - int num = Wrapped.Read(b, off, len); - return ((num <= 0) ? -1 : num); - } - int totalRead = 0; - while (totalRead < len) - { - int nr = Read(); - if (nr == -1) - return -1; - b[off + totalRead] = (byte)nr; - totalRead++; - } - return totalRead; - } - - public virtual void Reset() - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).InputStream.Reset(); - else - { - if (Wrapped == null) - throw new IOException(); - Wrapped.Position = _mark; - } - } - - public virtual long Skip(long cnt) - { - if (Wrapped is WrappedSystemStream) - return ((WrappedSystemStream)Wrapped).InputStream.Skip(cnt); - - long n = cnt; - while (n > 0) - { - if (Read() == -1) - return cnt - n; - n--; - } - return cnt - n; - } - - internal virtual bool CanSeek() - { - if (Wrapped != null) - return Wrapped.CanSeek; - return false; - } - - internal virtual long Position - { - get - { - if (Wrapped != null) - return Wrapped.Position; - throw new NotSupportedException(); - } - set - { - if (Wrapped != null) - Wrapped.Position = value; - else - throw new NotSupportedException(); - } - } + } + + public void Dispose () + { + Close (); + } + + internal Stream GetWrappedStream () + { + // Always create a wrapper stream (not directly Wrapped) since the subclass + // may be overriding methods that need to be called when used through the Stream class + return new WrappedSystemStream (this); + } + + public virtual void Mark (int readlimit) + { + if (Wrapped is WrappedSystemStream) + ((WrappedSystemStream)Wrapped).InputStream.Mark (readlimit); + else { + if (BaseStream is WrappedSystemStream) + ((WrappedSystemStream)BaseStream).OnMark (readlimit); + if (Wrapped != null) + _mark = Wrapped.Position; + } + } + + public virtual bool MarkSupported () + { + if (Wrapped is WrappedSystemStream) + return ((WrappedSystemStream)Wrapped).InputStream.MarkSupported (); + return ((Wrapped != null) && Wrapped.CanSeek); + } + + public virtual int Read () + { + if (Wrapped == null) { + throw new NotImplementedException (); + } + return Wrapped.ReadByte (); + } + + public virtual int Read (byte[] buf) + { + return Read (buf, 0, buf.Length); + } + + public virtual int Read (byte[] b, int off, int len) + { + if (Wrapped is WrappedSystemStream) + return ((WrappedSystemStream)Wrapped).InputStream.Read (b, off, len); + + if (Wrapped != null) { + int num = Wrapped.Read (b, off, len); + return ((num <= 0) ? -1 : num); + } + int totalRead = 0; + while (totalRead < len) { + int nr = Read (); + if (nr == -1) + return -1; + b[off + totalRead] = (byte)nr; + totalRead++; + } + return totalRead; + } + + public virtual void Reset () + { + if (Wrapped is WrappedSystemStream) + ((WrappedSystemStream)Wrapped).InputStream.Reset (); + else { + if (Wrapped == null) + throw new IOException (); + Wrapped.Position = _mark; + } + } + + public virtual long Skip (long cnt) + { + if (Wrapped is WrappedSystemStream) + return ((WrappedSystemStream)Wrapped).InputStream.Skip (cnt); + + long n = cnt; + while (n > 0) { + if (Read () == -1) + return cnt - n; + n--; + } + return cnt - n; + } + + internal virtual bool CanSeek () + { + if (Wrapped != null) + return Wrapped.CanSeek; + return false; + } + + internal virtual long Position { + get + { + if (Wrapped != null) + return Wrapped.Position; + throw new NotSupportedException (); + } + set { + if (Wrapped != null) + Wrapped.Position = value; + else + throw new NotSupportedException (); + } + } public virtual long Length { @@ -161,18 +152,18 @@ namespace SharpCifs.Util.Sharpen { if (Wrapped != null) { - return Wrapped.Length; + return Wrapped.Length; } throw new NotSupportedException(); } } - static internal InputStream Wrap(Stream s) - { - InputStream stream = new InputStream(); - stream.Wrapped = s; - return stream; - } - } + static internal InputStream Wrap (Stream s) + { + InputStream stream = new InputStream (); + stream.Wrapped = s; + return stream; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs index 90b6fde1ae..f9f1983b83 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/InputStreamReader.cs @@ -4,23 +4,22 @@ using System.Text; namespace SharpCifs.Util.Sharpen { public class InputStreamReader : StreamReader - { + { //Stream(string path) constructor deleted - //protected InputStreamReader (string file) : base(file) - //{ - //} + //protected InputStreamReader (string file) : base(file) + //{ + //} - public InputStreamReader(InputStream s) : base(s.GetWrappedStream()) - { - } + public InputStreamReader (InputStream s) : base(s.GetWrappedStream ()) + { + } - public InputStreamReader(InputStream s, string encoding) - : base(s.GetWrappedStream(), Encoding.GetEncoding(encoding)) - { - } + public InputStreamReader (InputStream s, string encoding) : base(s.GetWrappedStream (), Encoding.GetEncoding (encoding)) + { + } - public InputStreamReader(InputStream s, Encoding e) : base(s.GetWrappedStream(), e) - { - } - } + public InputStreamReader (InputStream s, Encoding e) : base(s.GetWrappedStream (), e) + { + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs index 77339699ab..634c7b404e 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Iterator.cs @@ -5,52 +5,49 @@ using System.Collections.Generic; namespace SharpCifs.Util.Sharpen { public interface ITerator - { - bool HasNext(); - object Next(); - void Remove(); - } - - public abstract class Iterator<T> : IEnumerator<T>, ITerator - { - private T _lastValue; - - object ITerator.Next() - { - return Next(); - } - - public abstract bool HasNext(); - public abstract T Next(); - public abstract void Remove(); - - bool IEnumerator.MoveNext() - { - if (HasNext()) - { - _lastValue = Next(); - return true; - } - return false; - } - - void IEnumerator.Reset() - { - throw new NotImplementedException(); - } - - void IDisposable.Dispose() - { - } - - T IEnumerator<T>.Current - { - get { return _lastValue; } - } - - object IEnumerator.Current - { - get { return _lastValue; } - } - } + { + bool HasNext (); + object Next (); + void Remove (); + } + + public abstract class Iterator<T> : IEnumerator<T>, ITerator + { + private T _lastValue; + + object ITerator.Next () + { + return Next (); + } + + public abstract bool HasNext (); + public abstract T Next (); + public abstract void Remove (); + + bool IEnumerator.MoveNext () + { + if (HasNext ()) { + _lastValue = Next (); + return true; + } + return false; + } + + void IEnumerator.Reset () + { + throw new NotImplementedException (); + } + + void IDisposable.Dispose () + { + } + + T IEnumerator<T>.Current { + get { return _lastValue; } + } + + object IEnumerator.Current { + get { return _lastValue; } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs index 4fbd185700..9f4970bddf 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/LinkageError.cs @@ -3,9 +3,9 @@ using System; namespace SharpCifs.Util.Sharpen { internal class LinkageError : Exception - { - public LinkageError(string msg) : base(msg) - { - } - } + { + public LinkageError (string msg) : base(msg) + { + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs index 85cdedd69b..50f3fa43b2 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MD5.cs @@ -4,16 +4,15 @@ using System; using System.Text; namespace SharpCifs.Util.Sharpen -{ - // ************************************************************** - // * Raw implementation of the MD5 hash algorithm - // * from RFC 1321. - // * - // * Written By: Reid Borsuk and Jenny Zheng - // * Copyright (c) Microsoft Corporation. All rights reserved. - // ************************************************************** - - // Simple struct for the (a,b,c,d) which is used to compute the mesage digest. +{ // ************************************************************** +// * Raw implementation of the MD5 hash algorithm +// * from RFC 1321. +// * +// * Written By: Reid Borsuk and Jenny Zheng +// * Copyright (c) Microsoft Corporation. All rights reserved. +// ************************************************************** + +// Simple struct for the (a,b,c,d) which is used to compute the mesage digest. struct AbcdStruct { public uint A; @@ -30,13 +29,9 @@ namespace SharpCifs.Util.Sharpen public static byte[] GetHash(string input, Encoding encoding) { if (null == input) - throw new ArgumentNullException( - "input", "Unable to calculate hash over null input data"); + throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); if (null == encoding) - throw new ArgumentNullException( - "encoding", - "Unable to calculate hash over a string without a default encoding. " - + "Consider using the GetHash(string) overload to use UTF8 Encoding"); + throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding"); byte[] target = encoding.GetBytes(input); @@ -51,8 +46,7 @@ namespace SharpCifs.Util.Sharpen public static string GetHashString(byte[] input) { if (null == input) - throw new ArgumentNullException( - "input", "Unable to calculate hash over null input data"); + throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); string retval = BitConverter.ToString(GetHash(input)); retval = retval.Replace("-", ""); @@ -63,13 +57,9 @@ namespace SharpCifs.Util.Sharpen public static string GetHashString(string input, Encoding encoding) { if (null == input) - throw new ArgumentNullException( - "input", "Unable to calculate hash over null input data"); + throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); if (null == encoding) - throw new ArgumentNullException( - "encoding", - "Unable to calculate hash over a string without a default encoding. " - + "Consider using the GetHashString(string) overload to use UTF8 Encoding"); + throw new ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHashString(string) overload to use UTF8 Encoding"); byte[] target = encoding.GetBytes(input); @@ -84,8 +74,7 @@ namespace SharpCifs.Util.Sharpen public static byte[] GetHash(byte[] input) { if (null == input) - throw new ArgumentNullException( - "input", "Unable to calculate hash over null input data"); + throw new ArgumentNullException("input", "Unable to calculate hash over null input data"); //Intitial values defined in RFC 1321 AbcdStruct abcd = new AbcdStruct(); @@ -102,18 +91,10 @@ namespace SharpCifs.Util.Sharpen startIndex += 64; } // The final data block. - return GetHashFinalBlock(input, - startIndex, - input.Length - startIndex, - abcd, - (Int64)input.Length * 8); + return GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64)input.Length * 8); } - internal static byte[] GetHashFinalBlock(byte[] input, - int ibStart, - int cbSize, - AbcdStruct abcd, - Int64 len) + internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, AbcdStruct abcd, Int64 len) { byte[] working = new byte[64]; byte[] length = BitConverter.GetBytes(len); @@ -148,11 +129,11 @@ namespace SharpCifs.Util.Sharpen // Performs a single block transform of MD5 for a given set of ABCD inputs /* If implementing your own hashing framework, be sure to set the initial ABCD correctly according to RFC 1321: - // A = 0x67452301; - // B = 0xefcdab89; - // C = 0x98badcfe; - // D = 0x10325476; - */ + // A = 0x67452301; + // B = 0xefcdab89; + // C = 0x98badcfe; + // D = 0x10325476; + */ internal static void GetHashBlock(byte[] input, ref AbcdStruct abcdValue, int ibStart) { uint[] temp = Converter(input, ibStart); @@ -276,8 +257,7 @@ namespace SharpCifs.Util.Sharpen private static uint[] Converter(byte[] input, int ibStart) { if (null == input) - throw new ArgumentNullException( - "input", "Unable convert null array to array of uInts"); + throw new ArgumentNullException("input", "Unable convert null array to array of uInts"); uint[] result = new uint[16]; diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs index e5be6075de..d0bd79aa28 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Matcher.cs @@ -4,84 +4,80 @@ using System.Text.RegularExpressions; namespace SharpCifs.Util.Sharpen { internal class Matcher - { - private int _current; - private MatchCollection _matches; - private Regex _regex; - private string _str; + { + private int _current; + private MatchCollection _matches; + private Regex _regex; + private string _str; - internal Matcher(Regex regex, string str) - { - this._regex = regex; - this._str = str; - } + internal Matcher (Regex regex, string str) + { + this._regex = regex; + this._str = str; + } - public int End() - { - if ((_matches == null) || (_current >= _matches.Count)) - { - throw new InvalidOperationException(); - } - return (_matches[_current].Index + _matches[_current].Length); - } + public int End () + { + if ((_matches == null) || (_current >= _matches.Count)) { + throw new InvalidOperationException (); + } + return (_matches[_current].Index + _matches[_current].Length); + } - public bool Find() - { - if (_matches == null) - { - _matches = _regex.Matches(_str); - _current = 0; - } - return (_current < _matches.Count); - } + public bool Find () + { + if (_matches == null) { + _matches = _regex.Matches (_str); + _current = 0; + } + return (_current < _matches.Count); + } - public bool Find(int index) - { - _matches = _regex.Matches(_str, index); - _current = 0; - return (_matches.Count > 0); - } + public bool Find (int index) + { + _matches = _regex.Matches (_str, index); + _current = 0; + return (_matches.Count > 0); + } - public string Group(int n) - { - if ((_matches == null) || (_current >= _matches.Count)) - { - throw new InvalidOperationException(); - } - Group grp = _matches[_current].Groups[n]; - return grp.Success ? grp.Value : null; - } + public string Group (int n) + { + if ((_matches == null) || (_current >= _matches.Count)) { + throw new InvalidOperationException (); + } + Group grp = _matches[_current].Groups[n]; + return grp.Success ? grp.Value : null; + } - public bool Matches() - { - _matches = null; - return Find(); - } + public bool Matches () + { + _matches = null; + return Find (); + } - public string ReplaceFirst(string txt) - { - return _regex.Replace(_str, txt, 1); - } + public string ReplaceFirst (string txt) + { + return _regex.Replace (_str, txt, 1); + } - public Matcher Reset(CharSequence str) - { - return Reset(str.ToString()); - } + public Matcher Reset (CharSequence str) + { + return Reset (str.ToString ()); + } - public Matcher Reset(string str) - { - _matches = null; - this._str = str; - return this; - } + public Matcher Reset (string str) + { + _matches = null; + this._str = str; + return this; + } - public int Start() - { - if ((_matches == null) || (_current >= _matches.Count)) - { - throw new InvalidOperationException(); - } - return _matches[_current].Index; - } - } + public int Start () + { + if ((_matches == null) || (_current >= _matches.Count)) { + throw new InvalidOperationException (); + } + return _matches[_current].Index; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs index 57fe3e0e98..5562f9d366 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/MessageDigest.cs @@ -6,58 +6,55 @@ using System.Security.Cryptography; namespace SharpCifs.Util.Sharpen { public abstract class MessageDigest - { - public void Digest(byte[] buffer, int o, int len) - { - byte[] d = Digest(); - d.CopyTo(buffer, o); - } - - public byte[] Digest(byte[] buffer) - { - Update(buffer); - return Digest(); - } - - public abstract byte[] Digest(); - public abstract int GetDigestLength(); - public static MessageDigest GetInstance(string algorithm) - { - switch (algorithm.ToLower()) - { - case "sha-1": - //System.Security.CryptographySHA1Managed not found - //return new MessageDigest<SHA1Managed> (); - return new MessageDigest<System.Security.Cryptography.SHA1>(); - case "md5": - return new MessageDigest<Md5Managed>(); + { + public void Digest (byte[] buffer, int o, int len) + { + byte[] d = Digest (); + d.CopyTo (buffer, o); + } + + public byte[] Digest (byte[] buffer) + { + Update (buffer); + return Digest (); + } + + public abstract byte[] Digest (); + public abstract int GetDigestLength (); + public static MessageDigest GetInstance (string algorithm) + { + switch (algorithm.ToLower ()) { + case "sha-1": + //System.Security.CryptographySHA1Managed not found + //return new MessageDigest<SHA1Managed> (); + return new MessageDigest<System.Security.Cryptography.SHA1>(); + case "md5": + return new MessageDigest<Md5Managed> (); } - throw new NotSupportedException( - string.Format("The requested algorithm \"{0}\" is not supported.", algorithm)); - } + throw new NotSupportedException (string.Format ("The requested algorithm \"{0}\" is not supported.", algorithm)); + } - public abstract void Reset(); - public abstract void Update(byte[] b); - public abstract void Update(byte b); - public abstract void Update(byte[] b, int offset, int len); - } + public abstract void Reset (); + public abstract void Update (byte[] b); + public abstract void Update (byte b); + public abstract void Update (byte[] b, int offset, int len); + } - public class MessageDigest<TAlgorithm> - : MessageDigest where TAlgorithm : HashAlgorithm //, new() //use static `Create` method - { - private TAlgorithm _hash; + public class MessageDigest<TAlgorithm> : MessageDigest where TAlgorithm : HashAlgorithm //, new() //use static `Create` method + { + private TAlgorithm _hash; //private CryptoStream _stream; //don't work .NET Core private MemoryStream _stream; - public MessageDigest() - { - Init(); - } + public MessageDigest () + { + Init (); + } - public override byte[] Digest() - { + public override byte[] Digest () + { //CryptoStream -> MemoryStream, needless method //_stream.FlushFinalBlock (); @@ -65,30 +62,29 @@ namespace SharpCifs.Util.Sharpen //byte[] hash = _hash.Hash; byte[] hash = _hash.ComputeHash(_stream.ToArray()); - Reset(); - return hash; - } + Reset (); + return hash; + } - public void Dispose() - { - if (_stream != null) - { - _stream.Dispose(); - } - _stream = null; + public void Dispose () + { + if (_stream != null) { + _stream.Dispose (); + } + _stream = null; } - public override int GetDigestLength() - { - return (_hash.HashSize / 8); - } + public override int GetDigestLength () + { + return (_hash.HashSize / 8); + } - private void Init() - { + private void Init () + { //use static `Create` method //_hash = Activator.CreateInstance<TAlgorithm> (); var createMethod = typeof(TAlgorithm).GetRuntimeMethod("Create", new Type[0]); - _hash = (TAlgorithm)createMethod.Invoke(null, new object[] { }); + _hash = (TAlgorithm)createMethod.Invoke(null, new object[] {}); //HashAlgorithm cannot cast `ICryptoTransform` on .NET Core, gave up using CryptoStream. //_stream = new CryptoStream(Stream.Null, _hash, CryptoStreamMode.Write); @@ -96,27 +92,27 @@ namespace SharpCifs.Util.Sharpen _stream = new MemoryStream(); } - public override void Reset() - { - Dispose(); - Init(); - } - - public override void Update(byte[] input) - { - _stream.Write(input, 0, input.Length); - } - - public override void Update(byte input) - { - _stream.WriteByte(input); - } - - public override void Update(byte[] input, int index, int count) - { - if (count < 0) - Console.WriteLine("Argh!"); - _stream.Write(input, index, count); - } - } + public override void Reset () + { + Dispose (); + Init (); + } + + public override void Update (byte[] input) + { + _stream.Write (input, 0, input.Length); + } + + public override void Update (byte input) + { + _stream.WriteByte (input); + } + + public override void Update (byte[] input, int index, int count) + { + if (count < 0) + Console.WriteLine ("Argh!"); + _stream.Write (input, index, count); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs index 58dd1bd10d..05599cea3b 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/NetworkStream.cs @@ -3,15 +3,15 @@ using System.IO; namespace SharpCifs.Util.Sharpen { - public class NetworkStream : Stream + public class NetworkStream : Stream { SocketEx _socket; - + public NetworkStream(SocketEx socket) { _socket = socket; } - + public override bool CanRead { get { throw new NotImplementedException(); } @@ -29,7 +29,7 @@ namespace SharpCifs.Util.Sharpen public override void Flush() { - // throw new NotImplementedException(); + // throw new NotImplementedException(); } public override long Length diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs index 6351c42b53..dc3d6ccc3e 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectInputStream.cs @@ -4,22 +4,22 @@ using System.IO; namespace SharpCifs.Util.Sharpen { internal class ObjectInputStream : InputStream - { - private BinaryReader _reader; + { + private BinaryReader _reader; - public ObjectInputStream(InputStream s) - { - _reader = new BinaryReader(s.GetWrappedStream()); - } + public ObjectInputStream (InputStream s) + { + _reader = new BinaryReader (s.GetWrappedStream ()); + } - public int ReadInt() - { - return _reader.ReadInt32(); - } + public int ReadInt () + { + return _reader.ReadInt32 (); + } - public object ReadObject() - { - throw new NotImplementedException(); - } - } + public object ReadObject () + { + throw new NotImplementedException (); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs index 3099fbe721..97f3a2cfd2 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ObjectOutputStream.cs @@ -3,17 +3,17 @@ using System.IO; namespace SharpCifs.Util.Sharpen { internal class ObjectOutputStream : OutputStream - { - private BinaryWriter _bw; + { + private BinaryWriter _bw; - public ObjectOutputStream(OutputStream os) - { - _bw = new BinaryWriter(os.GetWrappedStream()); - } + public ObjectOutputStream (OutputStream os) + { + _bw = new BinaryWriter (os.GetWrappedStream ()); + } - public virtual void WriteInt(int i) - { - _bw.Write(i); - } - } + public virtual void WriteInt (int i) + { + _bw.Write (i); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs index 1804d67451..0e6189f0cb 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStream.cs @@ -4,91 +4,83 @@ using System.IO; namespace SharpCifs.Util.Sharpen { public class OutputStream : IDisposable - { - protected Stream Wrapped; + { + protected Stream Wrapped; - public static implicit operator OutputStream(Stream s) - { - return Wrap(s); - } + public static implicit operator OutputStream (Stream s) + { + return Wrap (s); + } - public static implicit operator Stream(OutputStream s) - { - return s.GetWrappedStream(); - } - - public virtual void Close() - { - if (Wrapped != null) - { + public static implicit operator Stream (OutputStream s) + { + return s.GetWrappedStream (); + } + + public virtual void Close () + { + if (Wrapped != null) { //Stream.`Close` method deleted //Wrapped.Close (); Wrapped.Dispose(); } - } + } - public void Dispose() - { - Close(); - } + public void Dispose () + { + Close (); + } - public virtual void Flush() - { - if (Wrapped != null) - { - Wrapped.Flush(); - } - } + public virtual void Flush () + { + if (Wrapped != null) { + Wrapped.Flush (); + } + } - internal Stream GetWrappedStream() - { - // Always create a wrapper stream (not directly Wrapped) since the subclass - // may be overriding methods that need to be called when used through the Stream class - return new WrappedSystemStream(this); - } + internal Stream GetWrappedStream () + { + // Always create a wrapper stream (not directly Wrapped) since the subclass + // may be overriding methods that need to be called when used through the Stream class + return new WrappedSystemStream (this); + } - static internal OutputStream Wrap(Stream s) - { - OutputStream stream = new OutputStream(); - stream.Wrapped = s; - return stream; - } + static internal OutputStream Wrap (Stream s) + { + OutputStream stream = new OutputStream (); + stream.Wrapped = s; + return stream; + } - public virtual void Write(int b) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).OutputStream.Write(b); - else - { - if (Wrapped == null) - throw new NotImplementedException(); - Wrapped.WriteByte((byte)b); - } - } + public virtual void Write (int b) + { + if (Wrapped is WrappedSystemStream) + ((WrappedSystemStream)Wrapped).OutputStream.Write (b); + else { + if (Wrapped == null) + throw new NotImplementedException (); + Wrapped.WriteByte ((byte)b); + } + } - public virtual void Write(byte[] b) - { - Write(b, 0, b.Length); - } + public virtual void Write (byte[] b) + { + Write (b, 0, b.Length); + } - public virtual void Write(byte[] b, int offset, int len) - { - if (Wrapped is WrappedSystemStream) - ((WrappedSystemStream)Wrapped).OutputStream.Write(b, offset, len); - else - { - if (Wrapped != null) - { - Wrapped.Write(b, offset, len); - } - else - { - for (int i = 0; i < len; i++) - { - Write(b[i + offset]); - } - } - } - } - } + public virtual void Write (byte[] b, int offset, int len) + { + if (Wrapped is WrappedSystemStream) + ((WrappedSystemStream)Wrapped).OutputStream.Write (b, offset, len); + else { + if (Wrapped != null) { + Wrapped.Write (b, offset, len); + } else { + for (int i = 0; i < len; i++) { + Write (b[i + offset]); + } + } + } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs index 1b05848a32..6313b7c798 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/OutputStreamWriter.cs @@ -4,20 +4,17 @@ using System.Text; namespace SharpCifs.Util.Sharpen { internal class OutputStreamWriter : StreamWriter - { - public OutputStreamWriter(OutputStream stream) - : base(stream.GetWrappedStream()) - { - } + { + public OutputStreamWriter (OutputStream stream) : base(stream.GetWrappedStream ()) + { + } - public OutputStreamWriter(OutputStream stream, string encoding) - : base(stream.GetWrappedStream(), Extensions.GetEncoding(encoding)) - { - } + public OutputStreamWriter (OutputStream stream, string encoding) : base(stream.GetWrappedStream (), Extensions.GetEncoding (encoding)) + { + } - public OutputStreamWriter(OutputStream stream, Encoding encoding) - : base(stream.GetWrappedStream(), encoding) - { - } - } + public OutputStreamWriter (OutputStream stream, Encoding encoding) : base(stream.GetWrappedStream (), encoding) + { + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs index d2438be70a..d5004c988f 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedInputStream.cs @@ -3,206 +3,170 @@ using System.Threading; namespace SharpCifs.Util.Sharpen { - internal class PipedInputStream : InputStream - { - private byte[] _oneBuffer; - public const int PipeSize = 1024; + internal class PipedInputStream : InputStream + { + private byte[] _oneBuffer; + public const int PipeSize = 1024; + + protected byte[] Buffer; + private bool _closed; + private ManualResetEvent _dataEvent; + private int _end; + private int _start; + private object _thisLock; + private bool _allowGrow = false; + + public int In { + get { return _start; } + set { _start = value; } + } + + public int Out { + get { return _end; } + set { _end = value; } + } - protected byte[] Buffer; - private bool _closed; - private ManualResetEvent _dataEvent; - private int _end; - private int _start; - private object _thisLock; - private bool _allowGrow = false; + public PipedInputStream () + { + _thisLock = new object (); + _dataEvent = new ManualResetEvent (false); + Buffer = new byte[PipeSize + 1]; + } - public int In - { - get { return _start; } - set { _start = value; } - } + public PipedInputStream (PipedOutputStream os): this () + { + os.Attach (this); + } - public int Out - { - get { return _end; } - set { _end = value; } - } + public override void Close () + { + lock (_thisLock) { + _closed = true; + _dataEvent.Set (); + } + } - public PipedInputStream() - { - _thisLock = new object(); - _dataEvent = new ManualResetEvent(false); - Buffer = new byte[PipeSize + 1]; - } + public override int Available () + { + lock (_thisLock) { + if (_start <= _end) { + return (_end - _start); + } + return ((Buffer.Length - _start) + _end); + } + } - public PipedInputStream(PipedOutputStream os) : this() - { - os.Attach(this); - } + public override int Read () + { + if (_oneBuffer == null) + _oneBuffer = new byte[1]; + if (Read (_oneBuffer, 0, 1) == -1) + return -1; + return _oneBuffer[0]; + } - public override void Close() - { - lock (_thisLock) - { - _closed = true; - _dataEvent.Set(); - } - } - - public override int Available() - { - lock (_thisLock) - { - if (_start <= _end) - { - return (_end - _start); - } - return ((Buffer.Length - _start) + _end); - } - } - - public override int Read() - { - if (_oneBuffer == null) - _oneBuffer = new byte[1]; - if (Read(_oneBuffer, 0, 1) == -1) - return -1; - return _oneBuffer[0]; - } - - public override int Read(byte[] b, int offset, int len) - { - int length = 0; - do - { - _dataEvent.WaitOne(); - lock (_thisLock) - { - if (_closed && Available() == 0) - { - return -1; - } - if (_start < _end) - { - length = Math.Min(len, _end - _start); - Array.Copy(Buffer, _start, b, offset, length); - _start += length; - } - else if (_start > _end) - { - length = Math.Min(len, Buffer.Length - _start); - Array.Copy(Buffer, _start, b, offset, length); - len -= length; - _start = (_start + length) % Buffer.Length; - if (len > 0) - { - int i = Math.Min(len, _end); - Array.Copy(Buffer, 0, b, offset + length, i); - _start += i; - length += i; - } - } - if (_start == _end && !_closed) - { - _dataEvent.Reset(); - } - Monitor.PulseAll(_thisLock); - } - } while (length == 0); - return length; - } - - private int Allocate(int len) - { - int alen; - while ((alen = TryAllocate(len)) == 0) - { - // Wait until somebody reads data - try - { - Monitor.Wait(_thisLock); - } - catch - { - _closed = true; - _dataEvent.Set(); - throw; - } - } - return alen; - } - - int TryAllocate(int len) - { - int free; - if (_start <= _end) - { - free = (Buffer.Length - _end) + _start; - } - else - { - free = _start - _end; - } - if (free <= len) - { - if (!_allowGrow) - return free > 0 ? free - 1 : 0; - int sizeInc = (len - free) + 1; - byte[] destinationArray = new byte[Buffer.Length + sizeInc]; - if (_start <= _end) - { - Array.Copy(Buffer, _start, destinationArray, _start, _end - _start); - } - else - { - Array.Copy(Buffer, - 0, - destinationArray, - 0, - _end); - Array.Copy(Buffer, - _start, - destinationArray, - _start + sizeInc, - Buffer.Length - _start); - _start += sizeInc; - } - Buffer = destinationArray; - } - return len; - } - - internal void Write(int b) - { - lock (_thisLock) - { - Allocate(1); - Buffer[_end] = (byte)b; - _end = (_end + 1) % Buffer.Length; - _dataEvent.Set(); - } - } - - internal void Write(byte[] b, int offset, int len) - { - do - { - lock (_thisLock) - { - int alen = Allocate(len); - int length = Math.Min(Buffer.Length - _end, alen); - Array.Copy(b, offset, Buffer, _end, length); - _end = (_end + length) % Buffer.Length; - if (length < alen) - { - Array.Copy(b, offset + length, Buffer, 0, alen - length); - _end += alen - length; - } - _dataEvent.Set(); - len -= alen; - offset += alen; - } - } while (len > 0); - } - } + public override int Read (byte[] b, int offset, int len) + { + int length = 0; + do { + _dataEvent.WaitOne (); + lock (_thisLock) { + if (_closed && Available () == 0) { + return -1; + } + if (_start < _end) { + length = Math.Min (len, _end - _start); + Array.Copy (Buffer, _start, b, offset, length); + _start += length; + } else if (_start > _end) { + length = Math.Min (len, Buffer.Length - _start); + Array.Copy (Buffer, _start, b, offset, length); + len -= length; + _start = (_start + length) % Buffer.Length; + if (len > 0) { + int i = Math.Min (len, _end); + Array.Copy (Buffer, 0, b, offset + length, i); + _start += i; + length += i; + } + } + if (_start == _end && !_closed) { + _dataEvent.Reset (); + } + Monitor.PulseAll (_thisLock); + } + } while (length == 0); + return length; + } + + private int Allocate (int len) + { + int alen; + while ((alen = TryAllocate (len)) == 0) { + // Wait until somebody reads data + try { + Monitor.Wait (_thisLock); + } catch { + _closed = true; + _dataEvent.Set (); + throw; + } + } + return alen; + } + + int TryAllocate (int len) + { + int free; + if (_start <= _end) { + free = (Buffer.Length - _end) + _start; + } else { + free = _start - _end; + } + if (free <= len) { + if (!_allowGrow) + return free > 0 ? free - 1 : 0; + int sizeInc = (len - free) + 1; + byte[] destinationArray = new byte[Buffer.Length + sizeInc]; + if (_start <= _end) { + Array.Copy (Buffer, _start, destinationArray, _start, _end - _start); + } else { + Array.Copy (Buffer, 0, destinationArray, 0, _end); + Array.Copy (Buffer, _start, destinationArray, _start + sizeInc, Buffer.Length - _start); + _start += sizeInc; + } + Buffer = destinationArray; + } + return len; + } + + internal void Write (int b) + { + lock (_thisLock) { + Allocate (1); + Buffer[_end] = (byte)b; + _end = (_end + 1) % Buffer.Length; + _dataEvent.Set (); + } + } + + internal void Write (byte[] b, int offset, int len) + { + do { + lock (_thisLock) { + int alen = Allocate (len); + int length = Math.Min (Buffer.Length - _end, alen); + Array.Copy (b, offset, Buffer, _end, length); + _end = (_end + length) % Buffer.Length; + if (length < alen) { + Array.Copy (b, offset + length, Buffer, 0, alen - length); + _end += alen - length; + } + _dataEvent.Set (); + len -= alen; + offset += alen; + } + } while (len > 0); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs index d8269ec9b0..4c46f1ec00 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PipedOutputStream.cs @@ -1,37 +1,37 @@ namespace SharpCifs.Util.Sharpen { internal class PipedOutputStream : OutputStream - { - PipedInputStream _ips; + { + PipedInputStream _ips; - public PipedOutputStream() - { - } + public PipedOutputStream () + { + } - public PipedOutputStream(PipedInputStream iss) : this() - { - Attach(iss); - } + public PipedOutputStream (PipedInputStream iss) : this() + { + Attach (iss); + } - public override void Close() - { - _ips.Close(); - base.Close(); - } + public override void Close () + { + _ips.Close (); + base.Close (); + } - internal void Attach(PipedInputStream iss) - { - _ips = iss; - } + internal void Attach (PipedInputStream iss) + { + _ips = iss; + } - public override void Write(int b) - { - _ips.Write(b); - } + public override void Write (int b) + { + _ips.Write (b); + } - public override void Write(byte[] b, int offset, int len) - { - _ips.Write(b, offset, len); - } - } + public override void Write (byte[] b, int offset, int len) + { + _ips.Write (b, offset, len); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs index a492e50371..c366aa6659 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/PrintWriter.cs @@ -5,233 +5,227 @@ using System.Text; namespace SharpCifs.Util.Sharpen { public class PrintWriter : TextWriter - { - TextWriter _writer; - private FileStream _stream; - - public PrintWriter(FilePath path) - { + { + TextWriter _writer; + private FileStream _stream; + + public PrintWriter (FilePath path) + { //Stream(string path) constructor deleted _stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite); - _writer = new StreamWriter(_stream); - } + _writer = new StreamWriter (_stream); + } - public PrintWriter(TextWriter other) - { - _writer = other; - } + public PrintWriter (TextWriter other) + { + _writer = other; + } - public override Encoding Encoding - { - get { return _writer.Encoding; } - } + public override Encoding Encoding { + get { return _writer.Encoding; } + } public void Close() // remove `override` { - //Stream.`Close` method deleted + //Stream.`Close` method deleted //_writer.Close (); _writer.Dispose(); _stream.Dispose(); } - - public override void Flush() - { - _writer.Flush(); - } - - public override IFormatProvider FormatProvider - { - get - { - return _writer.FormatProvider; - } - } - - public override string NewLine - { - get - { - return _writer.NewLine; - } - set - { - _writer.NewLine = value; - } - } - - public override void Write(char[] buffer, int index, int count) - { - _writer.Write(buffer, index, count); - } - - public override void Write(char[] buffer) - { - _writer.Write(buffer); - } - - public void Write(string format, object arg0, object arg1, object arg2) - { - _writer.Write(format, arg0, arg1, arg2); - } - - public override void Write(string format, object arg0, object arg1) - { - _writer.Write(format, arg0, arg1); - } - - public override void Write(string format, object arg0) - { - _writer.Write(format, arg0); - } - - public override void Write(string format, params object[] arg) - { - _writer.Write(format, arg); - } - - public override void WriteLine(char[] buffer, int index, int count) - { - _writer.WriteLine(buffer, index, count); - } - - public override void WriteLine(char[] buffer) - { - _writer.WriteLine(buffer); - } - - public void WriteLine(string format, object arg0, object arg1, object arg2) - { - _writer.WriteLine(format, arg0, arg1, arg2); - } - - public override void WriteLine(string format, object arg0, object arg1) - { - _writer.WriteLine(format, arg0, arg1); - } - - public override void WriteLine(string format, object arg0) - { - _writer.WriteLine(format, arg0); - } - - public override void WriteLine(string format, params object[] arg) - { - _writer.WriteLine(format, arg); - } - - public override void WriteLine(ulong value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(uint value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(string value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(float value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(object value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(long value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(int value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(double value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(decimal value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(char value) - { - _writer.WriteLine(value); - } - - public override void WriteLine(bool value) - { - _writer.WriteLine(value); - } - - public override void WriteLine() - { - _writer.WriteLine(); - } - - public override void Write(bool value) - { - _writer.Write(value); - } - - public override void Write(char value) - { - _writer.Write(value); - } - - public override void Write(decimal value) - { - _writer.Write(value); - } - - public override void Write(double value) - { - _writer.Write(value); - } - - public override void Write(int value) - { - _writer.Write(value); - } - - public override void Write(long value) - { - _writer.Write(value); - } - - public override void Write(object value) - { - _writer.Write(value); - } - - public override void Write(float value) - { - _writer.Write(value); - } - - public override void Write(string value) - { - _writer.Write(value); - } - - public override void Write(uint value) - { - _writer.Write(value); - } - - public override void Write(ulong value) - { - _writer.Write(value); - } - } + + public override void Flush () + { + _writer.Flush (); + } + + public override IFormatProvider FormatProvider { + get { + return _writer.FormatProvider; + } + } + + public override string NewLine { + get { + return _writer.NewLine; + } + set { + _writer.NewLine = value; + } + } + + public override void Write (char[] buffer, int index, int count) + { + _writer.Write (buffer, index, count); + } + + public override void Write (char[] buffer) + { + _writer.Write (buffer); + } + + public void Write (string format, object arg0, object arg1, object arg2) + { + _writer.Write (format, arg0, arg1, arg2); + } + + public override void Write (string format, object arg0, object arg1) + { + _writer.Write (format, arg0, arg1); + } + + public override void Write (string format, object arg0) + { + _writer.Write (format, arg0); + } + + public override void Write (string format, params object[] arg) + { + _writer.Write (format, arg); + } + + public override void WriteLine (char[] buffer, int index, int count) + { + _writer.WriteLine (buffer, index, count); + } + + public override void WriteLine (char[] buffer) + { + _writer.WriteLine (buffer); + } + + public void WriteLine (string format, object arg0, object arg1, object arg2) + { + _writer.WriteLine (format, arg0, arg1, arg2); + } + + public override void WriteLine (string format, object arg0, object arg1) + { + _writer.WriteLine (format, arg0, arg1); + } + + public override void WriteLine (string format, object arg0) + { + _writer.WriteLine (format, arg0); + } + + public override void WriteLine (string format, params object[] arg) + { + _writer.WriteLine (format, arg); + } + + public override void WriteLine (ulong value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (uint value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (string value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (float value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (object value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (long value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (int value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (double value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (decimal value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (char value) + { + _writer.WriteLine (value); + } + + public override void WriteLine (bool value) + { + _writer.WriteLine (value); + } + + public override void WriteLine () + { + _writer.WriteLine (); + } + + public override void Write (bool value) + { + _writer.Write (value); + } + + public override void Write (char value) + { + _writer.Write (value); + } + + public override void Write (decimal value) + { + _writer.Write (value); + } + + public override void Write (double value) + { + _writer.Write (value); + } + + public override void Write (int value) + { + _writer.Write (value); + } + + public override void Write (long value) + { + _writer.Write (value); + } + + public override void Write (object value) + { + _writer.Write (value); + } + + public override void Write (float value) + { + _writer.Write (value); + } + + public override void Write (string value) + { + _writer.Write (value); + } + + public override void Write (uint value) + { + _writer.Write (value); + } + + public override void Write (ulong value) + { + _writer.Write (value); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs index 8aad1a4035..3d886ea87a 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Properties.cs @@ -6,76 +6,81 @@ namespace SharpCifs.Util.Sharpen { protected Hashtable _properties; - public Properties() { - this._properties = new Hashtable(); + _properties = new Hashtable(); } - public Properties(Properties defaultProp) : this() + public Properties(Properties defaultProp): this() { - this.PutAll(defaultProp._properties); + PutAll(defaultProp._properties); } public void PutAll(Hashtable properties) { foreach (var key in properties.Keys) { - this._properties.Put(key, properties[key]); + //_properties.Add(key, properties[key]); + _properties.Put(key, properties[key]); } } public void SetProperty(object key, object value) { - this._properties.Put(key, value); + //_properties.Add(key, value); + _properties.Put(key, value); } public object GetProperty(object key) { - return this._properties.Keys.Contains(key) - ? this._properties[key] - : null; + return _properties.Keys.Contains(key) ? _properties[key] : null; } public object GetProperty(object key, object def) { - return this._properties.Get(key) ?? def; + /*if (_properties.ContainsKey(key)) + { + return _properties[key]; + } + return def;*/ + object value = _properties.Get(key); + + return value ?? def; } public void Load(InputStream input) { - using (var reader = new StreamReader(input)) + StreamReader sr = new StreamReader(input); + while (!sr.EndOfStream) { - while (!reader.EndOfStream) - { - var line = reader.ReadLine(); - - if (string.IsNullOrEmpty(line)) - continue; + string line = sr.ReadLine(); - var tokens = line.Split('='); - - if (tokens.Length < 2) - continue; - - this._properties.Put(tokens[0], tokens[1]); + if (!string.IsNullOrEmpty(line)) + { + string[] tokens = line.Split('='); + //_properties.Add(tokens[0], tokens[1]); + _properties.Put(tokens[0], tokens[1]); } } } public void Store(OutputStream output) { - using (var writer = new StreamWriter(output)) + StreamWriter sw = new StreamWriter(output); + foreach (var key in _properties.Keys) { - foreach (var pair in this._properties) - writer.WriteLine($"{pair.Key}={pair.Value}"); + string line = string.Format("{0}={1}", key, _properties[key]); + sw.WriteLine(line); } } public void Store(TextWriter output) - { - foreach (var pair in this._properties) - output.WriteLine($"{pair.Key}={pair.Value}"); + { + foreach (var key in _properties.Keys) + { + string line = string.Format("{0}={1}", key, _properties[key]); + output.WriteLine(line); + } } } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs index 5d306b8f1b..bf3596212f 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/RandomAccessFile.cs @@ -4,86 +4,84 @@ using System.IO; namespace SharpCifs.Util.Sharpen { public class RandomAccessFile - { - private FileStream _stream; + { + private FileStream _stream; - public RandomAccessFile(FilePath file, string mode) : this(file.GetPath(), mode) - { - } + public RandomAccessFile (FilePath file, string mode) : this(file.GetPath (), mode) + { + } - public RandomAccessFile(string file, string mode) - { - if (mode.IndexOf('w') != -1) - _stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite); - else - _stream = new FileStream(file, FileMode.Open, FileAccess.Read); - } + public RandomAccessFile (string file, string mode) + { + if (mode.IndexOf ('w') != -1) + _stream = new FileStream (file, FileMode.OpenOrCreate, FileAccess.ReadWrite); + else + _stream = new FileStream (file, FileMode.Open, FileAccess.Read); + } - public void Close() - { + public void Close () + { //Stream.`Close` method deleted //_stream.Close (); _stream.Dispose(); } - public long GetFilePointer() - { - return _stream.Position; - } + public long GetFilePointer () + { + return _stream.Position; + } - public long Length() - { - return _stream.Length; - } + public long Length () + { + return _stream.Length; + } - public int Read(byte[] buffer) - { - int r = _stream.Read(buffer, 0, buffer.Length); - return r > 0 ? r : -1; - } + public int Read (byte[] buffer) + { + int r = _stream.Read (buffer, 0, buffer.Length); + return r > 0 ? r : -1; + } - public int Read(byte[] buffer, int start, int size) - { - return _stream.Read(buffer, start, size); - } + public int Read (byte[] buffer, int start, int size) + { + return _stream.Read (buffer, start, size); + } - public void ReadFully(byte[] buffer, int start, int size) - { - while (size > 0) - { - int num = _stream.Read(buffer, start, size); - if (num == 0) - { - throw new EofException(); - } - size -= num; - start += num; - } - } + public void ReadFully (byte[] buffer, int start, int size) + { + while (size > 0) { + int num = _stream.Read (buffer, start, size); + if (num == 0) { + throw new EofException (); + } + size -= num; + start += num; + } + } - public void Seek(long pos) - { - _stream.Position = pos; - } - - public void SetLength(long len) - { - _stream.SetLength(len); - } + public void Seek (long pos) + { + _stream.Position = pos; + } - public void Write(int value) - { - _stream.Write(BitConverter.GetBytes(value), 0, 4); - } + public void SetLength (long len) + { + _stream.SetLength (len); + } - public void Write(byte[] buffer) - { - _stream.Write(buffer, 0, buffer.Length); - } + public void Write (int value) + { + _stream.Write (BitConverter.GetBytes (value), 0, 4); + } + + public void Write (byte[] buffer) + { + _stream.Write (buffer, 0, buffer.Length); + } - public void Write(byte[] buffer, int start, int size) - { - _stream.Write(buffer, start, size); - } - } + public void Write (byte[] buffer, int start, int size) + { + _stream.Write (buffer, start, size); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs index a19f13fb9b..aa34db9d05 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ReentrantLock.cs @@ -3,20 +3,20 @@ using System.Threading; namespace SharpCifs.Util.Sharpen { internal class ReentrantLock - { - public void Lock() - { - Monitor.Enter(this); - } + { + public void Lock () + { + Monitor.Enter (this); + } - public bool TryLock() - { - return Monitor.TryEnter(this); - } + public bool TryLock () + { + return Monitor.TryEnter (this); + } - public void Unlock() - { - Monitor.Exit(this); - } - } + public void Unlock () + { + Monitor.Exit (this); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs index 5199fe32ce..c7fbe9a488 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Reference.cs @@ -1,7 +1,7 @@ namespace SharpCifs.Util.Sharpen { internal abstract class Reference<T> - { - public abstract T Get(); - } + { + public abstract T Get (); + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs index c15835ea4b..74ff16b1bb 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Runtime.cs @@ -8,208 +8,205 @@ using System.Threading; namespace SharpCifs.Util.Sharpen { - public class Runtime - { - private static Runtime _instance; - private List<ShutdownHook> _shutdownHooks = new List<ShutdownHook>(); - - internal void AddShutdownHook(IRunnable r) - { - ShutdownHook item = new ShutdownHook(); - item.Runnable = r; - _shutdownHooks.Add(item); - } - - internal int AvailableProcessors() - { - return Environment.ProcessorCount; - } - - public static long CurrentTimeMillis() - { - return DateTime.UtcNow.ToMillisecondsSinceEpoch(); - } - - static Hashtable _properties; - - public static Hashtable GetProperties() - { - if (_properties == null) - { - _properties = new Hashtable(); - _properties["jgit.fs.debug"] = "false"; - _properties["file.encoding"] = "UTF-8"; - if (Path.DirectorySeparatorChar != '\\') - _properties["os.name"] = "Unix"; - else - _properties["os.name"] = "Windows"; - } - return _properties; - } - - public static string GetProperty(string key) - { - if (GetProperties().Keys.Contains(key)) + public class Runtime + { + private static Runtime _instance; + private List<ShutdownHook> _shutdownHooks = new List<ShutdownHook> (); + + internal void AddShutdownHook (IRunnable r) + { + ShutdownHook item = new ShutdownHook (); + item.Runnable = r; + _shutdownHooks.Add (item); + } + + internal int AvailableProcessors () + { + return Environment.ProcessorCount; + } + + public static long CurrentTimeMillis () + { + return DateTime.UtcNow.ToMillisecondsSinceEpoch (); + } + + static Hashtable _properties; + + public static Hashtable GetProperties () + { + if (_properties == null) { + _properties = new Hashtable (); + _properties ["jgit.fs.debug"] = "false"; + _properties["file.encoding"] = "UTF-8"; + if (Path.DirectorySeparatorChar != '\\') + _properties ["os.name"] = "Unix"; + else + _properties ["os.name"] = "Windows"; + } + return _properties; + } + + public static string GetProperty (string key) + { + if (GetProperties().Keys.Contains(key)) { return ((string)GetProperties()[key]); } - return null; - } - - public static void SetProperty(string key, string value) - { - GetProperties()[key] = value; - } - - public static Runtime GetRuntime() - { - if (_instance == null) - { - _instance = new Runtime(); - } - return _instance; - } - - public static int IdentityHashCode(object ob) - { - return RuntimeHelpers.GetHashCode(ob); - } - - internal long MaxMemory() - { - return int.MaxValue; - } - - private class ShutdownHook - { - public IRunnable Runnable; - - ~ShutdownHook() - { - Runnable.Run(); - } - } - - public static void DeleteCharAt(StringBuilder sb, int index) - { - sb.Remove(index, 1); - } - - public static byte[] GetBytesForString(string str) - { - return Encoding.UTF8.GetBytes(str); - } - - public static byte[] GetBytesForString(string str, string encoding) - { - return Encoding.GetEncoding(encoding).GetBytes(str); - } - - public static FieldInfo[] GetDeclaredFields(Type t) - { + return null; + } + + public static void SetProperty (string key, string value) + { + GetProperties () [key] = value; + } + + public static Runtime GetRuntime () + { + if (_instance == null) { + _instance = new Runtime (); + } + return _instance; + } + + public static int IdentityHashCode (object ob) + { + return RuntimeHelpers.GetHashCode (ob); + } + + internal long MaxMemory () + { + return int.MaxValue; + } + + private class ShutdownHook + { + public IRunnable Runnable; + + ~ShutdownHook () + { + Runnable.Run (); + } + } + + public static void DeleteCharAt (StringBuilder sb, int index) + { + sb.Remove (index, 1); + } + + public static byte[] GetBytesForString (string str) + { + return Encoding.UTF8.GetBytes (str); + } + + public static byte[] GetBytesForString (string str, string encoding) + { + return Encoding.GetEncoding (encoding).GetBytes (str); + } + + public static FieldInfo[] GetDeclaredFields (Type t) + { throw new NotImplementedException("Type.GetFields not found on .NetStandard"); - //return t.GetFields (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - } - - public static void NotifyAll(object ob) - { - Monitor.PulseAll(ob); - } - - public static void Notify(object obj) - { - Monitor.Pulse(obj); - } - - public static void PrintStackTrace(Exception ex) - { - Console.WriteLine(ex); - } - - public static void PrintStackTrace(Exception ex, TextWriter tw) - { - tw.WriteLine(ex); - } - - public static string Substring(string str, int index) - { - return str.Substring(index); - } - - public static string Substring(string str, int index, int endIndex) - { - return str.Substring(index, endIndex - index); - } - - public static void Wait(object ob) - { - Monitor.Wait(ob); - } - - public static bool Wait(object ob, long milis) - { - return Monitor.Wait(ob, (int)milis); - } - - public static Type GetType(string name) - { - throw new NotImplementedException( - "AppDomain.CurrentDomain.GetAssemblies not found on .NetStandard"); - //foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) { - // Type t = a.GetType (name); - // if (t != null) - // return t; - //} + //return t.GetFields (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); + } + + public static void NotifyAll (object ob) + { + Monitor.PulseAll (ob); + } + + public static void Notify(object obj) + { + Monitor.Pulse(obj); + } + + public static void PrintStackTrace (Exception ex) + { + Console.WriteLine (ex); + } + + public static void PrintStackTrace (Exception ex, TextWriter tw) + { + tw.WriteLine (ex); + } + + public static string Substring (string str, int index) + { + return str.Substring (index); + } + + public static string Substring (string str, int index, int endIndex) + { + return str.Substring (index, endIndex - index); + } + + public static void Wait (object ob) + { + Monitor.Wait (ob); + } + + public static bool Wait (object ob, long milis) + { + return Monitor.Wait (ob, (int)milis); + } + + public static Type GetType (string name) + { + throw new NotImplementedException("AppDomain.CurrentDomain.GetAssemblies not found on .NetStandard"); + //foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies ()) { + // Type t = a.GetType (name); + // if (t != null) + // return t; + //} //never used - //throw new InvalidOperationException ("Type not found: " + name); - } - - public static void SetCharAt(StringBuilder sb, int index, char c) - { - sb[index] = c; - } - - public static bool EqualsIgnoreCase(string s1, string s2) - { - return s1.Equals(s2, StringComparison.CurrentCultureIgnoreCase); - } - - internal static long NanoTime() - { - return Environment.TickCount * 1000 * 1000; - } - - internal static int CompareOrdinal(string s1, string s2) - { - return string.CompareOrdinal(s1, s2); - } - - public static string GetStringForBytes(byte[] chars) - { - return Encoding.UTF8.GetString(chars, 0, chars.Length); - } - - public static string GetStringForBytes(byte[] chars, string encoding) - { - return GetEncoding(encoding).GetString(chars, 0, chars.Length); - } - - public static string GetStringForBytes(byte[] chars, int start, int len) - { - return Encoding.UTF8.GetString(chars, start, len); - } - - public static string GetStringForBytes(byte[] chars, int start, int len, string encoding) - { - return GetEncoding(encoding).Decode(chars, start, len); - } - - public static Encoding GetEncoding(string name) - { - Encoding e = Encoding.GetEncoding(name.Replace('_', '-')); - if (e is UTF8Encoding) - return new UTF8Encoding(false, true); - return e; - } - } + //throw new InvalidOperationException ("Type not found: " + name); + } + + public static void SetCharAt (StringBuilder sb, int index, char c) + { + sb [index] = c; + } + + public static bool EqualsIgnoreCase (string s1, string s2) + { + return s1.Equals (s2, StringComparison.CurrentCultureIgnoreCase); + } + + internal static long NanoTime () + { + return Environment.TickCount * 1000 * 1000; + } + + internal static int CompareOrdinal (string s1, string s2) + { + return string.CompareOrdinal (s1, s2); + } + + public static string GetStringForBytes (byte[] chars) + { + return Encoding.UTF8.GetString (chars, 0, chars.Length); + } + + public static string GetStringForBytes (byte[] chars, string encoding) + { + return GetEncoding (encoding).GetString (chars, 0, chars.Length); + } + + public static string GetStringForBytes (byte[] chars, int start, int len) + { + return Encoding.UTF8.GetString (chars, start, len); + } + + public static string GetStringForBytes (byte[] chars, int start, int len, string encoding) + { + return GetEncoding (encoding).Decode (chars, start, len); + } + + public static Encoding GetEncoding (string name) + { + Encoding e = Encoding.GetEncoding (name.Replace ('_','-')); + if (e is UTF8Encoding) + return new UTF8Encoding (false, true); + return e; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs index fb64c133f4..35334b4f2a 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SimpleDateFormat.cs @@ -4,63 +4,59 @@ using System.Globalization; namespace SharpCifs.Util.Sharpen { public class SimpleDateFormat : DateFormat - { - string _format; - - CultureInfo Culture - { - get; set; - } - - bool Lenient - { - get; set; - } - - public SimpleDateFormat() : this("g") - { - } - - public SimpleDateFormat(string format) : this(format, CultureInfo.CurrentCulture) - { - } - - public SimpleDateFormat(string format, CultureInfo c) - { - Culture = c; - this._format = format.Replace("EEE", "ddd"); - this._format = this._format.Replace("Z", "zzz"); - SetTimeZone(TimeZoneInfo.Local); - } - - public bool IsLenient() - { - return Lenient; - } - - public void SetLenient(bool lenient) - { - Lenient = lenient; - } - - public override DateTime Parse(string value) - { - if (IsLenient()) - return DateTime.Parse(value); - return DateTime.ParseExact(value, _format, Culture); - } - - public override string Format(DateTime date) - { - date += GetTimeZone().BaseUtcOffset; - return date.ToString(_format); - } - - public string Format(long date) - { - return Extensions.MillisToDateTimeOffset(date, (int)GetTimeZone().BaseUtcOffset - .TotalMinutes) - .DateTime.ToString(_format); - } - } + { + string _format; + + CultureInfo Culture { + get; set; + } + + bool Lenient { + get; set; + } + + public SimpleDateFormat (): this ("g") + { + } + + public SimpleDateFormat (string format): this (format, CultureInfo.CurrentCulture) + { + } + + public SimpleDateFormat (string format, CultureInfo c) + { + Culture = c; + this._format = format.Replace ("EEE", "ddd"); + this._format = this._format.Replace ("Z", "zzz"); + SetTimeZone (TimeZoneInfo.Local); + } + + public bool IsLenient () + { + return Lenient; + } + + public void SetLenient (bool lenient) + { + Lenient = lenient; + } + + public override DateTime Parse (string value) + { + if (IsLenient ()) + return DateTime.Parse (value); + return DateTime.ParseExact (value, _format, Culture); + } + + public override string Format (DateTime date) + { + date += GetTimeZone().BaseUtcOffset; + return date.ToString (_format); + } + + public string Format (long date) + { + return Extensions.MillisToDateTimeOffset (date, (int)GetTimeZone ().BaseUtcOffset.TotalMinutes).DateTime.ToString (_format); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs index 88aa9e4e6d..4d06519498 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SocketEx.cs @@ -23,7 +23,7 @@ namespace SharpCifs.Util.Sharpen { public class SocketEx : Socket { - private int _soTimeOut = -1; + private int _soTimeOut = -1; public int SoTimeOut { @@ -46,9 +46,7 @@ namespace SharpCifs.Util.Sharpen } } - public SocketEx(AddressFamily addressFamily, - SocketType socketType, - ProtocolType protocolType) + public SocketEx(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) : base(addressFamily, socketType, protocolType) { diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs index 4f3f41e7e9..c105a8bab6 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/SynchronizedList.cs @@ -4,120 +4,103 @@ using System.Collections.Generic; namespace SharpCifs.Util.Sharpen { internal class SynchronizedList<T> : IList<T> - { - private IList<T> _list; + { + private IList<T> _list; - public SynchronizedList(IList<T> list) - { - this._list = list; - } + public SynchronizedList (IList<T> list) + { + this._list = list; + } - public int IndexOf(T item) - { - lock (_list) - { - return _list.IndexOf(item); - } - } + public int IndexOf (T item) + { + lock (_list) { + return _list.IndexOf (item); + } + } - public void Insert(int index, T item) - { - lock (_list) - { - _list.Insert(index, item); - } - } + public void Insert (int index, T item) + { + lock (_list) { + _list.Insert (index, item); + } + } - public void RemoveAt(int index) - { - lock (_list) - { - _list.RemoveAt(index); - } - } + public void RemoveAt (int index) + { + lock (_list) { + _list.RemoveAt (index); + } + } - void ICollection<T>.Add(T item) - { - lock (_list) - { - _list.Add(item); - } - } + void ICollection<T>.Add (T item) + { + lock (_list) { + _list.Add (item); + } + } - void ICollection<T>.Clear() - { - lock (_list) - { - _list.Clear(); - } - } + void ICollection<T>.Clear () + { + lock (_list) { + _list.Clear (); + } + } - bool ICollection<T>.Contains(T item) - { - lock (_list) - { - return _list.Contains(item); - } - } + bool ICollection<T>.Contains (T item) + { + lock (_list) { + return _list.Contains (item); + } + } - void ICollection<T>.CopyTo(T[] array, int arrayIndex) - { - lock (_list) - { - _list.CopyTo(array, arrayIndex); - } - } + void ICollection<T>.CopyTo (T[] array, int arrayIndex) + { + lock (_list) { + _list.CopyTo (array, arrayIndex); + } + } - bool ICollection<T>.Remove(T item) - { - lock (_list) - { - return _list.Remove(item); - } - } + bool ICollection<T>.Remove (T item) + { + lock (_list) { + return _list.Remove (item); + } + } - IEnumerator<T> IEnumerable<T>.GetEnumerator() - { - return _list.GetEnumerator(); - } + IEnumerator<T> IEnumerable<T>.GetEnumerator () + { + return _list.GetEnumerator (); + } - IEnumerator IEnumerable.GetEnumerator() - { - return _list.GetEnumerator(); - } + IEnumerator IEnumerable.GetEnumerator () + { + return _list.GetEnumerator (); + } - public T this[int index] - { - get - { - lock (_list) - { - return _list[index]; - } - } - set - { - lock (_list) - { - _list[index] = value; - } - } - } + public T this[int index] { + get { + lock (_list) { + return _list[index]; + } + } + set { + lock (_list) { + _list[index] = value; + } + } + } - int ICollection<T>.Count - { - get - { - lock (_list) - { - return _list.Count; - } - } - } + int ICollection<T>.Count { + get { + lock (_list) { + return _list.Count; + } + } + } - bool ICollection<T>.IsReadOnly - { - get { return _list.IsReadOnly; } - } - } + bool ICollection<T>.IsReadOnly { + get { return _list.IsReadOnly; } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs index 9d874a0fa8..59f3df4699 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/Thread.cs @@ -1,314 +1,193 @@ -using SharpCifs.Util.DbsHelper; using System; using System.Collections.Generic; -using System.Threading; namespace SharpCifs.Util.Sharpen { public class Thread : IRunnable - { - private static ThreadGroup DefaultGroup = new ThreadGroup(); - - [ThreadStatic] - private static Thread WrapperThread; - - public static Thread CurrentThread() - { - if (Thread.WrapperThread == null) - { - Thread.WrapperThread = new Thread(System.Environment.CurrentManagedThreadId); - } - - return Thread.WrapperThread; - } - - - public CancellationTokenSource Canceller => this._canceller; - - public bool IsCanceled - { - get - { - if (this._canceller?.IsCancellationRequested == true - && !this._isCanceled) - { - this._isCanceled = true; - } - - return this._isCanceled; - } - } - - private IRunnable _runnable; - private ThreadGroup _tgroup; - private System.Threading.Tasks.Task _task = null; - private CancellationTokenSource _canceller = null; - - private string _name = string.Empty; - private bool _isBackground = true; - private bool _interrupted = false; - private int? _id = null; - private bool _isRunning = false; - private bool _isCanceled = false; - - - - public Thread() : this(null, null, null) - { - } - - - public Thread(string name) : this(null, null, name) - { - } - - - public Thread(ThreadGroup grp, string name) : this(null, grp, name) - { - } - - - public Thread(IRunnable runnable) : this(runnable, null, null) - { - } - - - private Thread(IRunnable runnable, ThreadGroup grp, string name) - { - this._runnable = runnable ?? this; - this._tgroup = grp ?? DefaultGroup; - this._tgroup.Add(this); - - if (name != null) - { - this._name = name; - } - } - - - private Thread(int threadId) - { - this._id = threadId; - - this._tgroup = DefaultGroup; - this._tgroup.Add(this); - } - - - public string GetName() - { - return this._name; - } - - - public ThreadGroup GetThreadGroup() - { - return this._tgroup; - } - - - public static void Yield() - { - } - - - public void Interrupt() - { - this._interrupted = true; - this._canceller?.Cancel(true); - } - - - public static bool Interrupted() - { - if (Thread.WrapperThread == null) - { - return false; - } - - Thread wrapperThread = Thread.WrapperThread; - lock (wrapperThread) - { - bool interrupted = Thread.WrapperThread._interrupted; - Thread.WrapperThread._interrupted = false; - return interrupted; - } - } - - - public bool IsAlive() - { - if (this._task == null) - return true; //実行されていない - - //Taskが存在し、続行中のときtrue - return (!this._task.IsCanceled - && !this._task.IsFaulted - && !this._task.IsCompleted); - } - - - public void Join() - { - this._task?.Wait(); - } - - - public void Join(long timeout) - { - this._task?.Wait((int) timeout); - } - - - public virtual void Run() - { - } - - - public void SetDaemon(bool daemon) - { - this._isBackground = daemon; - } - - - public void SetName(string name) - { - this._name = name; - } - - - public static void Sleep(long milis) - { - System.Threading.Tasks.Task.Delay((int) milis).Wait(); - } - - - public void Start(bool isSynced = false) - { - if (this._isRunning) - throw new InvalidOperationException("Thread Already started."); - - this._canceller = new CancellationTokenSource(); - - this._task = System.Threading.Tasks.Task.Run(() => - { - Thread.WrapperThread = this; - this._id = System.Environment.CurrentManagedThreadId; - - //Log.Out("Thread.Start - Task Start"); - this._isRunning = true; - - try - { - this._runnable.Run(); - //Log.Out("Thread.Start - Task Normaly End"); - } - catch (Exception exception) - { - //Log.Out("Thread.Start - Task Error End"); - Console.WriteLine(exception); - } - finally - { - this._isRunning = false; - - this._tgroup?.Remove(this); - - this._canceller?.Dispose(); - this._canceller = null; - - //Log.Out("Thread.Start - Task Close Completed"); - } - }, this._canceller.Token); - - //同期的に実行するとき、動作中フラグONまで待つ。 - if (isSynced) - while (!this._isRunning) - System.Threading.Tasks.Task.Delay(300).GetAwaiter().GetResult(); - } - - - public void Cancel(bool isSynced = false) - { - //Log.Out("Thread.Cancel"); - - this._isCanceled = true; - this._canceller?.Cancel(true); - - //同期的に実行するとき、動作中フラグOFFまで待つ。 - if (isSynced) - while (this._isRunning) - System.Threading.Tasks.Task.Delay(300).GetAwaiter().GetResult(); - } - - - public bool Equals(Thread thread) - { - //渡し値スレッドがnullのとき、合致しない - if (thread == null) - return false; - - //自身か渡し値スレッドの、スレッドIDが取得出来ていない(=スレッド未生成) - // →合致しない - if (this._id == null - || thread._id == null) - return false; - - return (this._id == thread._id); - } - - - public void Dispose() - { - //Log.Out("Thread.Dispose"); - - this._runnable = null; - this._tgroup = null; - this._task = null; - this._canceller?.Dispose(); - this._canceller = null; - this._name = null; - this._isRunning = false; - this._id = null; - } - } - - public class ThreadGroup - { - private List<Thread> _threads = new List<Thread>(); - - public ThreadGroup() - { - } - - public ThreadGroup(string name) - { - } - - internal void Add(Thread t) - { - lock (_threads) - { - _threads.Add(t); - } - } - - internal void Remove(Thread t) - { - lock (_threads) - { - _threads.Remove(t); + { + private static ThreadGroup _defaultGroup = new ThreadGroup (); + private bool _interrupted; + private IRunnable _runnable; + private ThreadGroup _tgroup; + private System.Threading.Thread _thread; + + [ThreadStatic] + private static Thread _wrapperThread; + + public Thread () : this(null, null, null) + { + } + + public Thread (string name) : this (null, null, name) + { + } + + public Thread (ThreadGroup grp, string name) : this (null, grp, name) + { + } + + public Thread (IRunnable runnable): this (runnable, null, null) + { + } + + Thread (IRunnable runnable, ThreadGroup grp, string name) + { + _thread = new System.Threading.Thread (InternalRun); + + this._runnable = runnable ?? this; + _tgroup = grp ?? _defaultGroup; + _tgroup.Add (this); + if (name != null) + _thread.Name = name; + } + + private Thread (System.Threading.Thread t) + { + _thread = t; + _tgroup = _defaultGroup; + _tgroup.Add (this); + } + + public static Thread CurrentThread () + { + if (_wrapperThread == null) { + _wrapperThread = new Thread (System.Threading.Thread.CurrentThread); + } + return _wrapperThread; + } + + public string GetName () + { + return _thread.Name; + } + + public ThreadGroup GetThreadGroup () + { + return _tgroup; + } + + private void InternalRun () + { + _wrapperThread = this; + try { + _runnable.Run (); + } catch (Exception exception) { + Console.WriteLine (exception); + } finally { + _tgroup.Remove (this); + } + } + + public static void Yield () + { + } + + public void Interrupt () + { + lock (_thread) { + _interrupted = true; + //thread.Interrupt (); + + //TODO: implement CancellationToken + //_thread.Abort(); + throw new NotImplementedException("implement CancellationToken for thread"); } } - public int Enumerate(Thread[] array) - { - lock (_threads) - { - int count = Math.Min(array.Length, _threads.Count); - _threads.CopyTo(0, array, 0, count); - return count; - } - } - } + public static bool Interrupted () + { + if (Thread._wrapperThread == null) { + return false; + } + Thread wrapperThread = Thread._wrapperThread; + lock (wrapperThread) { + bool interrupted = Thread._wrapperThread._interrupted; + Thread._wrapperThread._interrupted = false; + return interrupted; + } + } + + public bool IsAlive () + { + return _thread.IsAlive; + } + + public void Join () + { + _thread.Join (); + } + + public void Join (long timeout) + { + _thread.Join ((int)timeout); + } + + public virtual void Run () + { + } + + public void SetDaemon (bool daemon) + { + _thread.IsBackground = daemon; + } + + public void SetName (string name) + { + _thread.Name = name; + } + + public static void Sleep (long milis) + { + System.Threading.Thread.Sleep ((int)milis); + } + + public void Start () + { + _thread.Start (); + } + + public void Abort () + { + //TODO: implement CancellationToken + //_thread.Abort (); + throw new NotImplementedException("implement CancellationToken for thread"); + } + + } + + public class ThreadGroup + { + private List<Thread> _threads = new List<Thread> (); + + public ThreadGroup() + { + } + + public ThreadGroup (string name) + { + } + + internal void Add (Thread t) + { + lock (_threads) { + _threads.Add (t); + } + } + + internal void Remove (Thread t) + { + lock (_threads) { + _threads.Remove (t); + } + } + + public int Enumerate (Thread[] array) + { + lock (_threads) { + int count = Math.Min (array.Length, _threads.Count); + _threads.CopyTo (0, array, 0, count); + return count; + } + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs index 539ebedcf4..7276c06a2c 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadFactory.cs @@ -1,16 +1,13 @@ -using System.Threading.Tasks; - namespace SharpCifs.Util.Sharpen { - internal class ThreadFactory - { - public Thread NewThread(IRunnable r) - { - Thread t = new Thread(r); - t.SetDaemon(true); - t.Start(true); - - return t; - } - } + internal class ThreadFactory + { + public Thread NewThread (IRunnable r) + { + Thread t = new Thread (r); + t.SetDaemon (true); + t.Start (); + return t; + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs index c8b2179b8a..ef19b8bff5 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/ThreadPoolExecutor.cs @@ -4,180 +4,163 @@ using ST = System.Threading; namespace SharpCifs.Util.Sharpen { - class ThreadPoolExecutor - { - ThreadFactory _tf; - int _corePoolSize; - int _maxPoolSize; - List<Thread> _pool = new List<Thread>(); - int _runningThreads; - int _freeThreads; - bool _shutdown; - Queue<IRunnable> _pendingTasks = new Queue<IRunnable>(); - - public ThreadPoolExecutor(int corePoolSize, ThreadFactory factory) - { - this._corePoolSize = corePoolSize; - _maxPoolSize = corePoolSize; - _tf = factory; - } - - public void SetMaximumPoolSize(int size) - { - _maxPoolSize = size; - } - - public bool IsShutdown() - { - return _shutdown; - } - - public virtual bool IsTerminated() - { - lock (_pendingTasks) - { - return _shutdown && _pendingTasks.Count == 0; - } - } - - public virtual bool IsTerminating() - { - lock (_pendingTasks) - { - return _shutdown && !IsTerminated(); - } - } - - public int GetCorePoolSize() - { - return _corePoolSize; - } - - public void PrestartAllCoreThreads() - { - lock (_pendingTasks) - { - while (_runningThreads < _corePoolSize) - StartPoolThread(); - } - } - - public void SetThreadFactory(ThreadFactory f) - { - _tf = f; - } - - public void Execute(IRunnable r) - { - InternalExecute(r, true); - } - - internal void InternalExecute(IRunnable r, bool checkShutdown) - { - lock (_pendingTasks) - { - if (_shutdown && checkShutdown) - throw new InvalidOperationException(); - if (_runningThreads < _corePoolSize) - { - StartPoolThread(); - } - else if (_freeThreads > 0) - { - _freeThreads--; - } - else if (_runningThreads < _maxPoolSize) - { - StartPoolThread(); - } - _pendingTasks.Enqueue(r); - ST.Monitor.PulseAll(_pendingTasks); - } - } - - void StartPoolThread() - { - _runningThreads++; - _pool.Add(_tf.NewThread(new RunnableAction(RunPoolThread))); - } - - public void RunPoolThread() - { - while (!IsTerminated()) - { - try - { - IRunnable r = null; - lock (_pendingTasks) - { - _freeThreads++; - while (!IsTerminated() && _pendingTasks.Count == 0) - ST.Monitor.Wait(_pendingTasks); - if (IsTerminated()) - break; - r = _pendingTasks.Dequeue(); - } - if (r != null) - r.Run(); - } + class ThreadPoolExecutor + { + ThreadFactory _tf; + int _corePoolSize; + int _maxPoolSize; + List<Thread> _pool = new List<Thread> (); + int _runningThreads; + int _freeThreads; + bool _shutdown; + Queue<IRunnable> _pendingTasks = new Queue<IRunnable> (); + + public ThreadPoolExecutor (int corePoolSize, ThreadFactory factory) + { + this._corePoolSize = corePoolSize; + _maxPoolSize = corePoolSize; + _tf = factory; + } + + public void SetMaximumPoolSize (int size) + { + _maxPoolSize = size; + } + + public bool IsShutdown () + { + return _shutdown; + } + + public virtual bool IsTerminated () + { + lock (_pendingTasks) { + return _shutdown && _pendingTasks.Count == 0; + } + } + + public virtual bool IsTerminating () + { + lock (_pendingTasks) { + return _shutdown && !IsTerminated (); + } + } + + public int GetCorePoolSize () + { + return _corePoolSize; + } + + public void PrestartAllCoreThreads () + { + lock (_pendingTasks) { + while (_runningThreads < _corePoolSize) + StartPoolThread (); + } + } + + public void SetThreadFactory (ThreadFactory f) + { + _tf = f; + } + + public void Execute (IRunnable r) + { + InternalExecute (r, true); + } + + internal void InternalExecute (IRunnable r, bool checkShutdown) + { + lock (_pendingTasks) { + if (_shutdown && checkShutdown) + throw new InvalidOperationException (); + if (_runningThreads < _corePoolSize) { + StartPoolThread (); + } + else if (_freeThreads > 0) { + _freeThreads--; + } + else if (_runningThreads < _maxPoolSize) { + StartPoolThread (); + } + _pendingTasks.Enqueue (r); + ST.Monitor.PulseAll (_pendingTasks); + } + } + + void StartPoolThread () + { + _runningThreads++; + _pool.Add (_tf.NewThread (new RunnableAction (RunPoolThread))); + } + + public void RunPoolThread () + { + while (!IsTerminated ()) { + try { + IRunnable r = null; + lock (_pendingTasks) { + _freeThreads++; + while (!IsTerminated () && _pendingTasks.Count == 0) + ST.Monitor.Wait (_pendingTasks); + if (IsTerminated ()) + break; + r = _pendingTasks.Dequeue (); + } + if (r != null) + r.Run (); + } //supress all errors, anyway - //catch (ST.ThreadAbortException) { - // // Do not catch a thread abort. If we've been aborted just let the thread die. - // // Currently reseting an abort which was issued because the appdomain is being - // // torn down results in the process living forever and consuming 100% cpu time. - // return; - //} - catch - { - } - } - } - - public virtual void Shutdown() - { - lock (_pendingTasks) - { - _shutdown = true; - ST.Monitor.PulseAll(_pendingTasks); - } - } - - public virtual List<IRunnable> ShutdownNow() - { - lock (_pendingTasks) - { - _shutdown = true; - foreach (var t in _pool) - { - try - { - t.Cancel(true); - t.Dispose(); - } - catch { } - } - _pool.Clear(); - _freeThreads = 0; - _runningThreads = 0; - var res = new List<IRunnable>(_pendingTasks); - _pendingTasks.Clear(); - return res; - } - } - } - - class RunnableAction : IRunnable - { - Action _action; - - public RunnableAction(Action a) - { - _action = a; - } - - public void Run() - { - _action(); - } - } + //catch (ST.ThreadAbortException) { + // // Do not catch a thread abort. If we've been aborted just let the thread die. + // // Currently reseting an abort which was issued because the appdomain is being + // // torn down results in the process living forever and consuming 100% cpu time. + // return; + //} + catch { + } + } + } + + public virtual void Shutdown () + { + lock (_pendingTasks) { + _shutdown = true; + ST.Monitor.PulseAll (_pendingTasks); + } + } + + public virtual List<IRunnable> ShutdownNow () + { + lock (_pendingTasks) { + _shutdown = true; + foreach (var t in _pool) { + try { + t.Abort (); + } catch {} + } + _pool.Clear (); + _freeThreads = 0; + _runningThreads = 0; + var res = new List<IRunnable> (_pendingTasks); + _pendingTasks.Clear (); + return res; + } + } + } + + class RunnableAction: IRunnable + { + Action _action; + + public RunnableAction (Action a) + { + _action = a; + } + + public void Run () + { + _action (); + } + } } diff --git a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs index 6134ea89f4..ef2993fa61 100644 --- a/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs +++ b/Emby.Common.Implementations/IO/SharpCifs/Util/Sharpen/WrappedSystemStream.cs @@ -4,153 +4,136 @@ using System.IO; namespace SharpCifs.Util.Sharpen { internal class WrappedSystemStream : Stream - { - private InputStream _ist; - private OutputStream _ost; - int _position; - int _markedPosition; - - public WrappedSystemStream(InputStream ist) - { - this._ist = ist; - } - - public WrappedSystemStream(OutputStream ost) - { - this._ost = ost; - } - - public InputStream InputStream - { - get { return _ist; } - } - - public OutputStream OutputStream - { - get { return _ost; } - } + { + private InputStream _ist; + private OutputStream _ost; + int _position; + int _markedPosition; + + public WrappedSystemStream (InputStream ist) + { + this._ist = ist; + } + + public WrappedSystemStream (OutputStream ost) + { + this._ost = ost; + } + + public InputStream InputStream { + get { return _ist; } + } + + public OutputStream OutputStream { + get { return _ost; } + } public void Close() //remove `override` { - if (_ist != null) - { + if (_ist != null) { //Stream.`Close` method deleted - //_ist.Close (); + //_ist.Close (); _ist.Dispose(); - } - if (_ost != null) - { + } + if (_ost != null) { //Stream.`Close` method deleted - //_ost.Close (); + //_ost.Close (); _ost.Dispose(); - } - } - - public override void Flush() - { - _ost.Flush(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - int res = _ist.Read(buffer, offset, count); - if (res != -1) - { - _position += res; - return res; - } - return 0; - } - - public override int ReadByte() - { - int res = _ist.Read(); - if (res != -1) - _position++; - return res; - } - - public override long Seek(long offset, SeekOrigin origin) - { - if (origin == SeekOrigin.Begin) - Position = offset; - else if (origin == SeekOrigin.Current) - Position = Position + offset; - else if (origin == SeekOrigin.End) - Position = Length + offset; - return Position; - } - - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - _ost.Write(buffer, offset, count); - _position += count; - } - - public override void WriteByte(byte value) - { - _ost.Write(value); - _position++; - } - - public override bool CanRead - { - get { return (_ist != null); } - } - - public override bool CanSeek - { - get { return true; } - } - - public override bool CanWrite - { - get { return (_ost != null); } - } - - public override long Length - { - get { return _ist.Length; } - } - - internal void OnMark(int nb) - { - _markedPosition = _position; - _ist.Mark(nb); - } - - public override long Position - { - get - { - if (_ist != null && _ist.CanSeek()) - return _ist.Position; - return _position; - } - set - { - if (value == _position) - return; - - if (value == _markedPosition - && _ist.MarkSupported()) - { - _ist.Reset(); - } - else if (_ist != null && _ist.CanSeek()) - { - _ist.Position = value; - } - else - { - throw new NotSupportedException(); - } - } - } - } + } + } + + public override void Flush () + { + _ost.Flush (); + } + + public override int Read (byte[] buffer, int offset, int count) + { + int res = _ist.Read (buffer, offset, count); + if (res != -1) { + _position += res; + return res; + } + return 0; + } + + public override int ReadByte () + { + int res = _ist.Read (); + if (res != -1) + _position++; + return res; + } + + public override long Seek (long offset, SeekOrigin origin) + { + if (origin == SeekOrigin.Begin) + Position = offset; + else if (origin == SeekOrigin.Current) + Position = Position + offset; + else if (origin == SeekOrigin.End) + Position = Length + offset; + return Position; + } + + public override void SetLength (long value) + { + throw new NotSupportedException (); + } + + public override void Write (byte[] buffer, int offset, int count) + { + _ost.Write (buffer, offset, count); + _position += count; + } + + public override void WriteByte (byte value) + { + _ost.Write (value); + _position++; + } + + public override bool CanRead { + get { return (_ist != null); } + } + + public override bool CanSeek { + get { return true; } + } + + public override bool CanWrite { + get { return (_ost != null); } + } + + public override long Length { + get { return _ist.Length; } + } + + internal void OnMark (int nb) + { + _markedPosition = _position; + _ist.Mark (nb); + } + + public override long Position { + get + { + if (_ist != null && _ist.CanSeek ()) + return _ist.Position; + return _position; + } + set + { + if (value == _position) + return; + if (value == _markedPosition) + _ist.Reset (); + else if (_ist != null && _ist.CanSeek ()) { + _ist.Position = value; + } + else + throw new NotSupportedException (); + } + } + } } |
