using System; using System.IO; #if NET3 using Path = Net3_Proxy.Path; #endif namespace IPA.Utilities { /// /// A class providing various extension methods. /// public static class Extensions { /// /// Gets the default value for a given . /// /// the to get the default value for /// the default value of public static object GetDefault(this Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; } /// /// Unwraps a where T is such that if the value is null, it gives . /// /// the bool? to unwrap /// the unwrapped value, or if it was public static bool Unwrap(this bool? self) => self != null && self.Value; /// /// Returns true if starts with the path . /// The comparison is case-insensitive, handles / and \ slashes as folder separators and /// only matches if the base dir folder name is matched exactly ("c:\foobar\file.txt" is not a sub path of "c:\foo"). /// public static bool IsSubPathOf(this string path, string baseDirPath) { string normalizedPath = Path.GetFullPath(path.Replace('/', '\\') .WithEnding("\\")); string normalizedBaseDirPath = Path.GetFullPath(baseDirPath.Replace('/', '\\') .WithEnding("\\")); return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase); } /// /// Returns with the minimal concatenation of (starting from end) that /// results in satisfying .EndsWith(ending). /// /// "hel".WithEnding("llo") returns "hello", which is the result of "hel" + "lo". public static string WithEnding(this string str, string ending) { if (str == null) return ending; string result = str; // Right() is 1-indexed, so include these cases // * Append no characters // * Append up to N characters, where N is ending length for (int i = 0; i <= ending.Length; i++) { string tmp = result + ending.Right(i); if (tmp.EndsWith(ending)) return tmp; } return result; } /// Gets the rightmost characters from a string. /// The string to retrieve the substring from. /// The number of characters to retrieve. /// The substring. public static string Right(this string value, int length) { if (value == null) { throw new ArgumentNullException("value"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", length, "Length is less than zero"); } return (length < value.Length) ? value.Substring(value.Length - length) : value; } } }