♻ Refactor for UPM structure

This commit is contained in:
Oliver Booth 2020-07-15 16:21:14 +01:00
parent f4f8f52952
commit 59433272dc
59 changed files with 0 additions and 5196 deletions

View File

@ -1,215 +0,0 @@
# All files
[*]
guidelines = 130
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size=4
indent_style=space
tab_width=4
# New line preferences
end_of_line=crlf
insert_final_newline=true
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups=false
dotnet_sort_system_directives_first=true
# this. and Me. preferences
dotnet_style_qualification_for_event=true:suggestion
dotnet_style_qualification_for_field=true:suggestion
dotnet_style_qualification_for_method=true:suggestion
dotnet_style_qualification_for_property=true:suggestion
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members=true:warning
dotnet_style_predefined_type_for_member_access=true:warning
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators=always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators=always_for_clarity:silent
dotnet_style_parentheses_in_other_operators=never_if_unnecessary:silent
dotnet_style_parentheses_in_relational_binary_operators=always_for_clarity:silent
# Modifier preferences
dotnet_style_require_accessibility_modifiers=for_non_interface_members:silent
# Expression-level preferences
dotnet_style_coalesce_expression=true:suggestion
dotnet_style_collection_initializer=true:suggestion
dotnet_style_explicit_tuple_names=true:suggestion
dotnet_style_null_propagation=true:suggestion
dotnet_style_object_initializer=true:suggestion
dotnet_style_prefer_auto_properties=true:silent
dotnet_style_prefer_compound_assignment=true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment=true:silent
dotnet_style_prefer_conditional_expression_over_return=true:silent
dotnet_style_prefer_inferred_anonymous_type_member_names=false:suggestion
dotnet_style_prefer_inferred_tuple_names=false:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method=true:suggestion
dotnet_style_prefer_simplified_interpolation=true:suggestion
# Field preferences
dotnet_style_readonly_field=true:suggestion
# Parameter preferences
dotnet_code_quality_unused_parameters=all:suggestion
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere=true:warning
csharp_style_var_when_type_is_apparent=true:warning
csharp_style_var_for_built_in_types=true:warning
# Expression-bodied members
csharp_style_expression_bodied_accessors=true:suggestion
csharp_style_expression_bodied_constructors=false:suggestion
csharp_style_expression_bodied_indexers=true:suggestion
csharp_style_expression_bodied_lambdas=true:silent
csharp_style_expression_bodied_local_functions=false:silent
csharp_style_expression_bodied_methods=false:suggestion
csharp_style_expression_bodied_operators=false:suggestion
csharp_style_expression_bodied_properties=false:suggestion
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check=true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check=true:suggestion
csharp_style_prefer_switch_expression=true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call=true:suggestion
# Modifier preferences
csharp_prefer_static_local_function=true:suggestion
csharp_preferred_modifier_order=public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent
# Code-block preferences
csharp_prefer_braces=true:suggestion
csharp_prefer_simple_using_statement=true:suggestion
# Expression-level preferences
csharp_prefer_simple_default_expression=true:suggestion
csharp_style_deconstructed_variable_declaration=true:suggestion
csharp_style_inlined_variable_declaration=true:suggestion
csharp_style_pattern_local_over_anonymous_function=true:suggestion
csharp_style_prefer_index_operator=true:suggestion
csharp_style_prefer_range_operator=true:suggestion
csharp_style_throw_expression=true:suggestion
csharp_style_unused_value_assignment_preference=discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference=discard_variable:silent
# 'using' directive preferences
csharp_using_directive_placement=inside_namespace:suggestion
#### C# Formatting Rules ####
max_line_length=130
# New line preferences
csharp_new_line_before_catch=true
csharp_new_line_before_else=true
csharp_new_line_before_finally=true
csharp_new_line_before_members_in_anonymous_types=true
csharp_new_line_before_members_in_object_initializers=true
csharp_new_line_before_open_brace=all
csharp_new_line_between_query_expression_clauses=true
# Indentation preferences
csharp_indent_block_contents=true
csharp_indent_braces=false
csharp_indent_case_contents=true
csharp_indent_case_contents_when_block=true
csharp_indent_labels=one_less_than_current
csharp_indent_switch_labels=true
# Space preferences
csharp_space_after_cast=false
csharp_space_after_colon_in_inheritance_clause=true
csharp_space_after_comma=true
csharp_space_after_dot=false
csharp_space_after_keywords_in_control_flow_statements=true
csharp_space_after_semicolon_in_for_statement=true
csharp_space_around_binary_operators=before_and_after
csharp_space_around_declaration_statements=false
csharp_space_before_colon_in_inheritance_clause=true
csharp_space_before_comma=false
csharp_space_before_dot=false
csharp_space_before_open_square_brackets=false
csharp_space_before_semicolon_in_for_statement=false
csharp_space_between_empty_square_brackets=false
csharp_space_between_method_call_empty_parameter_list_parentheses=false
csharp_space_between_method_call_name_and_opening_parenthesis=false
csharp_space_between_method_call_parameter_list_parentheses=false
csharp_space_between_method_declaration_empty_parameter_list_parentheses=false
csharp_space_between_method_declaration_name_and_open_parenthesis=false
csharp_space_between_method_declaration_parameter_list_parentheses=false
csharp_space_between_parentheses=false
csharp_space_between_square_brackets=false
# Wrapping preferences
csharp_preserve_single_line_blocks=true
csharp_preserve_single_line_statements=true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity=suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols=interface
dotnet_naming_rule.interface_should_be_begins_with_i.style=begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity=suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols=types
dotnet_naming_rule.types_should_be_pascal_case.style=pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity=suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols=non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style=pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds=interface
dotnet_naming_symbols.interface.applicable_accessibilities=public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers=
dotnet_naming_symbols.types.applicable_kinds=class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities=public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers=
dotnet_naming_symbols.non_field_members.applicable_kinds=property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities=public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers=
# Naming styles
dotnet_naming_style.pascal_case.required_prefix=
dotnet_naming_style.pascal_case.required_suffix=
dotnet_naming_style.pascal_case.word_separator=
dotnet_naming_style.pascal_case.capitalization=pascal_case
dotnet_naming_style.begins_with_i.required_prefix=I
dotnet_naming_style.begins_with_i.required_suffix=
dotnet_naming_style.begins_with_i.word_separator=
dotnet_naming_style.begins_with_i.capitalization=pascal_case
# XML comment analysis is disabled due to project configuration
# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA0001.md
dotnet_diagnostic.SA0001.severity = silent
# A C# code file is missing a standard file header.
# https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1633.md
dotnet_diagnostic.SA1633.severity = silent
# Consider calling ConfigureAwait on the awaited Task
# https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2007?view=vs-2019
# https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1090.md
dotnet_diagnostic.CA2007.severity = silent
dotnet_diagnostic.RCS1090.severity = silent

350
.gitignore vendored
View File

@ -1,350 +0,0 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.idea
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/

View File

@ -1,72 +0,0 @@
# Changelog
## [2.2.0] - 2020-04-21
### Added
- Add `string.ChangeEncoding(Encoding, Encoding)`
- Converts this string from one encoding to another
- Add `string.IsLower`
- Determines if all alpha characters in this string are considered lowercase
- Add `string.IsUpper`
- Determines if all alpha characters in this string are considered uppercase
- Various extension methods with regards to reflection:
- `GetDefaultValue` and `GetDefaultValue<T>` - gets the value stored in the member's `DefaultValue` attribute
- `GetDescription`- gets the value stored in the member's `Description` attribute
- `SelectFromCustomAttribute<T1, T2>` - Internally calls `GetCustomAttribute<T1>` and passes it to a `Func<T1, T2>` so that specific members may be selected
### Changed
- n/a
### Removed
- n/a
## [2.1.0] - 2020-04-18
### Added
- `bool bool.And(bool)`
- Performs logical AND
- `bool bool.Or(bool)`
- Performs logical OR
- `bool bool.Not(bool)`
- Performs logical NOT
- `bool bool.XOr(bool)`
- Performs Logical XOR
- `bool bool.NAnd(bool)`
- Performs logical NAND
- `bool bool.NOr(bool)`
- Performs logical NOR
- `bool bool.XNOr(bool)`
- Performs logical XNOR
- `byte bool.ToByte()`
- 1 if `true`, 0 otherwise
- `short bool.ToInt16()`
- 1 if `true`, 0 otherwise
- `long bool.ToInt64()`
- 1 if `true`, 0 otherwise
### Changed
- n/a
### Removed
- n/a
## [2.0.0] - 2020-04-18
### Added
- Add `IEnumerable<T>.Split(int)`
- Performs the same operation as the previously defined `IEnumerable<byte>.Chunkify(int)`, except now accepts any type `T`
### Changed
- Fix `DateTime.Last(DayOfWeek)` implementation
- Now returns the correct date/time for a given day of the week
### Removed
- Remove `IEnumerable<byte>.Chunkify(int)`
- Replaced by a method of the same behaviour `IEnumerable<T>.Split(int)`
## Earlier versions
### ***Not documented***
[Unreleased]: https://github.com/oliverbooth/X10D/tree/HEAD
[2.2.0]: https://github.com/oliverbooth/X10D/releases/tag/2.2.0
[2.1.0]: https://github.com/oliverbooth/X10D/releases/tag/2.1.0
[2.0.0]: https://github.com/oliverbooth/X10D/releases/tag/2.0.0

View File

@ -1,29 +0,0 @@
## How you can contribute
Contributions to this project are always welcome. If you spot a bug, or want to request a new extension method, open a new issue or submit a pull request.
### Pull request guidelines
This project uses C# 8.0 language features, and adheres to the following analyzers:
- Rozlynator
- FxCop
- StyleCop
There is an `.editorconfig` and an analyzer `ruleset` file included in this repository. For quick and painless pull requests, ensure that these analyzers do not throw warnings.
### Code style
Below are a few pointers to which you may refer, but keep in mind this is not an exhaustive list:
- Use C# 8.0 features where possible
- Try to ensure code is CLS-compliant
- Follow all .NET guidelines for naming conventions
- Make full use of XMLDoc and be thorough - but concise - with all documentation.
- Ensure that no line exceeds 120 characters in length
- Do NOT include file headers in any form
- Declare `using` directives within namespace scope
- Try to avoid using exceptions for flow control
### Tests
When introducing a new extension method, you must ensure that you have also defined a unit test that asserts its correct behavior. The code style guidelines and code-analysis rules apply to the `X10D.Tests` equally as much as `X10D`, although documentation may be briefer. Refer to existing tests as a guideline.
### Disclaimer
In the event of a code style violation, a pull request may left open (or closed entirely) without merging. Keep in mind this does not mean the theory or implementation of the method is inherently bad or rejected entirely (although if this is the case, it will be outlined)

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2019 Oliver Booth
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

262
README.md
View File

@ -1,262 +0,0 @@
# X10D
## Extension methods on crack
[<img src="https://img.shields.io/github/workflow/status/oliverbooth/X10D/.NET%20Core">](https://github.com/oliverbooth/X10D/actions?query=workflow%3A%22.NET+Core%22)
[<img src="https://img.shields.io/github/issues/oliverbooth/X10D">](https://github.com/oliverbooth/X10D/issues)
[<img src="https://img.shields.io/nuget/v/X10D">](https://www.nuget.org/packages/X10D/)
[<img src="https://img.shields.io/github/license/oliverbooth/X10D">](https://github.com/oliverbooth/X10D/blob/master/LICENSE.md)
### About
X10D (pronounced *extend*), is a class library that provides extension methods for numerous .NET types. The purpose of this library is to simplify a codebase by reducing the need for repeated code when performing common operations. Simplify your codebase. Take advantage of .NET. Use extension methods.
*(I'm also [dogfooding](https://deviq.com/dogfooding/) this library, so there's that.)*
### Table of contents
- [Install](#install)
- [Features](#features)
- [Numeric](#numeric)
- [String](#string)
- [DateTime](#datetime)
- [Enumerable](#enumerable)
- [Enum](#enum)
- [Conversion](#conversion)
- [Random](#random)
- [Contributing](#contributing)
- [License](#license)
You can find the list of classes that have extension methods by viewing the `README.md` file in any of the respective library folders.
## Install
Install X10D with NuGet via the following command:
```ps
Install-Package X10D -Version 2.2.0
```
or by downloading the [latest release](https://github.com/oliverbooth/X10D/releases/latest) from this repository.
## Features
### Numeric extensions
> 👍 ProTip: *Most* of the extensions available for `int` will also exist for `short`, `long`, and their unsigned counterparts!
#### `bool` &lt;-&gt; `int`
Convert a `bool` to an `int` by using `ToInt32`. The value returned is 1 if the input is `true`, and 0 if it's `false`.
```cs
bool b = true;
int i = b.ToInt32(); // 1
```
The same also works in reverse. Using `ToBoolean` on an `int` will return `false` if the input is 0, and `true`if the input is anything else.
```cs
int zero = 0;
long nonZero = 1;
bool b1 = zero.ToBoolean(); // false
bool b2 = nonZero.ToBoolean(); // true
```
#### Between
Determine if a value is between other values using `Between` like so:
```cs
int i = 3;
if (i.Between(2, 4))
{
// i is between 2 and 4!
}
```
Since the signature of this method is defined with a generic constraint of `IComparable<T>`, this will also work for any object that is `IComparable<T>` - not just numeric types!
```cs
bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
```
#### IsEven (*and IsOdd*)
As the names suggest, this method determines if the input value is evenly divisible by 2.
```cs
int i = 5;
bool b = i.IsEven(); // false
```
There is also an `IsOdd` extension method, which will return the opposite of that returned by `IsEven`.
#### IsPrime
Determine if an integral is a prime number by using `IsPrime`.
```cs
bool b = 43.IsPrime(); // true
```
#### Clamp
Clamp a value between an upper and lower bound
```cs
int i = 5.Clamp(0, 3); // 3
```
#### Convert degrees &lt;-&gt; radians
Easily convert between radians and degrees
```cs
double rad = 2 * Math.PI;
double deg = rad.RadiansToDegrees(); // 360
rad = deg.DegreesToRadians(); // back to 2*pi
```
#### Round
Round a value to the nearest whole number:
```cs
var d = 2.75;
var rounded = d.Round(); // 3
```
Or specify a value to have it round to the nearest multiple of `x`:
```cs
double a = 8.0.Round(10); // 10
double b = 2.0.Round(10); // 0
```
### String
#### Repeat value
Repeat a string or a char a specific number of times using `Repeat`
```cs
var c = '-';
var str = "foo";
string repeatedC = c.Repeat(10); // ----------
string repeatedStr = str.Repeat(5); // foofoofoofoofoo
```
#### Base-64 encode/decode
```cs
var base64 = "Hello World".Base64Encode(); // SGVsbG8gV29ybGQ=
var str = "SGVsbG8gV29ybGQ=".Base64Decode(); // Hello World
```
### DateTime
#### Age
Get a rounded integer representing the number of years since a given date. i.e. easily calculate someone's age:
```cs
var dateOfBirth = new DateTime(1960, 7, 16);
int age = dateOfBirth.Age(); // the age as of today
```
You can also specify a date at which to stop counting the years, by passing an `asOf` date:
```cs
var dateOfBirth = new DateTime(1960, 7, 16);
int age = dateOfBirth.Age(new DateTime(1970, 7, 16)); // 10, the age as of 1970
```
#### To/From Unix Timestamp
Convert to/from a Unix timestamp represented in seconds using `FromUnixTimestamp` on a numeric type, and `ToUnixTimestamp` on a `DateTime`.
```cs
long sec = 1587223415;
DateTime time = sec.FromUnixTimestamp(); // 2020-04-18 15:23:35
long unix = time.ToUnixTimestamp();
```
or represent it with milliseconds by passing `true` for the `isMillis` argument:
```cs
long millis = 1587223415500;
DateTime time = millis.FromUnixTimestamp(true); // 2020-04-18 15:23:35.50
long unix = time.ToUnixTimestamp(true);
```
#### Get first/last day of month
Get the first or last day of the month by using `FirstDayOfMonth` and `LastDayOfMonth`
```cs
var dt = new DateTime(2016, 2, 4);
DateTime first = dt.FirstDayOfMonth(); // 2016-02-01
DateTime last = dt.LastDayOfMonth(); // 2016-02-29 (2016 is a leap year)
```
You can also use `First` or `Last` to get the first or final occurrence of a specific day of the week in a given month:
```cs
var dt = new DateTime(2019, 4, 14);
DateTime theLastFriday = dt.Last(DayOfWeek.Friday); // 2019-04-24
DateTime theLastThursday = dt.Last(DayOfWeek.Thursday); // 2019-04-40
```
### Enumerable
#### Split into chunks
Split an `IEnumerable<T>` into an `IEnumerable<IEnumerable<T>>`, essentially "chunking" the original IEnumerable into a specific size
```cs
var arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var chunks = arr.Split(2); // split into chunks of 2
foreach (var chunk in chunks)
{
Console.WriteLine(string.Join(", ", chunk));
}
// Output:
// 1, 2
// 3, 4
// 5, 6
// 7, 8
```
This also works for `string`:
```cs
var str = "Hello World";
var chunks = str.Split(2); // split string into chunks of 2
foreach (var chunk in chunks)
{
Console.WriteLine(string.Join(string.Empty, chunk));
}
// Output:
// He
// ll
// o <-- space is included
// Wo
// rl
// d <-- no space! end of string
```
### Enum
#### Parse string into enum
You can use the `EnumParse` method to convert a string into a value from an enum, while optionally ignoring case:
```cs
enum Number
{
Zero,
One,
Two,
Three,
}
Number num = "two".EnumParse<Number>(true); // num == Number.Two
```
#### `Next` / `Previous` enum cycling
Cycle through the values in an enum with `Next` and `Previous`:
```cs
Number two = Number.Two;
Number one = two.Previous();
Number three = two.Next();
```
### Conversion
Easily convert between types using `To`, `ToOrNull`, `ToOrDefault`, or `ToOrOther`, thereby shortening the call to `Convert.ChangeType` or `Convert.ToX`:
```CS
int i = "43".To<int>();
int j = "a".ToOrDefault<int>(); // 0
int k = "a".ToOrOther<int>(100); // 100
```
### Random
Do more with Random including flip a coin, randomly select an element in an array, or shuffle the array entirely.
```cs
var random = new Random();
// flip a coin
bool heads = random.CoinToss();
// randomly choose an item
var arr = new int[] { 1, 2, 3, 4 };
var item = random.OneOf(arr);
// shuffle an array or list
var shuffled = arr.Shuffle(random);
```
## Contributing
Contributions are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
## License
X10D is released under the MIT License. See [here](https://github.com/oliverbooth/X10D/blob/master/LICENSE.md) for more details.

View File

@ -1,35 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
<CodeAnalysisRuleSet>..\X10D.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
<PackageReference Include="Roslynator.Analyzers" Version="2.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.164">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Unity3D.SDK" Version="2019.4.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\X10D.Unity\X10D.Unity.csproj" />
<ProjectReference Include="..\X10D\X10D.csproj" />
</ItemGroup>
</Project>

View File

@ -1,3 +0,0 @@
using System;
[assembly: CLSCompliant(true)]

View File

@ -1,214 +0,0 @@
namespace X10D.Tests.Core
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="BooleanExtensions" />.
/// </summary>
[TestClass]
public class BooleanTests
{
/// <summary>
/// Tests for <see cref="BooleanExtensions.And" />.
/// </summary>
[TestMethod]
public void And()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsTrue(a.And(b));
Assert.IsFalse(b.And(c));
Assert.IsFalse(c.And(d));
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.NAnd" />.
/// </summary>
[TestMethod]
public void NAnd()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsFalse(a.NAnd(b));
Assert.IsTrue(b.NAnd(c));
Assert.IsTrue(c.NAnd(d));
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.NOr" />.
/// </summary>
[TestMethod]
public void NOr()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsFalse(a.NOr(b));
Assert.IsFalse(b.NOr(c));
Assert.IsTrue(c.NOr(d));
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.Not" />.
/// </summary>
[TestMethod]
public void Not()
{
const bool a = true;
const bool b = false;
Assert.IsTrue(a);
Assert.IsFalse(b);
Assert.IsFalse(a.Not());
Assert.IsTrue(b.Not());
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.Or" />.
/// </summary>
[TestMethod]
public void Or()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsTrue(a.Or(b));
Assert.IsTrue(b.Or(c));
Assert.IsFalse(c.Or(d));
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.ToByte" />.
/// </summary>
[TestMethod]
public void ToByte()
{
const bool a = true;
const bool b = false;
const byte c = 1;
const byte d = 0;
Assert.IsTrue(a);
Assert.IsFalse(b);
Assert.AreEqual(c, a.ToByte());
Assert.AreEqual(d, b.ToByte());
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.ToInt16" />.
/// </summary>
[TestMethod]
public void ToInt16()
{
const bool a = true;
const bool b = false;
Assert.IsTrue(a);
Assert.IsFalse(b);
Assert.AreEqual(1, a.ToInt16());
Assert.AreEqual(0, b.ToInt16());
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.ToInt32" />.
/// </summary>
[TestMethod]
public void ToInt32()
{
const bool a = true;
const bool b = false;
Assert.IsTrue(a);
Assert.IsFalse(b);
Assert.AreEqual(1, a.ToInt32());
Assert.AreEqual(0, b.ToInt32());
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.ToInt64" />.
/// </summary>
[TestMethod]
public void ToInt64()
{
const bool a = true;
const bool b = false;
Assert.IsTrue(a);
Assert.IsFalse(b);
Assert.AreEqual(1L, a.ToInt64());
Assert.AreEqual(0L, b.ToInt64());
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.XNOr" />.
/// </summary>
[TestMethod]
public void XNOr()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsTrue(a.XNOr(b));
Assert.IsFalse(b.XNOr(c));
Assert.IsTrue(c.XNOr(d));
}
/// <summary>
/// Tests for <see cref="BooleanExtensions.XOr" />.
/// </summary>
[TestMethod]
public void XOr()
{
const bool a = true;
const bool b = true;
const bool c = false;
const bool d = false;
Assert.IsTrue(a);
Assert.IsTrue(b);
Assert.IsFalse(c);
Assert.IsFalse(d);
Assert.IsFalse(a.XOr(b));
Assert.IsTrue(b.XOr(c));
Assert.IsFalse(c.XOr(d));
}
}
}

View File

@ -1,103 +0,0 @@
namespace X10D.Tests.Core
{
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="ByteExtensions" />.
/// </summary>
[TestClass]
public class ByteTests
{
/// <summary>
/// Tests for <see cref="ByteExtensions.AsString" />.
/// </summary>
[TestMethod]
public void AsString()
{
byte[] a = { 0x00, 0x73, 0xc6, 0xff };
Assert.AreEqual("00-73-C6-FF", a.AsString());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetInt16" />.
/// </summary>
[TestMethod]
public void GetInt16()
{
byte[] a = { 0xF3, 0x3F };
Assert.AreEqual(16371, a.GetInt16());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetInt32" />.
/// </summary>
[TestMethod]
public void GetInt32()
{
byte[] a = { 0xB0, 0x0B, 0x13, 0x5F };
Assert.AreEqual(1595083696, a.GetInt32());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetInt64" />.
/// </summary>
[TestMethod]
public void GetInt64()
{
byte[] a = { 0xB0, 0x0B, 0x13, 0x50, 0x05, 0x31, 0xB0, 0x0B };
Assert.AreEqual(842227029206305712L, a.GetInt64());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetString(IEnumerable{byte})" />.
/// </summary>
[TestMethod]
public void GetString()
{
byte[] a = { 0x48, 0xc3, 0xa9, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 };
Assert.AreEqual("H\u00e9llo World", a.GetString());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetString(IEnumerable{byte}, Encoding)" />.
/// </summary>
[TestMethod]
public void GetStringAscii()
{
byte[] a = { 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64 };
Assert.AreEqual("Hello World", a.GetString(Encoding.ASCII));
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetUInt16" />.
/// </summary>
[TestMethod]
public void GetUInt16()
{
byte[] a = { 0xF3, 0x3F };
Assert.AreEqual(16371, a.GetUInt16());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetUInt32" />.
/// </summary>
[TestMethod]
public void GetUInt32()
{
byte[] a = { 0xB0, 0x0B, 0x13, 0x5F };
Assert.AreEqual(1595083696U, a.GetUInt32());
}
/// <summary>
/// Tests for <see cref="ByteExtensions.GetUInt64" />.
/// </summary>
[TestMethod]
public void GetUInt64()
{
byte[] a = { 0xB0, 0x0B, 0x13, 0x50, 0x05, 0x31, 0xB0, 0x0B };
Assert.AreEqual(842227029206305712UL, a.GetUInt64());
}
}
}

View File

@ -1,35 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="CharExtensions" />.
/// </summary>
[TestClass]
public class CharTests
{
/// <summary>
/// Tests for <see cref="CharExtensions.Repeat" />.
/// </summary>
[TestMethod]
public void Random()
{
var set = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
var random = set.Random(20);
Assert.IsTrue(random.All(c => Array.IndexOf(set, c) >= 0));
Assert.IsFalse(random.Any(c => Array.IndexOf(set, c) < -1));
}
/// <summary>
/// Tests for <see cref="CharExtensions.Repeat" />.
/// </summary>
[TestMethod]
public void Repeat()
{
Assert.AreEqual("aaaaaaaaaa", 'a'.Repeat(10));
}
}
}

View File

@ -1,22 +0,0 @@
namespace X10D.Tests.Core
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="ComparableExtensions" />.
/// </summary>
[TestClass]
public class ComparableTests
{
/// <summary>
/// Tests for <see cref="ComparableExtensions.Between{T}" />.
/// </summary>
[TestMethod]
public void Between()
{
Assert.IsTrue(5.Between(2, 7));
Assert.IsTrue(10.Between(9, 11));
Assert.IsFalse(100.Between(80, 99));
}
}
}

View File

@ -1,58 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="ConvertibleExtensions" />.
/// </summary>
[TestClass]
public class ConvertibleTests
{
/// <summary>
/// Tests for <see cref="ConvertibleExtensions.To{T}" />.
/// </summary>
[TestMethod]
public void To()
{
Assert.AreEqual(2, "2".To<int>());
Assert.AreEqual("12.5", 12.50.To<string>());
Assert.IsTrue("True".To<bool>());
}
/// <summary>
/// Tests for <see cref="ConvertibleExtensions.ToOrDefault{T}(System.IConvertible, System.IFormatProvider)" />.
/// </summary>
[TestMethod]
public void ToOrDefault()
{
Assert.AreEqual(2, "2".ToOrDefault<int>());
Assert.AreEqual("12.5", 12.50.ToOrDefault<string>());
Assert.IsTrue("True".ToOrDefault<bool>());
Assert.ThrowsException<FormatException>(() => "Foo".ToOrDefault<double>());
Assert.IsTrue("1.5".ToOrDefault(out float f));
Assert.AreEqual(1.5f, f);
}
/// <summary>
/// Tests for <see cref="ConvertibleExtensions.ToOrNull{T}(System.IConvertible, System.IFormatProvider)" />.
/// </summary>
[TestMethod]
public void ToOrNull()
{
Assert.IsFalse("foo".ToOrNull(out ConvertibleTests t));
Assert.IsNull(t);
}
/// <summary>
/// Tests for <see cref="ConvertibleExtensions.ToOrOther{T}(System.IConvertible, T, System.IFormatProvider)" />.
/// </summary>
[TestMethod]
public void ToOrOther()
{
Assert.AreEqual(2.0, "Foo".ToOrOther(2.0));
Assert.IsFalse("Foo".ToOrOther(out var d, 2.0));
Assert.AreEqual(2.0, d);
}
}
}

View File

@ -1,107 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="DateTimeExtensions" />.
/// </summary>
[TestClass]
public class DateTimeTests
{
/// <summary>
/// Tests for <see cref="DateTimeExtensions.Age(DateTime)" />.
/// </summary>
[TestMethod]
public void Age()
{
// no choice but to create dynamic based on today's date.
// age varies with time
var now = DateTime.Now;
var dt = new DateTime(now.Year - 18, 1, 1);
Assert.AreEqual(18, dt.Age());
}
/// <summary>
/// Tests for <see cref="DateTimeExtensions.First" />.
/// </summary>
[TestMethod]
public void First()
{
var dt = new DateTime(2018, 6, 20);
Assert.AreEqual(4, dt.First(DayOfWeek.Monday).Day);
}
/// <summary>
/// Tests for <see cref="DateTimeExtensions.FirstDayOfMonth" />.
/// </summary>
[TestMethod]
public void FirstDayOfMonth()
{
var dt = new DateTime(2018, 6, 20);
var first = dt.FirstDayOfMonth();
Assert.AreEqual(dt.Year, first.Year);
Assert.AreEqual(dt.Month, first.Month);
Assert.AreEqual(1, first.Day);
}
/// <summary>
/// Tests for <see cref="DateTimeExtensions.Last" />.
/// </summary>
[TestMethod]
public void Last()
{
{
var dt = new DateTime(2019, 12, 1);
var last = dt.Last(DayOfWeek.Wednesday);
Assert.AreEqual(dt.Year, last.Year);
Assert.AreEqual(dt.Month, last.Month);
Assert.AreEqual(25, last.Day);
}
{
var dt = new DateTime(2020, 4, 14);
var last = dt.Last(DayOfWeek.Friday);
Assert.AreEqual(dt.Year, last.Year);
Assert.AreEqual(dt.Month, last.Month);
Assert.AreEqual(24, last.Day);
last = dt.Last(DayOfWeek.Thursday);
Assert.AreEqual(dt.Year, last.Year);
Assert.AreEqual(dt.Month, last.Month);
Assert.AreEqual(30, last.Day);
}
}
/// <summary>
/// Tests for <see cref="DateTimeExtensions.LastDayOfMonth" />.
/// </summary>
[TestMethod]
public void LastDayOfMonth()
{
var dt = new DateTime(2016, 2, 4);
var last = dt.LastDayOfMonth();
Assert.AreEqual(dt.Year, last.Year);
Assert.AreEqual(dt.Month, last.Month);
Assert.AreEqual(29, last.Day); // 2016 is a leap year
}
/// <summary>
/// Tests for <see cref="DateTimeExtensions.ToUnixTimeStamp" />.
/// </summary>
[TestMethod]
public void ToUnixTimestamp()
{
var dt = new DateTime(2015, 10, 21, 1, 0, 0, DateTimeKind.Utc);
var unix = dt.ToUnixTimeStamp();
Assert.AreEqual(1445389200L, unix);
}
}
}

View File

@ -1,42 +0,0 @@
namespace X10D.Tests.Core
{
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="DictionaryExtensions" />.
/// </summary>
[TestClass]
public class DictionaryTests
{
/// <summary>
/// Tests for <see cref="DictionaryExtensions.ToConnectionString{T1,T2}(IDictionary{T1,T2})" />.
/// </summary>
[TestMethod]
public void ToConnectionString()
{
var dictionary = new Dictionary<string, object>
{
{ "username", "Foo" }, { "password", "Foo Bar" }, { "port", 3306 },
};
var connectionString = dictionary.ToConnectionString();
Assert.AreEqual("username=Foo;password=\"Foo Bar\";port=3306", connectionString);
}
/// <summary>
/// Tests for <see cref="DictionaryExtensions.ToGetParameters{T1,T2}(IDictionary{T1,T2})" />.
/// </summary>
[TestMethod]
public void ToGetParameters()
{
var dictionary = new Dictionary<string, object>
{
{ "username", "Foo" }, { "password", "Foo Bar" }, { "port", 3306 },
};
var getParameterString = dictionary.ToGetParameters();
Assert.AreEqual("username=Foo&password=Foo+Bar&port=3306", getParameterString);
}
}
}

View File

@ -1,84 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="DoubleExtensions" />.
/// </summary>
[TestClass]
public class DoubleTests
{
/// <summary>
/// Tests for <see cref="DoubleExtensions.Clamp" />.
/// </summary>
[TestMethod]
public void Clamp()
{
Assert.AreEqual(2.0, 3.0.Clamp(1.0, 2.0));
Assert.AreEqual(1.0, (-3.0).Clamp(1.0, 2.0));
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.DegreesToRadians" />.
/// </summary>
[TestMethod]
public void DegreesToRadians()
{
Assert.AreEqual(Math.PI, 180.0.DegreesToRadians());
Assert.AreEqual(Math.PI * 1.5, 270.0.DegreesToRadians());
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.GetBytes" />.
/// </summary>
[TestMethod]
public void GetBytes()
{
CollectionAssert.AreEqual(
new byte[] { 0x18, 0x2D, 0x44, 0x54, 0xFB, 0x21, 0x09, 0x40 },
Math.PI.GetBytes());
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.IsEven" />.
/// </summary>
[TestMethod]
public void IsEven()
{
Assert.IsTrue(2.0.IsEven());
Assert.IsFalse(1.0.IsEven());
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.IsOdd" />.
/// </summary>
[TestMethod]
public void IsOdd()
{
Assert.IsFalse(2.0.IsOdd());
Assert.IsTrue(1.0.IsOdd());
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.RadiansToDegrees" />.
/// </summary>
[TestMethod]
public void RadiansToDegrees()
{
Assert.AreEqual(180.0, Math.PI.RadiansToDegrees());
Assert.AreEqual(360.0, (2.0 * Math.PI).RadiansToDegrees());
}
/// <summary>
/// Tests for <see cref="DoubleExtensions.Round" />.
/// </summary>
[TestMethod]
public void Round()
{
Assert.AreEqual(5.0, 3.5.Round(5));
Assert.AreEqual(5.0, 7.0.Round(5));
Assert.AreEqual(10.0, 7.5.Round(5));
}
}
}

View File

@ -1,55 +0,0 @@
namespace X10D.Tests.Core
{
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="EnumerableExtensions" />.
/// </summary>
[TestClass]
public class EnumerableTests
{
/// <summary>
/// Tests for <see cref="EnumerableExtensions.Split{T}" /> using an array of <see cref="byte" />.
/// </summary>
[TestMethod]
public void SplitByte()
{
byte[] foo = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
IEnumerable<IEnumerable<byte>> chunks = foo.Split(2).ToArray();
Assert.AreEqual(4, chunks.Count());
CollectionAssert.AreEqual(new byte[] { 0x01, 0x02 }, chunks.ElementAt(0).ToList());
CollectionAssert.AreEqual(new byte[] { 0x03, 0x04 }, chunks.ElementAt(1).ToList());
CollectionAssert.AreEqual(new byte[] { 0x05, 0x06 }, chunks.ElementAt(2).ToList());
CollectionAssert.AreEqual(new byte[] { 0x07, 0x08 }, chunks.ElementAt(3).ToList());
// test exceeding chunk size
chunks = foo.Split(foo.Length + 10).ToArray();
Assert.AreEqual(1, chunks.Count());
CollectionAssert.AreEqual(foo, chunks.SelectMany(c => c).ToList());
}
/// <summary>
/// Tests for <see cref="EnumerableExtensions.Split{T}" /> using an array of <see cref="int" />.
/// </summary>
[TestMethod]
public void SplitInt32()
{
int[] foo = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
IEnumerable<IEnumerable<int>> chunks = foo.Split(2).ToArray();
Assert.AreEqual(4, chunks.Count());
CollectionAssert.AreEqual(new[] { 0x01, 0x02 }, chunks.ElementAt(0).ToList());
CollectionAssert.AreEqual(new[] { 0x03, 0x04 }, chunks.ElementAt(1).ToList());
CollectionAssert.AreEqual(new[] { 0x05, 0x06 }, chunks.ElementAt(2).ToList());
CollectionAssert.AreEqual(new[] { 0x07, 0x08 }, chunks.ElementAt(3).ToList());
// test exceeding chunk size
chunks = foo.Split(foo.Length + 10).ToArray();
Assert.AreEqual(1, chunks.Count());
CollectionAssert.AreEqual(foo, chunks.SelectMany(c => c).ToList());
}
}
}

View File

@ -1,70 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="ReflectionExtensions" />.
/// </summary>
[TestClass]
public class ReflectionTests
{
/// <summary>
/// Test for <see cref="ReflectionExtensions.GetDefaultValue{T}(System.Reflection.MemberInfo)" />.
/// </summary>
[TestMethod]
public void GetDefaultValue()
{
var klass = new TestClass();
foreach (var property in klass.GetType().GetProperties())
{
Assert.AreEqual("Foo", property.GetDefaultValue<string>());
}
}
/// <summary>
/// Test for <see cref="ReflectionExtensions.GetDescription(System.Reflection.MemberInfo)" />.
/// </summary>
[TestMethod]
public void GetDescription()
{
var klass = new TestClass();
foreach (var property in klass.GetType().GetProperties())
{
Assert.AreEqual("Test description", property.GetDescription());
}
}
/// <summary>
/// Test for <see cref="ReflectionExtensions.GetDescription(System.Reflection.MemberInfo)" />.
/// </summary>
[TestMethod]
public void SelectFromCustomAttribute()
{
var klass = new TestClass();
foreach (var property in klass.GetType().GetProperties())
{
var value = property.SelectFromCustomAttribute<TestAttribute, string>(a => a.TestValue);
Assert.AreEqual("Bar", value);
}
}
[AttributeUsage(AttributeTargets.Property)]
private sealed class TestAttribute : Attribute
{
public string TestValue { get; set; }
}
private sealed class TestClass
{
[System.ComponentModel.Description("Test description")]
[DefaultValue("Foo")]
[Test(TestValue = "Bar")]
public string TestProperty { get; set; }
}
}
}

View File

@ -1,34 +0,0 @@
namespace X10D.Tests.Core
{
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="StringExtensions" />.
/// </summary>
[TestClass]
public class StringTests
{
/// <summary>
/// Tests for <see cref="StringExtensions.Repeat" />.
/// </summary>
[TestMethod]
public void Repeat()
{
Assert.AreEqual("foofoofoofoofoo", "foo".Repeat(5));
}
/// <summary>
/// Tests for <see cref="StringExtensions.Split" />.
/// </summary>
[TestMethod]
public void Split()
{
const string str = "Hello World";
// ReSharper disable once SuggestVarOrType_Elsewhere
var arr = str.Split(2).ToArray();
CollectionAssert.AreEqual(new[] { "He", "ll", "o ", "Wo", "rl", "d" }, arr);
}
}
}

View File

@ -1,26 +0,0 @@
namespace X10D.Tests.Core
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Tests for <see cref="TimeSpanParser" />.
/// </summary>
[TestClass]
public class TimeSpanParserTests
{
/// <summary>
/// Tests for <see cref="TimeSpanParser.Parse" />.
/// </summary>
[TestMethod]
public void TestParser()
{
Assert.AreEqual(TimeSpan.FromHours(3), "3h".ToTimeSpan());
Assert.AreEqual(TimeSpan.FromMinutes(2.5), "2.5m".ToTimeSpan());
Assert.AreEqual(TimeSpan.FromHours(1), "60m".ToTimeSpan());
Assert.AreEqual(TimeSpan.FromDays(1), "1d".ToTimeSpan());
Assert.AreEqual(TimeSpan.FromDays(8), "1w 1d".ToTimeSpan());
Assert.AreEqual(TimeSpan.FromDays(8), "1w1d".ToTimeSpan());
}
}
}

View File

@ -1,93 +0,0 @@
namespace X10D.Tests.Unity
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UnityEngine;
using X10D.Unity;
/// <summary>
/// Tests for <see cref="Vector3Extensions" />.
/// </summary>
[TestClass]
public class Vector3Tests
{
/// <summary>
/// Tests for <see cref="Vector3Extensions.Round" /> by rounding to the nearest 0.5.
/// </summary>
[TestMethod]
public void TestRoundHalf()
{
var vector = new Vector3(1.8f, 2.1f, 3.37f);
Assert.AreEqual(new Vector3(2, 2, 3.5f), vector.Round(0.5f));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.Round" /> by rounding to the nearest integer.
/// </summary>
[TestMethod]
public void TestRoundInteger()
{
var vector = new Vector3(1.8f, 2.1f, 3.37f);
Assert.AreEqual(new Vector3(2, 2, 3), vector.Round());
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithX" />.
/// </summary>
[TestMethod]
public void TestWithX()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(4, 2, 3), vector.WithX(4));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithXY" />.
/// </summary>
[TestMethod]
public void TestWithXY()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(8, 10, 3), vector.WithXY(8, 10));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithXZ" />.
/// </summary>
[TestMethod]
public void TestWithXZ()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(8, 2, 10), vector.WithXZ(8, 10));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithY" />.
/// </summary>
[TestMethod]
public void TestWithY()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(1, 4, 3), vector.WithY(4));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithYZ" />.
/// </summary>
[TestMethod]
public void TestWithYZ()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(1, 8, 10), vector.WithYZ(8, 10));
}
/// <summary>
/// Tests for <see cref="Vector3Extensions.WithZ" />.
/// </summary>
[TestMethod]
public void TestWithZ()
{
var vector = new Vector3(1, 2, 3);
Assert.AreEqual(new Vector3(1, 2, 4), vector.WithZ(4));
}
}
}

BIN
X10D.Unity.dll Normal file

Binary file not shown.

View File

@ -1,72 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Authors>Oliver Booth</Authors>
<NeutralLanguage>en</NeutralLanguage>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<RepositoryUrl>https://github.com/oliverbooth/X10D</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Description>Extension methods on crack.</Description>
<PackageLicenseFile>LICENSE.md</PackageLicenseFile>
<PackageIcon>icon.png</PackageIcon>
<PackageIconUrl />
<PackageTags>dotnet extension-methods unity</PackageTags>
<Version>2.2.0</Version>
<CodeAnalysisRuleSet>..\X10D.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<PackageVersion>2.5.0</PackageVersion>
<AssemblyVersion>2.5.0</AssemblyVersion>
<FileVersion>2.5.0</FileVersion>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<None Include="..\LICENSE.md">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="2.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.164">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Unity3D.SDK" Version="2019.4.3.1">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\X10D\X10D.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Update="Resource.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resource.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resource.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,107 +0,0 @@
namespace X10D.Unity
{
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using UnityEngine;
/// <summary>
/// Represents a class which inherits <see cref="MonoBehaviour" /> to offer wider functionality.
/// </summary>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global", Justification = "Unity property")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global", Justification = "Unity property")]
[SuppressMessage("ReSharper", "SA1300", Justification = "Unity API-compliant property")]
[SuppressMessage("ReSharper", "CA2007", Justification = "Unnecessary")]
[SuppressMessage("ReSharper", "RCS1090", Justification = "Unnecessary")]
[SuppressMessage("ReSharper", "RCS1213", Justification = "Unity method")]
[SuppressMessage("ReSharper", "UnusedParameter.Global", Justification = "Override method")]
public abstract class BetterBehavior : MonoBehaviour
{
/// <summary>
/// Gets the <see cref="Transform" /> component attached to this object.
/// </summary>
public new Transform transform { get; private set; }
/// <summary>
/// Awake is called when the script instance is being loaded.
/// </summary>
protected virtual void Awake()
{
this.transform = this.GetComponent<Transform>();
}
/// <summary>
/// Frame-rate independent messaging for physics calculations.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
protected virtual void OnFixedUpdate(in GameTime gameTime)
{
}
/// <summary>
/// Frame-rate independent messaging for physics calculations.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
/// <returns>Returns a task representing the result of the operation.</returns>
protected virtual Task OnFixedUpdateAsync(GameTime gameTime)
{
return Task.CompletedTask;
}
/// <summary>
/// Called once per frame, after all <c>Update</c> calls.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
protected virtual void OnLateUpdate(in GameTime gameTime)
{
}
/// <summary>
/// Called once per frame, after all <c>Update</c> calls.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
/// <returns>Returns a task representing the result of the operation.</returns>
protected virtual Task OnLateUpdateAsync(GameTime gameTime)
{
return Task.CompletedTask;
}
/// <summary>
/// Called once per frame.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
protected virtual void OnUpdate(in GameTime gameTime)
{
}
/// <summary>
/// Called once per frame.
/// </summary>
/// <param name="gameTime">A snapshot of timing values.</param>
/// <returns>Returns a task representing the result of the operation.</returns>
protected virtual Task OnUpdateAsync(GameTime gameTime)
{
return Task.CompletedTask;
}
private async void FixedUpdate()
{
var time = GameTime.CreateFromCurrentTimes();
this.OnFixedUpdate(time);
await this.OnFixedUpdateAsync(time);
}
private async void LateUpdate()
{
var time = GameTime.CreateFromCurrentTimes();
this.OnLateUpdate(time);
await this.OnLateUpdateAsync(time);
}
private async void Update()
{
var time = GameTime.CreateFromCurrentTimes();
this.OnUpdate(time);
await this.OnUpdateAsync(time);
}
}
}

View File

@ -1,64 +0,0 @@
namespace X10D.Unity
{
using System;
using JetBrains.Annotations;
using UnityEngine;
/// <summary>
/// Extension methods for <see cref="GameObject" />.
/// </summary>
public static class GameObjectExtensions
{
/// <summary>
/// Rotates the <see cref="Transform" /> component on the current <see cref="GameObject" /> such that is is facing another
/// <see cref="GameObject" />.
/// </summary>
/// <param name="gameObject">The current game object.</param>
/// <param name="other">The target.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="gameObject" /> is null
/// - or -
/// <paramref name="other" /> is null.
/// </exception>
public static void LookAt([NotNull] this GameObject gameObject, [NotNull] GameObject other)
{
if (gameObject is null)
{
throw new ArgumentNullException(nameof(gameObject));
}
if (other is null)
{
throw new ArgumentNullException(nameof(other));
}
gameObject.LookAt(other.transform);
}
/// <summary>
/// Rotates the <see cref="Transform" /> component on the current <see cref="GameObject" /> such that is is facing another
/// <see cref="Transform" />.
/// </summary>
/// <param name="gameObject">The current game object.</param>
/// <param name="other">The target.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="gameObject" /> is null
/// - or -
/// <paramref name="other" /> is null.
/// </exception>
public static void LookAt([NotNull] this GameObject gameObject, [NotNull] Transform other)
{
if (gameObject is null)
{
throw new ArgumentNullException(nameof(gameObject));
}
if (other is null)
{
throw new ArgumentNullException(nameof(other));
}
gameObject.transform.LookAt(other);
}
}
}

View File

@ -1,54 +0,0 @@
namespace X10D.Unity
{
using System;
using UnityEngine;
/// <summary>
/// Represents a struct which contains game timing information.
/// </summary>
public readonly struct GameTime
{
private GameTime(float totalTime, float deltaTime, float fixedDeltaTime, int frameCount, float timeScale)
{
this.TotalTime = TimeSpan.FromSeconds(totalTime);
this.DeltaTime = TimeSpan.FromSeconds(deltaTime);
this.FixedDeltaTime = TimeSpan.FromSeconds(fixedDeltaTime);
this.FrameCount = frameCount;
this.TimeScale = timeScale;
}
/// <summary>
/// Gets the time since the last frame was rendered.
/// </summary>
public TimeSpan DeltaTime { get; }
/// <summary>
/// Gets the time since the last physics time step.
/// </summary>
public TimeSpan FixedDeltaTime { get; }
/// <summary>
/// Gets the total number of frames which have been rendered.
/// </summary>
public int FrameCount { get; }
/// <summary>
/// Gets the total time for which the game has been running.
/// </summary>
public TimeSpan TotalTime { get; }
/// <summary>
/// Gets the time scale.
/// </summary>
public float TimeScale { get; }
/// <summary>
/// Creates a new instance of the <see cref="GameTime" /> struct by creating a snapshot of values offered by <see cref="Time" />.
/// </summary>
/// <returns>An instance of <see cref="GameTime" />.</returns>
public static GameTime CreateFromCurrentTimes()
{
return new GameTime(Time.time, Time.deltaTime, Time.fixedDeltaTime, Time.frameCount, Time.timeScale);
}
}
}

View File

@ -1,37 +0,0 @@
namespace X10D.Unity
{
using System;
using JetBrains.Annotations;
using UnityEngine;
/// <summary>
/// Extension methods for <see cref="Transform" />.
/// </summary>
public static class TransformExtensions
{
/// <summary>
/// Rotates the current <see cref="Transform" /> such that is is facing another <see cref="GameObject" />.
/// </summary>
/// <param name="transform">The current transform.</param>
/// <param name="other">The target.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="transform" /> is null
/// - or -
/// <paramref name="other" /> is null.
/// </exception>
public static void LookAt([NotNull] this Transform transform, [NotNull] GameObject other)
{
if (transform is null)
{
throw new ArgumentNullException(nameof(transform));
}
if (other is null)
{
throw new ArgumentNullException(nameof(other));
}
transform.LookAt(other.transform);
}
}
}

View File

@ -1,111 +0,0 @@
namespace X10D.Unity
{
using UnityEngine;
/// <summary>
/// Extension methods for <see cref="Vector3" />.
/// </summary>
public static class Vector3Extensions
{
/// <summary>
/// Rounds a <see cref="Vector3" /> by calling <see cref="SingleExtensions.Round" /> on each of the components.
/// </summary>
/// <param name="vector">The vector to round.</param>
/// <param name="nearest">The nearest value.</param>
/// <returns><paramref name="vector" /> rounded to the nearest <paramref name="nearest" />.</returns>
public static Vector3 Round(this Vector3 vector, float nearest = 1)
{
return new Vector3(vector.x.Round(nearest), vector.y.Round(nearest), vector.z.Round(nearest));
}
/// <summary>
/// Returns a vector whose Y and Z components match that of a provided vector, and sets the X component to a provided value.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="x">The new X value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose Y and Z components match that of <paramref name="vector" />,
/// but with the <see cref="Vector3.x" /> component set to <paramref name="x" />.
/// </returns>
public static Vector3 WithX(this Vector3 vector, float x)
{
return new Vector3(x, vector.y, vector.z);
}
/// <summary>
/// Returns a vector whose Z component matches that of a provided vector, and sets the X and Y components to provided values.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="x">The new X value.</param>
/// <param name="y">The new Y value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose Z component matches that of <paramref name="vector" />,
/// but with the <see cref="Vector3.x" /> and <see cref="Vector3.y" /> components set to <paramref name="x" /> and
/// <paramref name="y" /> respectively.
/// </returns>
public static Vector3 WithXY(this Vector3 vector, float x, float y)
{
return new Vector3(x, y, vector.z);
}
/// <summary>
/// Returns a vector whose Y component matches that of a provided vector, and sets the X and Z components to provided values.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="x">The new X value.</param>
/// <param name="z">The new Z value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose Y component matches that of <paramref name="vector" />,
/// but with the <see cref="Vector3.x" /> and <see cref="Vector3.z" /> components set to <paramref name="x" /> and
/// <paramref name="z" /> respectively.
/// </returns>
public static Vector3 WithXZ(this Vector3 vector, float x, float z)
{
return new Vector3(x, vector.y, z);
}
/// <summary>
/// Returns a vector whose X and Z components match that of a provided vector, and sets the Y component to a provided value.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="y">The new Y value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose X and Z components match that of <paramref name="vector" />,
/// but with the <see cref="Vector3.y" /> component set to <paramref name="y" />.
/// </returns>
public static Vector3 WithY(this Vector3 vector, float y)
{
return new Vector3(vector.x, y, vector.z);
}
/// <summary>
/// Returns a vector whose X component matches that of a provided vector, and sets the Y and Z components to provided values.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="y">The new Y value.</param>
/// <param name="z">The new Z value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose X component matches that of <paramref name="vector" />,
/// but with the <see cref="Vector3.y" /> and <see cref="Vector3.z" /> components set to <paramref name="y" /> and
/// <paramref name="z" /> respectively.
/// </returns>
public static Vector3 WithYZ(this Vector3 vector, float y, float z)
{
return new Vector3(vector.x, y, z);
}
/// <summary>
/// Returns a vector whose X and Y components match that of a provided vector, and sets the Z component to a provided value.
/// </summary>
/// <param name="vector">The input vector.</param>
/// <param name="z">The new Z value.</param>
/// <returns>
/// Returns a <see cref="Vector3" /> whose X and Y components match that of <paramref name="vector" />,
/// but with the <see cref="Vector3.z" /> component set to <paramref name="z" />.
/// </returns>
public static Vector3 WithZ(this Vector3 vector, float z)
{
return new Vector3(vector.x, vector.y, z);
}
}
}

BIN
X10D.dll Normal file

Binary file not shown.

View File

@ -1,42 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28902.138
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "X10D", "X10D\X10D.csproj", "{4A8CC062-8B82-4625-B3CC-7DBEAB2AF149}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "X10D.Tests", "X10D.Tests\X10D.Tests.csproj", "{DF228EA2-D8EC-4A40-8917-E1E62E3B7D8E}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{FF6E59AB-1A23-4981-834C-47BEB5A46DC1}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Unity", "X10D.Unity\X10D.Unity.csproj", "{C21ABC58-68D6-4CA0-9CE6-A2E96C5E89AE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4A8CC062-8B82-4625-B3CC-7DBEAB2AF149}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A8CC062-8B82-4625-B3CC-7DBEAB2AF149}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A8CC062-8B82-4625-B3CC-7DBEAB2AF149}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A8CC062-8B82-4625-B3CC-7DBEAB2AF149}.Release|Any CPU.Build.0 = Release|Any CPU
{DF228EA2-D8EC-4A40-8917-E1E62E3B7D8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DF228EA2-D8EC-4A40-8917-E1E62E3B7D8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DF228EA2-D8EC-4A40-8917-E1E62E3B7D8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DF228EA2-D8EC-4A40-8917-E1E62E3B7D8E}.Release|Any CPU.Build.0 = Release|Any CPU
{C21ABC58-68D6-4CA0-9CE6-A2E96C5E89AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C21ABC58-68D6-4CA0-9CE6-A2E96C5E89AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C21ABC58-68D6-4CA0-9CE6-A2E96C5E89AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C21ABC58-68D6-4CA0-9CE6-A2E96C5E89AE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6F733785-8837-410C-BD91-C4AD1F0A6914}
EndGlobalSection
EndGlobal

View File

@ -1,27 +0,0 @@
# X10D
## About
The X10D library contains extension methods for standard .NET library types.
## Extended Classes
Below is a list of the number of extension methods written for a given type. Overloaded methods are not counted.
| Type | Library | Method count |
| :--- | :--- | :--- |
| `bool` | `X10D` | 1 |
| `byte` / `byte[]` | `X10D` | 8 |
| `char` | `X10D` | 1 |
| `IComparable` | `X10D` | 1 |
| `IConvertible` | `X10D` | 4 |
| `DateTime` | `X10D` | 11 |
| `EndPoint` | `X10D` | 2 |
| `double` | `X10D` | 7 |
| `enum` | `X10D` | 2 |
| `float` | `X10D` | 7 |
| `short` / `ushort` | `X10D` | 11 |
| `int` / `uint` | `X10D` | 25 |
| `long` / `ulong` | `X10D` | 13 |
| `IList<T>` | `X10D` | 2 |
| `Random` | `X10D` | 2 |
| `string` / `SecureString` | `X10D` | 8 |
| `Dictionary<T1, T2>` | `X10D` | 2 |

View File

@ -1,81 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace X10D {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resource() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("X10D.Resource", typeof(Resource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Must specify valid information for parsing in the string..
/// </summary>
internal static string EnumParseEmptyStringException {
get {
return ResourceManager.GetString("EnumParseEmptyStringException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Type provided must be an Enum..
/// </summary>
internal static string EnumParseNotEnumException {
get {
return ResourceManager.GetString("EnumParseNotEnumException", resourceCulture);
}
}
}
}

View File

@ -1,126 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="EnumParseEmptyStringException" xml:space="preserve">
<value>Must specify valid information for parsing in the string.</value>
</data>
<data name="EnumParseNotEnumException" xml:space="preserve">
<value>Type provided must be an Enum.</value>
</data>
</root>

View File

@ -1,65 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Authors>Oliver Booth</Authors>
<NeutralLanguage>en</NeutralLanguage>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<RepositoryUrl>https://github.com/oliverbooth/X10D</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<Description>Extension methods on crack.</Description>
<PackageLicenseFile>LICENSE.md</PackageLicenseFile>
<PackageIcon>icon.png</PackageIcon>
<PackageIconUrl />
<PackageTags>dotnet extension-methods</PackageTags>
<Version>2.2.0</Version>
<CodeAnalysisRuleSet>..\X10D.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<AssemblyVersion>2.5.0</AssemblyVersion>
<FileVersion>2.5.0</FileVersion>
<PackageVersion>2.5.0</PackageVersion>
</PropertyGroup>
<ItemGroup>
<None Include="..\icon.png">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<None Include="..\LICENSE.md">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="2.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.164">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<Compile Update="Resource.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resource.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Resource.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project>

View File

@ -1,3 +0,0 @@
using System;
[assembly: CLSCompliant(true)]

View File

@ -1,145 +0,0 @@
namespace X10D
{
/// <summary>
/// Extension methods for <see cref="bool" />.
/// </summary>
public static class BooleanExtensions
{
/// <summary>
/// Performs logical AND on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> AND <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool And(this bool value, bool comparison)
{
return value && comparison;
}
/// <summary>
/// Performs logical NAND on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> NAND <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool NAnd(this bool value, bool comparison)
{
return !(value && comparison);
}
/// <summary>
/// Performs logical NOR on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> NOR <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool NOr(this bool value, bool comparison)
{
return !(value || comparison);
}
/// <summary>
/// Performs logical NOT on this <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> is <see langword="false" />,
/// or <see langword="false" /> otherwise.
/// </returns>
public static bool Not(this bool value)
{
return !value;
}
/// <summary>
/// Performs logical OR on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> OR <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool Or(this bool value, bool comparison)
{
return value || comparison;
}
/// <summary>
/// Gets the value of this boolean as represented by <see cref="byte" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <returns>Returns 1 if <paramref name="value" /> is <see langword="true" />, or 0 otherwise.</returns>
public static byte ToByte(this bool value)
{
return (byte)value.ToInt32();
}
/// <summary>
/// Gets the value of this boolean as represented by <see cref="short" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <returns>Returns 1 if <paramref name="value" /> is <see langword="true" />, or 0 otherwise.</returns>
public static short ToInt16(this bool value)
{
return (short)value.ToInt32();
}
/// <summary>
/// Gets the value of this boolean as represented by <see cref="int" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <returns>Returns 1 if <paramref name="value" /> is <see langword="true" />, or 0 otherwise.</returns>
public static int ToInt32(this bool value)
{
return value ? 1 : 0;
}
/// <summary>
/// Gets the value of this boolean as represented by <see cref="long" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <returns>Returns 1 if <paramref name="value" /> is <see langword="true" />, 0 otherwise.</returns>
public static long ToInt64(this bool value)
{
return value.ToInt32();
}
/// <summary>
/// Performs logical XNOR on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> XNOR <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool XNOr(this bool value, bool comparison)
{
return !(value ^ comparison);
}
/// <summary>
/// Performs logical XOR on this <see cref="bool" /> and another <see cref="bool" />.
/// </summary>
/// <param name="value">The boolean.</param>
/// <param name="comparison">The boolean comparator.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="value" /> XOR <paramref name="comparison" />
/// evaluate to <see langword="true" />, or <see langword="false" /> otherwise.
/// </returns>
public static bool XOr(this bool value, bool comparison)
{
return value ^ comparison;
}
}
}

View File

@ -1,116 +0,0 @@
namespace X10D
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Extension methods for <see cref="byte" />.
/// </summary>
public static class ByteExtensions
{
/// <summary>
/// Gets a <see cref="string" /> literally representing the raw values in the <see cref="byte" />[].
/// </summary>
/// <param name="bytes">The bytes to get.</param>
/// <returns>Returns a <see cref="string" />.</returns>
public static string AsString(this IEnumerable<byte> bytes)
{
return BitConverter.ToString(bytes.ToArray());
}
/// <summary>
/// Converts the <see cref="byte" />[] to an <see cref="short" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="short" />.</returns>
public static short GetInt16(this IEnumerable<byte> bytes)
{
return BitConverter.ToInt16(bytes.ToArray(), 0);
}
/// <summary>
/// Converts the <see cref="byte" />[] to an <see cref="int" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="int" />.</returns>
public static int GetInt32(this IEnumerable<byte> bytes)
{
return BitConverter.ToInt32(bytes.ToArray(), 0);
}
/// <summary>
/// Converts the <see cref="byte" />[] to an <see cref="long" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="long" />.</returns>
public static long GetInt64(this IEnumerable<byte> bytes)
{
return BitConverter.ToInt64(bytes.ToArray(), 0);
}
/// <summary>
/// Gets a <see cref="string" /> representing the value the <see cref="byte" />[] with
/// <see cref="Encoding.UTF8" /> encoding.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns a <see cref="string" />.</returns>
public static string GetString(this IEnumerable<byte> bytes)
{
return bytes.GetString(Encoding.UTF8);
}
/// <summary>
/// Gets a <see cref="string" /> representing the value the <see cref="byte" />[] with the provided encoding.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <param name="encoding">The encoding to use.</param>
/// <returns>Returns a <see cref="string" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="encoding" /> is <see langword="null" />.</exception>
public static string GetString(this IEnumerable<byte> bytes, Encoding encoding)
{
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
// ReSharper disable once SuggestVarOrType_Elsewhere
var array = bytes.ToArray();
return encoding.GetString(array, 0, array.Length);
}
/// <summary>
/// Converts the <see cref="byte" />[] to a <see cref="ushort" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="ushort" />.</returns>
[CLSCompliant(false)]
public static ushort GetUInt16(this IEnumerable<byte> bytes)
{
return BitConverter.ToUInt16(bytes.ToArray(), 0);
}
/// <summary>
/// Converts the <see cref="byte" />[] to an <see cref="uint" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="uint" />.</returns>
[CLSCompliant(false)]
public static uint GetUInt32(this IEnumerable<byte> bytes)
{
return BitConverter.ToUInt32(bytes.ToArray(), 0);
}
/// <summary>
/// Converts the <see cref="byte" />[] to an <see cref="ulong" />.
/// </summary>
/// <param name="bytes">The bytes to convert.</param>
/// <returns>Returns an <see cref="ulong" />.</returns>
[CLSCompliant(false)]
public static ulong GetUInt64(this IEnumerable<byte> bytes)
{
return BitConverter.ToUInt64(bytes.ToArray(), 0);
}
}
}

View File

@ -1,90 +0,0 @@
namespace X10D
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/// <summary>
/// Extension methods for <see cref="char" />.
/// </summary>
public static class CharExtensions
{
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="chars" />.
/// </summary>
/// <param name="chars">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
public static string Random(this char[] chars, int length)
{
return chars.Random(length, RandomExtensions.Random);
}
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="chars" />.
/// </summary>
/// <param name="chars">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
/// <exception cref="ArgumentNullException"><paramref name="random" /> is <see langword="null" />.</exception>
public static string Random(this char[] chars, int length, Random random)
{
if (chars is null)
{
throw new ArgumentNullException(nameof(chars));
}
if (random is null)
{
throw new ArgumentNullException(nameof(random));
}
var builder = new StringBuilder(length);
for (var i = 0; i < length; i++)
{
builder.Append(chars[random.Next(0, chars.Length)]);
}
return builder.ToString();
}
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="chars" />.
/// </summary>
/// <param name="chars">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
public static string Random(this IEnumerable<char> chars, int length)
{
return chars.Random(length, RandomExtensions.Random);
}
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="chars" />.
/// </summary>
/// <param name="chars">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
public static string Random(this IEnumerable<char> chars, int length, Random random)
{
return chars.ToArray().Random(length, random);
}
/// <summary>
/// Repeats a character a specified number of times.
/// </summary>
/// <param name="c">The character to repeat.</param>
/// <param name="count">The repeat count.</param>
/// <returns>
/// Returns a <see cref="string" /> whose value is <paramref name="c" /> repeated
/// <paramref name="count" /> times.
/// </returns>
public static string Repeat(this char c, int count)
{
return new string(c, count);
}
}
}

View File

@ -1,27 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="IComparable" />.
/// </summary>
public static class ComparableExtensions
{
/// <summary>
/// Determines if <paramref name="actual" /> is between <paramref name="lower" /> and <paramref name="upper" />.
/// </summary>
/// <typeparam name="T">The comparable type.</typeparam>
/// <param name="actual">The value to compare.</param>
/// <param name="lower">The exclusive lower bound.</param>
/// <param name="upper">The exclusive upper bound.</param>
/// <returns>
/// Returns <see langword="true" /> if the value is between the bounds, <see langword="false" />
/// otherwise.
/// </returns>
public static bool Between<T>(this T actual, T lower, T upper)
where T : IComparable<T>
{
return actual.CompareTo(lower) > 0 && actual.CompareTo(upper) < 0;
}
}
}

View File

@ -1,161 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="IConvertible" />.
/// </summary>
public static class ConvertibleExtensions
{
/// <summary>
/// Converts the object to another type.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns the value converted to <see cref="T" />.</returns>
/// <exception cref="InvalidCastException">
/// This conversion is not supported.
/// -or-
/// <paramref name="value" /> is <see langword="null" /> and <typeparamref name="T" /> is a value type.
/// </exception>
[CLSCompliant(false)]
public static T To<T>(this IConvertible value, IFormatProvider provider = null)
{
if (value is null)
{
return default;
}
return (T)Convert.ChangeType(value, typeof(T), provider);
}
/// <summary>
/// Converts the object to another type, returning the default value on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="provider">The format provider.</param>
/// <returns>Returns the value converted to <see cref="T" />.</returns>
/// <exception cref="InvalidCastException">This conversion is not supported.</exception>
[CLSCompliant(false)]
public static T ToOrDefault<T>(this IConvertible value, IFormatProvider provider = null)
{
return value is null ? default : To<T>(value, provider);
}
/// <summary>
/// Converts the object to another type, returning the default value on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="newObj">The parameter where the result should be sent.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns <see langword="true" /> on success, <see langword="true" /> on failure.</returns>
[CLSCompliant(false)]
public static bool ToOrDefault<T>(this IConvertible value, out T newObj, IFormatProvider provider = null)
{
if (value is null)
{
newObj = default;
return false;
}
try
{
newObj = To<T>(value, provider);
return true;
}
catch (InvalidCastException)
{
newObj = default;
return false;
}
}
/// <summary>
/// Converts the object to another type, returning <see langword="null" /> on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns a <see cref="T" /> or <see langword="null" />.</returns>
[CLSCompliant(false)]
public static T ToOrNull<T>(this IConvertible value, IFormatProvider provider = null)
where T : class
{
return value.ToOrNull(out T v, provider) ? v : null;
}
/// <summary>
/// Converts the object to another type, returning <see langword="null" /> on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="newObj">The parameter where the result should be sent.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns a <see cref="T" /> or <see langword="null" />.</returns>
[CLSCompliant(false)]
public static bool ToOrNull<T>(this IConvertible value, out T newObj, IFormatProvider provider = null)
where T : class
{
return ToOrOther(value, out newObj, null, provider);
}
/// <summary>
/// Converts the object to another type, returning a different value on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="other">The backup value.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns the value converted to <see cref="T" />.</returns>
[CLSCompliant(false)]
public static T ToOrOther<T>(this IConvertible value, T other, IFormatProvider provider = null)
{
if (value is null)
{
return other;
}
try
{
return To<T>(value, provider);
}
catch (Exception ex) when (ex is InvalidCastException || ex is FormatException)
{
return other;
}
}
/// <summary>
/// Converts the object to another type, returning a different value on failure.
/// </summary>
/// <typeparam name="T">The type to convert to.</typeparam>
/// <param name="value">The object to convert.</param>
/// <param name="newObj">The parameter where the result should be sent.</param>
/// <param name="other">The backup value.</param>
/// <param name="provider">An object that supplies culture-specific formatting information.</param>
/// <returns>Returns <see langword="true" /> on success, <see langword="true" /> on failure.</returns>
[CLSCompliant(false)]
public static bool ToOrOther<T>(this IConvertible value, out T newObj, T other, IFormatProvider provider = null)
{
if (value is null)
{
newObj = other;
return false;
}
try
{
newObj = To<T>(value, provider);
return true;
}
catch (Exception ex) when (ex is InvalidCastException || ex is FormatException)
{
newObj = other;
return false;
}
}
}
}

View File

@ -1,124 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="DateTime" />.
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Returns a rounded integer of the number of years since a given date as of today.
/// </summary>
/// <param name="date">The date from which to start.</param>
/// <returns>Returns the number of years since <paramref name="date" /> as of today.</returns>
public static int Age(this DateTime date)
{
return date.Age(DateTime.Today);
}
/// <summary>
/// Returns a rounded integer of the number of years since a given date as of another given date.
/// </summary>
/// <param name="date">The date from which to start.</param>
/// <param name="asOf">The date at which to stop counting.</param>
/// <returns>
/// Returns the integer number of years since <paramref name="date" /> as of
/// <paramref name="asOf" />.
/// </returns>
public static int Age(this DateTime date, DateTime asOf)
{
return (int)(((asOf.Date - TimeSpan.FromDays(1) - date.Date).TotalDays + 1) / 365.2425);
}
/// <summary>
/// Gets a DateTime representing the first occurence of a specified day in the current month.
/// </summary>
/// <param name="current">The current day.</param>
/// <param name="dayOfWeek">The current day of week.</param>
/// <returns>Returns a date representing the first occurence of <paramref name="dayOfWeek" />.</returns>
public static DateTime First(this DateTime current, DayOfWeek dayOfWeek)
{
var first = current.FirstDayOfMonth();
if (first.DayOfWeek != dayOfWeek)
{
first = first.Next(dayOfWeek);
}
return first;
}
/// <summary>
/// Gets a <see cref="DateTime" /> representing the first day in the current month.
/// </summary>
/// <param name="current">The current date.</param>
/// <returns>Returns a date representing the first day of the month>.</returns>
public static DateTime FirstDayOfMonth(this DateTime current)
{
return current.AddDays(1 - current.Day);
}
/// <summary>
/// Gets a <see cref="DateTime" /> representing the last specified day in the current month.
/// </summary>
/// <param name="current">The current date.</param>
/// <param name="dayOfWeek">The current day of week.</param>
/// <returns>Returns a date representing the final occurence of <paramref name="dayOfWeek" />.</returns>
public static DateTime Last(this DateTime current, DayOfWeek dayOfWeek)
{
var last = current.LastDayOfMonth();
var lastDayOfWeek = last.DayOfWeek;
var diff = dayOfWeek - lastDayOfWeek;
var offset = diff > 0 ? diff - 7 : diff;
return last.AddDays(offset);
}
/// <summary>
/// Gets a <see cref="DateTime" /> representing the last day in the current month.
/// </summary>
/// <param name="current">The current date.</param>
/// <returns>Returns a date representing the last day of the month>.</returns>
public static DateTime LastDayOfMonth(this DateTime current)
{
var daysInMonth = DateTime.DaysInMonth(current.Year, current.Month);
return new DateTime(current.Year, current.Month, daysInMonth);
}
/// <summary>
/// Gets a <see cref="DateTime" /> representing the first date following the current date which falls on the
/// given day of the week.
/// </summary>
/// <param name="current">The current date.</param>
/// <param name="dayOfWeek">The day of week for the next date to get.</param>
/// <returns>Returns a date representing the next occurence of <paramref name="dayOfWeek" />.</returns>
public static DateTime Next(this DateTime current, DayOfWeek dayOfWeek)
{
var offsetDays = dayOfWeek - current.DayOfWeek;
if (offsetDays <= 0)
{
offsetDays += 7;
}
return current.AddDays(offsetDays);
}
/// <summary>
/// Converts the <see cref="DateTime" /> to a Unix timestamp.
/// </summary>
/// <param name="time">The <see cref="DateTime" /> instance.</param>
/// <param name="useMillis">
/// Optional. Whether or not the return value should be represented as milliseconds.
/// Defaults to <see langword="false" />.
/// </param>
/// <returns>Returns a Unix timestamp representing the provided <see cref="DateTime" />.</returns>
public static long ToUnixTimeStamp(this DateTime time, bool useMillis = false)
{
DateTimeOffset offset = time;
return useMillis ? offset.ToUnixTimeMilliseconds() : offset.ToUnixTimeSeconds();
}
}
}

View File

@ -1,101 +0,0 @@
namespace X10D
{
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
/// <summary>
/// A set of extension methods for <see cref="Dictionary{TKey,TValue}" />.
/// </summary>
public static class DictionaryExtensions
{
/// <summary>
/// Converts a <see cref="IReadOnlyDictionary{T1,T2}" /> to an object-relational-safe connection string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value; set.</returns>
public static string ToConnectionString<T1, T2>(this IReadOnlyDictionary<T1, T2> dictionary)
{
static string SanitizeValue<T>(T value)
{
return value is string str &&
Regex.IsMatch(str, "\\s")
? $"\"{str}\""
: value.ToString();
}
var strings = dictionary.Select(o => $"{o.Key}={SanitizeValue(o.Value)}");
return string.Join(";", strings);
}
/// <summary>
/// Converts a <see cref="IDictionary{T1,T2}" /> to an object-relational-safe connection string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value; set.</returns>
public static string ToConnectionString<T1, T2>(this IDictionary<T1, T2> dictionary)
{
return ((IReadOnlyDictionary<T1, T2>)dictionary).ToConnectionString();
}
/// <summary>
/// Converts a <see cref="Dictionary{T1,T2}" /> to an object-relational-safe connection string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value; set.</returns>
public static string ToConnectionString<T1, T2>(this Dictionary<T1, T2> dictionary)
{
return ((IReadOnlyDictionary<T1, T2>)dictionary).ToConnectionString();
}
/// <summary>
/// Converts an <see cref="IReadOnlyDictionary{T1,T2}" /> to a HTTP GET parameter string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value& set.</returns>
public static string ToGetParameters<T1, T2>(this IReadOnlyDictionary<T1, T2> dictionary)
{
static string Sanitize(KeyValuePair<T1, T2> kvp)
{
var key = HttpUtility.UrlEncode(kvp.Key.ToString());
var value = HttpUtility.UrlEncode(kvp.Value.ToString());
return $"{key}={value}";
}
return string.Join("&", dictionary.Select(Sanitize));
}
/// <summary>
/// Converts an <see cref="IDictionary{T1,T2}" /> to a HTTP GET parameter string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value& set.</returns>
public static string ToGetParameters<T1, T2>(this IDictionary<T1, T2> dictionary)
{
return ((IReadOnlyDictionary<T1, T2>)dictionary).ToGetParameters();
}
/// <summary>
/// Converts a <see cref="Dictionary{T1,T2}" /> to a HTTP GET parameter string.
/// </summary>
/// <typeparam name="T1">The key type.</typeparam>
/// <typeparam name="T2">The value type.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <returns>Returns a <see cref="string" /> representing the dictionary as a key=value& set.</returns>
public static string ToGetParameters<T1, T2>(this Dictionary<T1, T2> dictionary)
{
return ((IReadOnlyDictionary<T1, T2>)dictionary).ToGetParameters();
}
}
}

View File

@ -1,93 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="double" />.
/// </summary>
public static class DoubleExtensions
{
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
public static double Clamp(this double value, double min, double max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Converts an angle from degrees to radians.
/// </summary>
/// <param name="angle">The angle in degrees.</param>
/// <returns>Returns <paramref name="angle" /> in radians.</returns>
public static double DegreesToRadians(this double angle)
{
return (Math.PI * angle) / 180.0;
}
/// <summary>
/// Converts the <see cref="double" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this double number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Determines if the <see cref="double" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsEven(this double number)
{
return Math.Abs(number % 2.0) < double.Epsilon;
}
/// <summary>
/// Determines if the <see cref="double" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsOdd(this double number)
{
return !number.IsEven();
}
/// <summary>
/// Converts an angle from radians to degrees.
/// </summary>
/// <param name="angle">The angle in radians.</param>
/// <returns>Returns <paramref name="angle" /> in degrees.</returns>
public static double RadiansToDegrees(this double angle)
{
return angle * (180.0 / Math.PI);
}
/// <summary>
/// Rounds to the nearest value.
/// </summary>
/// <param name="v">The value to round.</param>
/// <param name="nearest">The nearest value.</param>
/// <returns>Returns the rounded value.</returns>
public static double Round(this double v, double nearest = 1)
{
return Math.Round(v / nearest) * nearest;
}
}
}

View File

@ -1,43 +0,0 @@
namespace X10D
{
using System.Net;
/// <summary>
/// Extension methods for <see cref="EndPoint" /> and derived types.
/// </summary>
public static class EndPointExtensions
{
/// <summary>
/// Gets the endpoint hostname.
/// </summary>
/// <param name="endPoint">The endpoint whose hostname to get.</param>
/// <returns>
/// Returns a <see cref="string" /> representing the hostname, which may be an IP or a DNS, or empty
/// string on failure.
/// </returns>
public static string GetHost(this EndPoint endPoint)
{
return endPoint switch
{
IPEndPoint ip => ip.Address.ToString(),
DnsEndPoint dns => dns.Host,
var _ => string.Empty,
};
}
/// <summary>
/// Gets the endpoint port.
/// </summary>
/// <param name="endPoint">The endpoint whose port to get.</param>
/// <returns>Returns an <see cref="int" /> representing the port, or 0 on failure.</returns>
public static int GetPort(this EndPoint endPoint)
{
return endPoint switch
{
IPEndPoint ip => ip.Port,
DnsEndPoint dns => dns.Port,
var _ => 0,
};
}
}
}

View File

@ -1,33 +0,0 @@
namespace X10D
{
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Extension methods for <see cref="IEnumerable{T}" />.
/// </summary>
public static class EnumerableExtensions
{
/// <summary>
/// Splits <paramref name="value" /> into chunks of size <paramref name="chunkSize" />.
/// </summary>
/// <typeparam name="T">Any type.</typeparam>
/// <param name="value">The collection to split.</param>
/// <param name="chunkSize">The maximum length of the nested <see cref="byte" /> collection.</param>
/// <returns>
/// Returns an <see cref="IEnumerable{T}" /> of <see cref="IEnumerable{T}" /> of <see cref="byte" />
/// values.
/// </returns>
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> value, int chunkSize)
{
var enumerable = value.ToArray();
var count = enumerable.LongCount();
chunkSize = chunkSize.Clamp(1, enumerable.Length);
for (var i = 0; i < (int)(count / chunkSize); i++)
{
yield return enumerable.Skip(i * chunkSize).Take(chunkSize);
}
}
}
}

View File

@ -1,189 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="short" />.
/// </summary>
public static class Int16Extensions
{
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
public static short Clamp(this short value, short min, short max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
[CLSCompliant(false)]
public static ushort Clamp(this ushort value, ushort min, ushort max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Converts the <see cref="short" /> to a <see cref="DateTime" /> treating it as a Unix timestamp.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="isMillis">
/// Optional. Whether or not the input value should be treated as milliseconds. Defaults
/// to <see langword="false" />..
/// </param>
/// <returns>
/// Returns a <see cref="DateTime" /> representing <paramref name="timestamp" /> seconds since the Unix
/// epoch.
/// </returns>
public static DateTime FromUnixTimestamp(this short timestamp, bool isMillis = false)
{
return ((long)timestamp).FromUnixTimestamp(isMillis);
}
/// <summary>
/// Converts the <see cref="ushort" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
[CLSCompliant(false)]
public static byte[] GetBytes(this ushort number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Converts the <see cref="short" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this short number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Determines if the <see cref="short" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsEven(this short number)
{
return ((long)number).IsEven();
}
/// <summary>
/// Determines if the <see cref="ushort" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsEven(this ushort number)
{
return ((ulong)number).IsEven();
}
/// <summary>
/// Determines if the <see cref="short" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsOdd(this short number)
{
return !number.IsEven();
}
/// <summary>
/// Determines if the <see cref="ushort" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsOdd(this ushort number)
{
return !number.IsEven();
}
/// <summary>
/// Determines if the <see cref="short" /> is a prime number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is prime, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsPrime(this short number)
{
return ((long)number).IsPrime();
}
/// <summary>
/// Determines if the <see cref="short" /> is a prime number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is prime, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsPrime(this ushort number)
{
return ((ulong)number).IsPrime();
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
public static bool ToBoolean(this short value)
{
return ((long)value).ToBoolean();
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool ToBoolean(this ushort value)
{
return ((ulong)value).ToBoolean();
}
}
}

View File

@ -1,175 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="int" />.
/// </summary>
public static class Int32Extensions
{
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
public static int Clamp(this int value, int min, int max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
[CLSCompliant(false)]
public static uint Clamp(this uint value, uint min, uint max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Converts the <see cref="int" /> to a <see cref="DateTime" /> treating it as a Unix timestamp.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="isMillis">
/// Optional. Whether or not the input value should be treated as milliseconds. Defaults
/// to <see langword="false" />..
/// </param>
/// <returns>
/// Returns a <see cref="DateTime" /> representing <paramref name="timestamp" /> seconds since the Unix
/// epoch.
/// </returns>
public static DateTime FromUnixTimestamp(this int timestamp, bool isMillis = false)
{
return ((long)timestamp).FromUnixTimestamp(isMillis);
}
/// <summary>
/// Converts the <see cref="uint" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
[CLSCompliant(false)]
public static byte[] GetBytes(this uint number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Converts the <see cref="int" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this int number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Determines if the <see cref="int" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsEven(this int number)
{
return ((long)number).IsEven();
}
/// <summary>
/// Determines if the <see cref="uint" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsEven(this uint number)
{
return ((ulong)number).IsEven();
}
/// <summary>
/// Determines if the <see cref="int" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsOdd(this int number)
{
return !number.IsEven();
}
/// <summary>
/// Determines if the <see cref="uint" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsOdd(this uint number)
{
return !number.IsEven();
}
/// <summary>
/// Determines if the <see cref="int" /> is a prime number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is prime, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsPrime(this int number)
{
return ((long)number).IsPrime();
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
public static bool ToBoolean(this int value)
{
return ((long)value).ToBoolean();
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool ToBoolean(this uint value)
{
return ((ulong)value).ToBoolean();
}
}
}

View File

@ -1,241 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="long" />.
/// </summary>
public static class Int64Extensions
{
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
public static long Clamp(this long value, long min, long max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
[CLSCompliant(false)]
public static ulong Clamp(this ulong value, ulong min, ulong max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Converts the <see cref="long" /> to a <see cref="DateTime" /> treating it as a Unix timestamp.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="isMillis">
/// Optional. Whether or not the input value should be treated as milliseconds. Defaults
/// to <see langword="false" />.
/// </param>
/// <returns>
/// Returns a <see cref="DateTime" /> representing <paramref name="timestamp" /> seconds since the Unix
/// epoch.
/// </returns>
public static DateTime FromUnixTimestamp(this long timestamp, bool isMillis = false)
{
var offset = isMillis
? DateTimeOffset.FromUnixTimeMilliseconds(timestamp)
: DateTimeOffset.FromUnixTimeSeconds(timestamp);
return offset.DateTime;
}
/// <summary>
/// Converts the <see cref="ulong" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
[CLSCompliant(false)]
public static byte[] GetBytes(this ulong number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Converts the <see cref="long" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this long number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Determines if the <see cref="long" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsEven(this long number)
{
return Math.Abs(number % 2.0) < double.Epsilon;
}
/// <summary>
/// Determines if the <see cref="ulong" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsEven(this ulong number)
{
return Math.Abs(number % 2.0) < double.Epsilon;
}
/// <summary>
/// Determines if the <see cref="long" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsOdd(this long number)
{
return !IsEven(number);
}
/// <summary>
/// Determines if the <see cref="ulong" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsOdd(this ulong number)
{
return !IsEven(number);
}
/// <summary>
/// Determines if the <see cref="long" /> is a prime number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is prime, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsPrime(this long number)
{
if (number <= 1)
{
return false;
}
if (number == 2)
{
return true;
}
if (number % 2 == 0)
{
return false;
}
var boundary = (long)Math.Floor(Math.Sqrt(number));
for (var i = 3; i <= boundary; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Determines if the <see cref="ulong" /> is a prime number.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is prime, <see langword="false" />
/// otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool IsPrime(this ulong number)
{
if (number <= 1)
{
return false;
}
if (number == 2)
{
return true;
}
if (number % 2 == 0)
{
return false;
}
var boundary = (ulong)Math.Floor(Math.Sqrt(number));
for (uint i = 3; i <= boundary; i += 2)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
public static bool ToBoolean(this long value)
{
return value != 0;
}
/// <summary>
/// Gets an boolean value that represents this integer.
/// </summary>
/// <param name="value">The integer.</param>
/// <returns>
/// Returns <see langword="false" /> if <paramref name="value" /> is 0,
/// <see langword="true" /> otherwise.
/// </returns>
[CLSCompliant(false)]
public static bool ToBoolean(this ulong value)
{
return value != 0;
}
}
}

View File

@ -1,104 +0,0 @@
namespace X10D
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Extension methods for <see cref="IList{T}" />.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Returns a random element from <paramref name="source" /> using a new <see cref="Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to draw from.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
public static T OneOf<T>(this IEnumerable<T> source)
{
return source.OneOf(new Random());
}
/// <summary>
/// Returns a random element from <paramref name="source" /> using the <see cref="Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to draw from.</param>
/// <param name="random">The <see cref="Random" /> instance.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
public static T OneOf<T>(this IEnumerable<T> source, Random random)
{
return source.ToList().OneOf(random);
}
/// <summary>
/// Returns a random element from <paramref name="source" /> using a new <see cref="Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to draw from.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
public static T OneOf<T>(this IList<T> source)
{
return source.OneOf(new Random());
}
/// <summary>
/// Returns a random element from <paramref name="source" /> using the <see cref="Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to draw from.</param>
/// <param name="random">The <see cref="Random" /> instance.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
public static T OneOf<T>(this IList<T> source, Random random)
{
return random.OneOf(source);
}
/// <summary>
/// Shuffles an enumerable.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source)
{
return source.Shuffle(new Random());
}
/// <summary>
/// Shuffles an enumerable.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <param name="random">The <see cref="Random" /> instance.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random)
{
return source.OrderBy(_ => random.Next());
}
/// <summary>
/// Shuffles a list.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IList<T> source)
{
return source.Shuffle(new Random());
}
/// <summary>
/// Shuffles a list.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <param name="random">The <see cref="Random" /> instance.</param>
/// <returns>Returns <paramref name="source" /> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IList<T> source, Random random)
{
return source.OrderBy(_ => random.Next());
}
}
}

View File

@ -1,76 +0,0 @@
namespace X10D
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Extension methods for <see cref="Random" />.
/// </summary>
public static class RandomExtensions
{
/// <summary>
/// Gets the <see cref="System.Random" /> instance to which other extension methods may refer, when one is
/// needed but not provided.
/// </summary>
internal static Random Random { get; } = new Random();
/// <summary>
/// Returns either <see langword="true" /> or <see langword="false" /> based on <paramref name="random" />'s next
/// generation.
/// </summary>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <returns>
/// Returns <see langword="true" /> or <see langword="false" /> depending on the return value
/// from <see cref="System.Random.Next(int)" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="random" /> is <see langword="null" />.</exception>
public static bool CoinToss(this Random random)
{
if (random is null)
{
throw new ArgumentNullException(nameof(random));
}
return random.Next(2) == 0;
}
/// <summary>
/// Returns a random element from <paramref name="source" /> using the <see cref="System.Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <param name="source">The collection from which to draw.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
public static T OneOf<T>(this Random random, params T[] source)
{
return source.ToList().OneOf(random);
}
/// <summary>
/// Returns a random element from <paramref name="source" /> using the <see cref="System.Random" /> instance.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <param name="source">The collection from which to draw.</param>
/// <returns>Returns a random element of type <see cref="T" /> from <paramref name="source" />.</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="random" /> or <paramref name="source" /> is
/// <see langword="null" />.
/// </exception>
public static T OneOf<T>(this Random random, IList<T> source)
{
if (random is null)
{
throw new ArgumentNullException(nameof(random));
}
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return source[random.Next(source.Count)];
}
}
}

View File

@ -1,123 +0,0 @@
namespace X10D
{
using System;
using System.ComponentModel;
using System.Reflection;
/// <summary>
/// Extension methods for various reflection types.
/// </summary>
public static class ReflectionExtensions
{
/// <summary>
/// Gets the value set in this member's annotated <see cref="DefaultValueAttribute" />, or
/// <see langword="default" /> if none exists.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// Returns an <see cref="object" /> representing the value stored in this member's
/// <see cref="DefaultValueAttribute" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="member" /> is <see langword="null" />.</exception>
public static object GetDefaultValue(this MemberInfo member)
{
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (!(member.GetCustomAttribute<DefaultValueAttribute>() is { } attribute))
{
return default;
}
return attribute.Value;
}
/// <summary>
/// Gets the value set in this member's annotated <see cref="DefaultValueAttribute" />, or
/// <see langword="default" /> if none exists.
/// </summary>
/// <typeparam name="T">The type to which the value should cast.</typeparam>
/// <param name="member">The member.</param>
/// <returns>
/// Returns an instance of <typeparamref name="T" /> representing the value stored in this member's
/// <see cref="DefaultValueAttribute" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="member" /> is <see langword="null" />.</exception>
public static T GetDefaultValue<T>(this MemberInfo member)
{
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
return (T)member.GetDefaultValue();
}
/// <summary>
/// Gets the value set in this member's annotated <see cref="DescriptionAttribute" />, or
/// <see langword="null" /> if none exists.
/// </summary>
/// <param name="member">The member.</param>
/// <returns>
/// Returns a string representing the value stored in this member's
/// <see cref="DescriptionAttribute" />.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="member" /> is <see langword="null" />.</exception>
public static string GetDescription(this MemberInfo member)
{
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (!(member.GetCustomAttribute<DescriptionAttribute>() is { } attribute))
{
return null;
}
return attribute.Description;
}
/// <summary>
/// Retrieves a custom attribute of a specified type that is applied to the specified member, and passes it
/// to a selector delegate in order to select one or more the members in the attribute.
/// </summary>
/// <typeparam name="TAttribute">The attribute type.</typeparam>
/// <typeparam name="TReturn">The return type of the <paramref name="selector" /> delegate.</typeparam>
/// <param name="member">The member.</param>
/// <param name="selector">The selector delegate.</param>
/// <returns>
/// Returns an instance of <typeparamref name="TReturn" /> as provided from
/// <paramref name="selector" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="member" /> is <see langword="null" />
/// -or-
/// <paramref name="selector" /> is <see langword="null" />.
/// </exception>
public static TReturn SelectFromCustomAttribute<TAttribute, TReturn>(
this MemberInfo member,
Func<TAttribute, TReturn> selector)
where TAttribute : Attribute
{
if (member is null)
{
throw new ArgumentNullException(nameof(member));
}
if (selector is null)
{
throw new ArgumentNullException(nameof(selector));
}
if (!(member.GetCustomAttribute<TAttribute>() is { } attribute))
{
return default;
}
return selector(attribute);
}
}
}

View File

@ -1,93 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see cref="float" />.
/// </summary>
public static class SingleExtensions
{
/// <summary>
/// Clamps a value between a minimum and a maximum value.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum value.</param>
/// <param name="max">The maximum value.</param>
/// <returns>
/// Returns <paramref name="max" /> if <paramref name="value" /> is greater than it,
/// <paramref name="min" /> if <paramref name="value" /> is less than it,
/// or <paramref name="value" /> itself otherwise.
/// </returns>
public static float Clamp(this float value, float min, float max)
{
return Math.Min(Math.Max(value, min), max);
}
/// <summary>
/// Converts an angle from degrees to radians.
/// </summary>
/// <param name="angle">The angle in degrees.</param>
/// <returns>Returns <paramref name="angle" /> in radians.</returns>
public static float DegreesToRadians(this float angle)
{
return (float)((double)angle).DegreesToRadians();
}
/// <summary>
/// Converts the <see cref="float" /> to a <see cref="byte" />[].
/// </summary>
/// <param name="number">The number to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this float number)
{
return BitConverter.GetBytes(number);
}
/// <summary>
/// Determines if the <see cref="float" /> is even.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is even, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsEven(this float number)
{
return ((double)number).IsEven();
}
/// <summary>
/// Determines if the <see cref="float" /> is odd.
/// </summary>
/// <param name="number">The number.</param>
/// <returns>
/// Returns <see langword="true" /> if <paramref name="number" /> is odd, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsOdd(this float number)
{
return !number.IsEven();
}
/// <summary>
/// Converts an angle from radians to degrees.
/// </summary>
/// <param name="angle">The angle in radians.</param>
/// <returns>Returns <paramref name="angle" /> in degrees.</returns>
public static float RadiansToDegrees(this float angle)
{
return (float)((double)angle).RadiansToDegrees();
}
/// <summary>
/// Rounds to the nearest value.
/// </summary>
/// <param name="v">The value to round.</param>
/// <param name="nearest">The nearest value.</param>
/// <returns>Returns the rounded value.</returns>
public static float Round(this float v, float nearest = 1)
{
return (float)((double)v).Round(nearest);
}
}
}

View File

@ -1,32 +0,0 @@
namespace X10D
{
using System;
using System.IO;
using System.Security.Cryptography;
/// <summary>
/// Extension methods for <see cref="Stream" />.
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Returns the hash of a stream using the specified hashing algorithm.
/// </summary>
/// <typeparam name="T">A <see cref="HashAlgorithm" /> derived type.</typeparam>
/// <param name="stream">The stream whose hash is to be computed.</param>
/// <returns>Returns a <see cref="byte" /> array representing the hash of the stream.</returns>
/// <exception cref="ArgumentNullException"><paramref name="stream" /> is <see langword="null" />.</exception>
public static byte[] GetHash<T>(this Stream stream)
where T : HashAlgorithm
{
if (stream is null)
{
throw new ArgumentNullException(nameof(stream));
}
var create = typeof(T).GetMethod("Create", Array.Empty<Type>());
using var crypt = (T)create?.Invoke(null, null);
return crypt?.ComputeHash(stream);
}
}
}

View File

@ -1,356 +0,0 @@
namespace X10D
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security;
using System.Text;
/// <summary>
/// Extension methods for <see cref="string" />.
/// </summary>
public static class StringExtensions
{
/// <summary>
/// Decodes a base-64 encoded string.
/// </summary>
/// <param name="data">The base-64 string to decode.</param>
/// <returns>Returns the string in plain text.</returns>
public static string Base64Decode(this string data)
{
return Convert.FromBase64String(data).GetString();
}
/// <summary>
/// Encodes a base-64 encoded string.
/// </summary>
/// <param name="value">The plain text string to decode.</param>
/// <returns>Returns the string in plain text.</returns>
public static string Base64Encode(this string value)
{
return Convert.ToBase64String(value.GetBytes());
}
/// <summary>
/// Converts this string from one encoding to another.
/// </summary>
/// <param name="str">The input string.</param>
/// <param name="from">The input encoding.</param>
/// <param name="to">The output encoding.</param>
/// <returns>
/// Returns a new <see cref="string" /> with its data converted to
/// <paramref name="to" />.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="str" /> is <see langword="null" />
/// - or -
/// <paramref name="from" /> is <see langword="null" />
/// -or
/// <paramref name="to" /> is <see langword="null" />.
/// </exception>
public static string ChangeEncoding(this string str, Encoding from, Encoding to)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
if (from is null)
{
throw new ArgumentNullException(nameof(from));
}
if (to is null)
{
throw new ArgumentNullException(nameof(to));
}
return str.GetBytes(from).GetString(to);
}
/// <summary>
/// Parses a <see cref="string" /> into an <see cref="Enum" />.
/// </summary>
/// <typeparam name="T">The type of the <see cref="Enum" />.</typeparam>
/// <param name="value">The <see cref="string" /> value to parse.</param>
/// <returns>The <see cref="Enum" /> value corresponding to the <see cref="string" />.</returns>
/// <remarks>
/// Credit for this method goes to Scott Dorman:
/// (http://geekswithblogs.net/sdorman/Default.aspx).
/// </remarks>
public static T EnumParse<T>(this string value)
{
return value.EnumParse<T>(false);
}
/// <summary>
/// Parses a <see cref="string" /> into an <see cref="Enum" />.
/// </summary>
/// <typeparam name="T">The type of the <see cref="Enum" />.</typeparam>
/// <param name="value">The <see cref="string" /> value to parse.</param>
/// <param name="ignoreCase">Whether or not to ignore casing.</param>
/// <returns>The <see cref="Enum" /> value corresponding to the <see cref="string" />.</returns>
/// <remarks>
/// Credit for this method goes to Scott Dorman:
/// (http://geekswithblogs.net/sdorman/Default.aspx).
/// </remarks>
public static T EnumParse<T>(this string value, bool ignoreCase)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
value = value.Trim();
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(Resource.EnumParseEmptyStringException, nameof(value));
}
var t = typeof(T);
if (!t.IsEnum)
{
throw new ArgumentException(Resource.EnumParseNotEnumException);
}
return (T)Enum.Parse(t, value, ignoreCase);
}
/// <summary>
/// Gets a <see cref="byte" />[] representing the value the <see cref="string" /> with
/// <see cref="Encoding.UTF8" /> encoding.
/// </summary>
/// <param name="str">The string to convert.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
public static byte[] GetBytes(this string str)
{
return str.GetBytes(Encoding.UTF8);
}
/// <summary>
/// Gets a <see cref="byte" />[] representing the value the <see cref="string" /> with the provided encoding.
/// </summary>
/// <param name="str">The string to convert.</param>
/// <param name="encoding">The encoding to use.</param>
/// <returns>Returns a <see cref="byte" />[].</returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="str" /> or <paramref name="encoding" /> or both are
/// <see langword="null" />.
/// </exception>
public static byte[] GetBytes(this string str, Encoding encoding)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
if (encoding is null)
{
throw new ArgumentNullException(nameof(encoding));
}
return encoding.GetBytes(str);
}
/// <summary>
/// Determines if all alpha characters in this string are considered lowercase.
/// </summary>
/// <param name="str">The input string.</param>
/// <returns>
/// Returns <see langword="true" /> if all alpha characters are lowercase, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsLower(this string str)
{
return str.Where(char.IsLetter).All(char.IsLower);
}
/// <summary>
/// Determines if all alpha characters in this string are considered uppercase.
/// </summary>
/// <param name="str">The input string.</param>
/// <returns>
/// Returns <see langword="true" /> if all alpha characters are uppercase, <see langword="false" />
/// otherwise.
/// </returns>
public static bool IsUpper(this string str)
{
return str.Where(char.IsLetter).All(char.IsUpper);
}
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="str" />.
/// </summary>
/// <param name="str">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
public static string Random(this string str, int length)
{
return str.Random(length, RandomExtensions.Random);
}
/// <summary>
/// Generates a new random string by filling it with characters found in <see cref="str" />.
/// </summary>
/// <param name="str">The character set.</param>
/// <param name="length">The length of the string to generate.</param>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <returns>Returns a <see cref="string" /> containing <paramref name="length" /> characters.</returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static string Random(this string str, int length, Random random)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return str.ToCharArray().Random(length, random);
}
/// <summary>
/// Repeats a string a specified number of times.
/// </summary>
/// <param name="str">The string to repeat.</param>
/// <param name="count">The repeat count.</param>
/// <returns>
/// Returns a <see cref="string" /> whose value is <paramref name="str" /> repeated
/// <paramref name="count" /> times.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static string Repeat(this string str, int count)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
var builder = new StringBuilder(str.Length * count);
for (var i = 0; i < count; i++)
{
builder.Append(str);
}
return builder.ToString();
}
/// <summary>
/// Shuffles the characters in the string.
/// </summary>
/// <param name="str">The string to shuffle.</param>
/// <returns>Returns a <see cref="string" /> containing the characters in <paramref name="str" />, rearranged.</returns>
public static string Shuffle(this string str)
{
return str.Shuffle(RandomExtensions.Random);
}
/// <summary>
/// Shuffles the characters in the string.
/// </summary>
/// <param name="str">The string to shuffle.</param>
/// <param name="random">The <see cref="System.Random" /> instance.</param>
/// <returns>Returns a <see cref="string" /> containing the characters in <paramref name="str" />, rearranged.</returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static string Shuffle(this string str, Random random)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return new string(str.ToCharArray().Shuffle(random).ToArray());
}
/// <summary>
/// Splits the <see cref="string" /> into chunks that are no greater than <paramref name="chunkSize" /> in length.
/// </summary>
/// <param name="str">The string to split.</param>
/// <param name="chunkSize">The maximum length of each string in the returned result.</param>
/// <returns>
/// Returns an <see cref="IEnumerable{T}" /> containing <see cref="string" /> instances which are no
/// greater than <paramref name="chunkSize" /> in length.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static IEnumerable<string> Split(this string str, int chunkSize)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return SplitInternal();
IEnumerable<string> SplitInternal()
{
for (var i = 0; i < str.Length; i += chunkSize)
{
yield return str.Substring(i, Math.Min(chunkSize, str.Length - i));
}
}
}
/// <summary>
/// Converts a <see cref="string" /> to a <see cref="SecureString" />.
/// </summary>
/// <param name="str">The string to convert.</param>
/// <returns>Returns a <see cref="SecureString" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static SecureString ToSecureString(this string str)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
if (string.IsNullOrWhiteSpace(str))
{
return null;
}
var result = new SecureString();
foreach (var c in str)
{
result.AppendChar(c);
}
return result;
}
/// <summary>
/// Converts a <see cref="SecureString" /> to a <see cref="string" />.
/// </summary>
/// <param name="str">The <see cref="SecureString" /> to convert.</param>
/// <param name="extension">Whether or not to use this extension method.</param>
/// <returns>Returns a <see cref="string" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static string ToString(this SecureString str, bool extension)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return extension ? new NetworkCredential(string.Empty, str).Password : str.ToString();
}
/// <summary>
/// Parses a shorthand time span string (e.g. 3w 2d 1.5h) and converts it to an instance of
/// <see cref="TimeSpan" />.
/// </summary>
/// <param name="str">The input string.</param>
/// <returns>Returns an instance of <see cref="TimeSpan" />.</returns>
/// <exception cref="ArgumentNullException"><paramref name="str" /> is <see langword="null" />.</exception>
public static TimeSpan ToTimeSpan(this string str)
{
if (str is null)
{
throw new ArgumentNullException(nameof(str));
}
return TimeSpanParser.Parse(str);
}
}
}

View File

@ -1,56 +0,0 @@
namespace X10D
{
using System;
/// <summary>
/// Extension methods for <see langword="struct" /> types.
/// </summary>
public static class StructExtensions
{
/// <summary>
/// Returns the next value in an <see cref="Enum" /> using the specified value as a starting point.
/// </summary>
/// <typeparam name="T">An <see cref="Enum" />.</typeparam>
/// <param name="src">An <see cref="Enum" /> value.</param>
/// <param name="wrap">
/// Optional. Whether or not to wrap to the to the start of the enum. Defaults to
/// true.
/// </param>
/// <returns>Returns a <see cref="T" /> value.</returns>
public static T Next<T>(this T src, bool wrap = true)
where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum");
}
var arr = (T[])Enum.GetValues(src.GetType());
var j = Array.IndexOf(arr, src) + 1;
return arr.Length == j ? arr[wrap ? 0 : j - 1] : arr[j];
}
/// <summary>
/// Returns the previous value in an <see cref="Enum" /> using the specified value as a starting point.
/// </summary>
/// <typeparam name="T">An <see cref="Enum" />.</typeparam>
/// <param name="src">An <see cref="Enum" /> value.</param>
/// <param name="wrap">
/// Optional. Whether or not to wrap to the to the end of the enum. Defaults to
/// true.
/// </param>
/// <returns>Returns a <see cref="T" /> value.</returns>
public static T Previous<T>(this T src, bool wrap = true)
where T : struct
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum");
}
var arr = (T[])Enum.GetValues(src.GetType());
var j = Array.IndexOf(arr, src) - 1;
return j < 0 ? arr[wrap ? arr.Length - 1 : 0] : arr[j];
}
}
}

View File

@ -1,77 +0,0 @@
namespace X10D
{
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
/// <summary>
/// Represents a class which contains a <see cref="string" /> parser which converts into <see cref="TimeSpan" />.
/// </summary>
public static class TimeSpanParser
{
/// <summary>
/// Parses a shorthand time span string (e.g. 3w 2d 1.5h) and converts it to an instance of
/// <see cref="TimeSpan" />.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="provider">The format provider.</param>
/// <returns>Returns an instance of <see cref="TimeSpan" />.</returns>
public static TimeSpan Parse(string input, IFormatProvider provider = null)
{
const string realNumberPattern = @"([0-9]*\.[0-9]+|[0-9]+)";
var pattern = $"^(?:{realNumberPattern} *w)? *" +
$"(?:{realNumberPattern} *d)? *" +
$"(?:{realNumberPattern} *h)? *" +
$"(?:{realNumberPattern} *m)? *" +
$"(?:{realNumberPattern} *s)? *" +
$"(?:{realNumberPattern} *ms)?$";
var match = Regex.Match(input, pattern);
double weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0, milliseconds = 0;
if (match.Groups[1].Success)
{
weeks = double.Parse(match.Groups[1].Value, provider);
}
if (match.Groups[2].Success)
{
days = double.Parse(match.Groups[2].Value, provider);
}
if (match.Groups[3].Success)
{
hours = double.Parse(match.Groups[3].Value, provider);
}
if (match.Groups[4].Success)
{
minutes = double.Parse(match.Groups[4].Value, provider);
}
if (match.Groups[5].Success)
{
seconds = double.Parse(match.Groups[5].Value, provider);
}
if (match.Groups[6].Success)
{
milliseconds = double.Parse(match.Groups[6].Value, provider);
}
Trace.WriteLine($"Input: {input}");
Trace.WriteLine($"Parsed: {weeks}w {days}d {hours}h {minutes}m {seconds}s {milliseconds}ms");
var span = TimeSpan.Zero;
span += TimeSpan.FromDays(weeks * 7);
span += TimeSpan.FromDays(days);
span += TimeSpan.FromHours(hours);
span += TimeSpan.FromMinutes(minutes);
span += TimeSpan.FromSeconds(seconds);
span += TimeSpan.FromMilliseconds(milliseconds);
return span;
}
}
}

View File

@ -1,21 +0,0 @@
namespace X10D
{
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for <see cref="WaitHandle" />.
/// </summary>
public static class WaitHandleExtensions
{
/// <summary>
/// Returns a <see cref="Task" /> which can be awaited until the current <see cref="WaitHandle" /> receives a signal.
/// </summary>
/// <param name="handle">The <see cref="WaitHandle" /> instance.</param>
/// <returns>Returns a task which wraps <see cref="WaitHandle.WaitOne()" />.</returns>
public static Task WaitOneAsync(this WaitHandle handle)
{
return new Task(() => handle.WaitOne());
}
}
}

View File

@ -1 +0,0 @@
theme: jekyll-theme-slate

BIN
icon.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB