Radarr/src/NzbDrone.Core/Fluent.cs

141 lines
3.4 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NzbDrone.Common.EnsureThat;
namespace NzbDrone.Core
{
public static class Fluent
{
public static string WithDefault(this string actual, object defaultValue)
{
Ensure.That(defaultValue, () => defaultValue).IsNotNull();
2020-11-06 02:43:08 +00:00
if (string.IsNullOrWhiteSpace(actual))
{
return defaultValue.ToString();
}
return actual;
}
public static long Megabytes(this int megabytes)
{
return Convert.ToInt64(megabytes * 1024L * 1024L);
}
public static long Gigabytes(this int gigabytes)
{
2013-07-17 07:33:54 +00:00
return Convert.ToInt64(gigabytes * 1024L * 1024L * 1024L);
}
public static long Megabytes(this double megabytes)
{
return Convert.ToInt64(megabytes * 1024L * 1024L);
}
public static long Gigabytes(this double gigabytes)
{
return Convert.ToInt64(gigabytes * 1024L * 1024L * 1024L);
}
public static long Round(this long number, long level)
{
return Convert.ToInt64(Math.Floor((decimal)number / level) * level);
}
public static string ToBestDateString(this DateTime dateTime)
{
if (dateTime == DateTime.Today.AddDays(-1))
2019-12-22 22:08:53 +00:00
{
return "Yesterday";
2019-12-22 22:08:53 +00:00
}
if (dateTime == DateTime.Today)
2019-12-22 22:08:53 +00:00
{
return "Today";
2019-12-22 22:08:53 +00:00
}
if (dateTime == DateTime.Today.AddDays(1))
2019-12-22 22:08:53 +00:00
{
return "Tomorrow";
2019-12-22 22:08:53 +00:00
}
if (dateTime > DateTime.Today.AddDays(1) && dateTime < DateTime.Today.AddDays(7))
2019-12-22 22:08:53 +00:00
{
return dateTime.DayOfWeek.ToString();
2019-12-22 22:08:53 +00:00
}
return dateTime.ToShortDateString();
}
public static int MaxOrDefault(this IEnumerable<int> ints)
{
if (ints == null)
2019-12-22 22:08:53 +00:00
{
return 0;
2019-12-22 22:08:53 +00:00
}
var intList = ints.ToList();
if (!intList.Any())
2019-12-22 22:08:53 +00:00
{
return 0;
2019-12-22 22:08:53 +00:00
}
return intList.Max();
}
public static string Truncate(this string s, int maxLength)
{
if (Encoding.UTF8.GetByteCount(s) <= maxLength)
2019-12-22 22:08:53 +00:00
{
return s;
2019-12-22 22:08:53 +00:00
}
var cs = s.ToCharArray();
var length = 0;
var i = 0;
while (i < cs.Length)
{
var charSize = 1;
if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
2019-12-22 22:08:53 +00:00
{
charSize = 2;
2019-12-22 22:08:53 +00:00
}
var byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
if ((byteSize + length) <= maxLength)
{
i = i + charSize;
length += byteSize;
}
else
2019-12-22 22:08:53 +00:00
{
break;
2019-12-22 22:08:53 +00:00
}
}
2019-12-22 22:08:53 +00:00
return s.Substring(0, i);
}
public static int MinOrDefault(this IEnumerable<int> ints)
{
if (ints == null)
2019-12-22 22:08:53 +00:00
{
return 0;
2019-12-22 22:08:53 +00:00
}
var intsList = ints.ToList();
if (!intsList.Any())
2019-12-22 22:08:53 +00:00
{
return 0;
2019-12-22 22:08:53 +00:00
}
return intsList.Min();
}
}
}