123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- using System.Linq;
- namespace FsDb
- {
- internal static class Utility
- {
- public static string CombineLocalPath(this string me, params string[] nexts)
- {
- if (me == null || nexts.Length == 0)
- throw new ArgumentNullException();
- string dsc = Path.DirectorySeparatorChar.ToString();
- var lst = nexts.ToList();// new List<string>();
- lst.Insert(0, me);
- return string.Join(
- dsc
- , lst.ToArray()
- )
- ;
- }
- public static IEnumerable<T> DoEach<T>(this IEnumerable<T> source, Action<T> actionToDo)
- {
- foreach (var item in source)
- {
- actionToDo(item);
- }
- return source;
- }
- public static byte[] ReadToEnd(this System.IO.Stream stream)
- {
- long originalPosition = 0;
- if (stream.CanSeek)
- {
- originalPosition = stream.Position;
- stream.Position = 0;
- }
- try
- {
- byte[] readBuffer = new byte[4096];
- int totalBytesRead = 0;
- int bytesRead;
- while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
- {
- totalBytesRead += bytesRead;
- if (totalBytesRead == readBuffer.Length)
- {
- int nextByte = stream.ReadByte();
- if (nextByte != -1)
- {
- byte[] temp = new byte[readBuffer.Length * 2];
- Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
- Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
- readBuffer = temp;
- totalBytesRead++;
- }
- }
- }
- byte[] buffer = readBuffer;
- if (readBuffer.Length != totalBytesRead)
- {
- buffer = new byte[totalBytesRead];
- Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
- }
- return buffer;
- }
- finally
- {
- if (stream.CanSeek)
- {
- stream.Position = originalPosition;
- }
- }
- }
- }
- internal static class TypeParser<T> where T : struct
- {
- private delegate bool conv(string value, out T result);
- private static readonly Type type;
- private static conv del;
- static TypeParser()
- {
- type = typeof(T);
- if (type.Name == "Nullable`1")
- throw new Exception();
- var mi = type.GetMethods().First(p => p.Name == "TryParse" && p.GetParameters().Length == 2);
- del = (conv)Delegate.CreateDelegate(typeof(conv), mi);
- }
- public static T Convert(object value)
- {
- if (value == null || value == DBNull.Value)
- return default(T);
- T result = default(T);
- del(value.ToString(), out result);
- return result;
- }
- public static T? ConvertNullable(object value)
- {
- if (value == null || value == DBNull.Value)
- return null;
- T result;
- if (del(value.ToString(), out result))
- return result;
- return null;
- }
- }
- }
|