Skip to content

Commit

Permalink
[core] Fix all the new nullability warnings
Browse files Browse the repository at this point in the history
This cropped up as netcoreapp3.0 and net5.0 targets were added
to all the libs which compiled profile specific optimisations.

Fun. I don't have regrets about this.
  • Loading branch information
alanmcgovern committed Mar 30, 2022
1 parent 3c41956 commit 9095e77
Show file tree
Hide file tree
Showing 82 changed files with 251 additions and 237 deletions.
2 changes: 1 addition & 1 deletion src/BigEndianBigInteger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public BigEndianBigInteger (int value)
public int CompareTo (BigEndianBigInteger other)
=> Value.CompareTo (other.Value);

public override bool Equals (object obj)
public override bool Equals (object? obj)
=> obj is BigEndianBigInteger val && Equals (val);

public bool Equals (BigEndianBigInteger other)
Expand Down
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<CI Condition="'$(CI)' == '' and '$(TF_BUILD)' == 'true'">true</CI>
<CI Condition="'$(CI)' == '' ">false</CI>

<NoWarn>1701;1702;1591;0419</NoWarn>
<NoWarn>1701;1702;1591;0419;netsdk1138</NoWarn>

<LangVersion>8.0</LangVersion>
<DebugType>portable</DebugType>
Expand Down
1 change: 1 addition & 0 deletions src/Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<Compile Include="$(MSBuildThisFileDirectory)MemoryExtensions.cs" Condition="'$(UseMemoryExtensions)' == 'true'" Link="Linked\%(FileName)%(Extension)" />
<Compile Include="$(MSBuildThisFileDirectory)BigEndianBigInteger.cs" Link="Linked\%(FileName)%(Extension)" Condition="$(ProjectName) == 'MonoTorrent.Dht' or $(ProjectName) == 'MonoTorrent.Client'" />
<Compile Include="$(MSBuildThisFileDirectory)ValueStopwatch.cs" Link="Linked\%(FileName)%(Extension)" />
<Compile Include="$(MSBuildThisFileDirectory)NullabilityAttributes.cs" Link="Linked\%(FileName)%(Extension)" Condition="'$(TargetFramework)' == 'netstandard2.0'" />
</ItemGroup>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;

namespace MonoTorrent.BEncoding
Expand Down Expand Up @@ -110,7 +111,7 @@ public override bool Equals (object? obj)
return false;

foreach (KeyValuePair<BEncodedString, BEncodedValue> keypair in dictionary) {
if (!other.TryGetValue (keypair.Key, out BEncodedValue val))
if (!other.TryGetValue (keypair.Key, out BEncodedValue? val))
return false;

if (!keypair.Value.Equals (val))
Expand Down Expand Up @@ -176,7 +177,7 @@ public void CopyTo (KeyValuePair<BEncodedString, BEncodedValue>[] array, int arr

public BEncodedValue? GetValueOrDefault (BEncodedString key, BEncodedValue? defaultValue)
{
return dictionary.TryGetValue (key, out BEncodedValue value) ? value : defaultValue;
return dictionary.TryGetValue (key, out BEncodedValue? value) ? value : defaultValue;
}

public bool IsReadOnly => false;
Expand All @@ -191,7 +192,9 @@ public bool Remove (KeyValuePair<BEncodedString, BEncodedValue> item)
return dictionary.Remove (item.Key);
}

public bool TryGetValue (BEncodedString key, out BEncodedValue value)
#pragma warning disable 8767
public bool TryGetValue (BEncodedString key, [MaybeNullWhen (false)] out BEncodedValue value)
#pragma warning restore 8767
{
return dictionary.TryGetValue (key, out value);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public override int LengthInBytes ()
return length;
}

public override bool Equals (object obj)
public override bool Equals (object? obj)
{
if (!(obj is BEncodedList other))
return false;
Expand Down
16 changes: 5 additions & 11 deletions src/MonoTorrent.BEncoding/MonoTorrent.BEncoding/BEncodedNumber.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,22 +108,16 @@ public override int LengthInBytes ()
// Add 2 for the 'i' and 'e'. Special case '0' as we can't Log10 it. Add 1 if the number is negative. Then calculate digits!
=> 2 + (Number == 0 ? 1 : (Number > 0 ? 1 : 2) + (int) Math.Log10 (Math.Abs ((double)Number)));

public int CompareTo (object other)
public int CompareTo (object? other)
{
if (other is BEncodedNumber || other is long || other is int)
return CompareTo ((BEncodedNumber) other);

return -1;
}

public int CompareTo (BEncodedNumber other)
{
if (other == null)
throw new ArgumentNullException (nameof (other));

return Number.CompareTo (other.Number);
return 1;
}

public int CompareTo (BEncodedNumber? other)
=> other == null ? 1 : Number.CompareTo (other.Number);

public int CompareTo (long other)
=> Number.CompareTo (other);
Expand All @@ -133,7 +127,7 @@ public int CompareTo (long other)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals (object obj)
public override bool Equals (object? obj)
=> obj is BEncodedNumber obj2 ? Number == obj2.Number : false;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,7 @@ public class BEncodedString : BEncodedValue, IComparable<BEncodedString>, IEquat
{
public static readonly BEncodedString Empty = new BEncodedString (ReadOnlyMemory<byte>.Empty);

public static bool IsNullOrEmpty (
#if !NETSTANDARD2_0
[NotNullWhen (false)]
#endif
BEncodedString? value)
public static bool IsNullOrEmpty ([NotNullWhen (false)] BEncodedString? value)
=> value is null || value.Span.IsEmpty;

public static BEncodedString FromMemory (ReadOnlyMemory<byte> buffer)
Expand All @@ -61,21 +57,15 @@ public static BEncodedString UrlDecode (string urlEncodedValue)
return new BEncodedString (new ReadOnlyMemory<byte> (HttpUtility.UrlDecodeToBytes (urlEncodedValue, Encoding.UTF8)));
}

#if !NETSTANDARD2_0
[return: NotNullIfNotNull ("value")]
#endif
public static implicit operator BEncodedString? (string? value)
=> value is null ? null : (value.Length == 0 ? Empty : new BEncodedString (value));

#if !NETSTANDARD2_0
[return: NotNullIfNotNull ("value")]
#endif
public static implicit operator BEncodedString? (char[]? value)
=> value is null ? null : (value.Length == 0 ? Empty : new BEncodedString (value));

#if !NETSTANDARD2_0
[return: NotNullIfNotNull ("value")]
#endif
public static implicit operator BEncodedString? (byte[]? value)
=> value is null ? null : (value.Length == 0 ? Empty : new BEncodedString (value));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public override int Read (byte[] buffer, int offset, int count)
public byte[] TransformFinalBlock ()
{
algorithm.TransformFinalBlock (read_one_buffer, 0, 0);
return algorithm.Hash;
return algorithm.Hash!;
}

public override void Flush ()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@ protected override void HandleLtMetadataMessage (PeerId id, LTMetadata message)

try {
if (this.Settings.AutoSaveLoadMagnetLinkMetadata) {
if (!Directory.Exists (Path.GetDirectoryName (savePath)))
Directory.CreateDirectory (Path.GetDirectoryName (savePath));
if (Path.GetDirectoryName (savePath) is string parentDir && !Directory.Exists (parentDir))
Directory.CreateDirectory (parentDir);
File.Delete (savePath);
File.WriteAllBytes (savePath, dict.Encode ());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public int? PreferredChunkSize {
int? preferredChunkSize = null;
for (int i = 0; i < limiters.Count; i++)
if (limiters[i].PreferredChunkSize.HasValue)
preferredChunkSize = preferredChunkSize.HasValue ? Math.Min (limiters[i].PreferredChunkSize.Value, preferredChunkSize.Value) : limiters[i].PreferredChunkSize.Value;
preferredChunkSize = preferredChunkSize.HasValue ? Math.Min (limiters[i].PreferredChunkSize!.Value, preferredChunkSize.Value) : limiters[i].PreferredChunkSize!.Value;
return preferredChunkSize;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ internal TrackerTier (Factories factories, IEnumerable<string> trackerUrls)
{
var trackerList = new List<ITracker> ();
foreach (string trackerUrl in trackerUrls) {
if (!Uri.TryCreate (trackerUrl, UriKind.Absolute, out Uri result)) {
if (!Uri.TryCreate (trackerUrl, UriKind.Absolute, out Uri? result)) {
logger.InfoFormatted ("Invalid tracker Url specified: {0}", trackerUrl);
continue;
}
Expand Down
21 changes: 10 additions & 11 deletions src/MonoTorrent.Client/MonoTorrent.Client/ClientEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,11 @@ public static async Task<ClientEngine> RestoreStateAsync (ReadOnlyMemory<byte> b
foreach (BEncodedDictionary file in (BEncodedList) torrent[nameof (manager.Files)]) {
TorrentFileInfo torrentFile;
torrentFile = (TorrentFileInfo) manager.Files.Single (t => t.Path == ((BEncodedString) file[nameof (torrentFile.Path)]).Text);
torrentFile.Priority = (Priority) Enum.Parse (typeof (Priority), file[nameof (torrentFile.Priority)].ToString ());
torrentFile.Priority = (Priority) Enum.Parse (typeof (Priority), file[nameof (torrentFile.Priority)].ToString ()!);
torrentFile.FullPath = ((BEncodedString) file[nameof (torrentFile.FullPath)]).Text;
}
} else {
var magnetLink = MagnetLink.Parse (torrent[nameof (manager.MagnetLink)].ToString ());
var magnetLink = MagnetLink.Parse (torrent[nameof (manager.MagnetLink)].ToString ()!);
if (streaming)
await clientEngine.AddStreamingAsync (magnetLink, saveDirectory, torrentSettings);
else
Expand Down Expand Up @@ -337,7 +337,7 @@ public async Task<TorrentManager> AddAsync (string metadataPath, string saveDire

var metadataCachePath = Settings.GetMetadataPath (torrent.InfoHashes);
if (metadataPath != metadataCachePath) {
Directory.CreateDirectory (Path.GetDirectoryName (metadataCachePath));
Directory.CreateDirectory (Path.GetDirectoryName (metadataCachePath)!);
File.Copy (metadataPath, metadataCachePath, true);
}
return await AddAsync (null, torrent, saveDirectory, settings);
Expand Down Expand Up @@ -369,7 +369,7 @@ public async Task<TorrentManager> AddAsync (Torrent torrent, string saveDirector
}

var metadataCachePath = Settings.GetMetadataPath (torrent.InfoHashes);
Directory.CreateDirectory (Path.GetDirectoryName (metadataCachePath));
Directory.CreateDirectory (Path.GetDirectoryName (metadataCachePath)!);
File.WriteAllBytes (metadataCachePath, editor.ToDictionary ().Encode ());

return await AddAsync (null, torrent, saveDirectory, settings);
Expand Down Expand Up @@ -572,12 +572,12 @@ public async Task<ReadOnlyMemory<byte>> DownloadMetadataAsync (MagnetLink magnet
return data;
}

async void HandleLocalPeerFound (object sender, LocalPeerFoundEventArgs args)
async void HandleLocalPeerFound (object? sender, LocalPeerFoundEventArgs args)
{
try {
await MainLoop;

TorrentManager manager = allTorrents.FirstOrDefault (t => t.InfoHashes.Contains (args.InfoHash));
TorrentManager? manager = allTorrents.FirstOrDefault (t => t.InfoHashes.Contains (args.InfoHash));
// There's no TorrentManager in the engine
if (manager == null)
return;
Expand Down Expand Up @@ -669,12 +669,11 @@ void RegisterLocalPeerDiscovery (ILocalPeerDiscovery? localPeerDiscovery)
}
}

async void DhtEnginePeersFound (object o, PeersFoundEventArgs e)
async void DhtEnginePeersFound (object? o, PeersFoundEventArgs e)
{
await MainLoop;

TorrentManager manager = allTorrents.FirstOrDefault (t => t.InfoHashes.Contains (e.InfoHash));

TorrentManager? manager = allTorrents.FirstOrDefault (t => t.InfoHashes.Contains (e.InfoHash));
if (manager == null)
return;

Expand All @@ -688,7 +687,7 @@ async void DhtEnginePeersFound (object o, PeersFoundEventArgs e)
}
}

async void DhtEngineStateChanged (object o, EventArgs e)
async void DhtEngineStateChanged (object? o, EventArgs e)
{
if (DhtEngine.State != DhtState.Ready)
return;
Expand Down Expand Up @@ -869,7 +868,7 @@ async ReusableTasks.ReusableTask MaybeSaveDhtNodes ()
// concurrently.
using (await dhtNodeLocker.EnterAsync ().ConfigureAwait (false)) {
var savePath = Settings.GetDhtNodeCacheFilePath ();
var parentDir = Path.GetDirectoryName (savePath);
var parentDir = Path.GetDirectoryName (savePath)!;
Directory.CreateDirectory (parentDir);
File.WriteAllBytes (savePath, nodes.ToArray ());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,21 +125,13 @@ public void Encode (Stream s)
s.Write (data, 0, data.Length);
}

#if NETSTANDARD2_0
public static bool TryLoad (Stream s, out FastResume? fastResume)
#else
public static bool TryLoad (Stream s, [NotNullWhen (true)] out FastResume? fastResume)
#endif
{
fastResume = Load (s);
return fastResume != null;
}

#if NETSTANDARD2_0
public static bool TryLoad (string fastResumeFilePath, out FastResume? fastResume)
#else
public static bool TryLoad (string fastResumeFilePath, [NotNullWhen (true)] out FastResume? fastResume)
#endif
{
fastResume = null;
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ internal async ReusableTask<bool> GetHashAsync (ITorrentManagerInfo manager, int

await IOLoop;

if (IncrementalHashes.TryGetValue (ValueTuple.Create (manager, pieceIndex), out IncrementalHashData incrementalHash)) {
if (IncrementalHashes.TryGetValue (ValueTuple.Create (manager, pieceIndex), out IncrementalHashData? incrementalHash)) {
// Immediately remove it from the dictionary so another thread writing data to using `WriteAsync` can't try to use it
IncrementalHashes.Remove (ValueTuple.Create (manager, pieceIndex));

Expand Down Expand Up @@ -477,7 +477,7 @@ internal async ReusableTask WriteAsync (ITorrentManagerInfo manager, BlockInfo r

try {
int pieceIndex = request.PieceIndex;
if (!IncrementalHashes.TryGetValue (ValueTuple.Create (manager, pieceIndex), out IncrementalHashData incrementalHash) && request.StartOffset == 0) {
if (!IncrementalHashes.TryGetValue (ValueTuple.Create (manager, pieceIndex), out IncrementalHashData? incrementalHash) && request.StartOffset == 0) {
incrementalHash = IncrementalHashes[ValueTuple.Create (manager, pieceIndex)] = IncrementalHashCache.Dequeue ();
incrementalHash.PrepareForFirstUse (manager, pieceIndex);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public void SetListener (IPeerConnectionListener listener)
Listener.ConnectionReceived += ConnectionReceived;
}

async void ConnectionReceived (object sender, PeerConnectionEventArgs e)
async void ConnectionReceived (object? sender, PeerConnectionEventArgs e)
{
await ClientEngine.MainLoop;
var peer = new Peer ("", e.Connection.Uri, EncryptionTypes.All);
Expand All @@ -93,7 +93,7 @@ async void ConnectionReceived (object sender, PeerConnectionEventArgs e)
return;
}
if (!e.Connection.IsIncoming) {
var manager = Engine.Torrents.FirstOrDefault (t => t.InfoHashes.Contains (e.InfoHash!));
var manager = Engine.Torrents.FirstOrDefault (t => t.InfoHashes.Contains (e.InfoHash!))!;
var id = new PeerId (peer, e.Connection, new MutableBitField (manager.Bitfield.Length).SetAll (false));
id.LastMessageSent.Restart ();
id.LastMessageReceived.Restart ();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ internal PeerExchangeManager (TorrentManager manager, PeerId id)
manager.OnPeerFound += OnAdd;
}

internal void OnAdd (object source, PeerAddedEventArgs e)
internal void OnAdd (object? source, PeerAddedEventArgs e)
{
addedPeers.Add (e.Peer);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ public override string ToString ()
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals (object obj)
public override bool Equals (object? obj)
{
return (!(obj is TorrentManager m)) ? false : Equals (m);
}
Expand All @@ -506,7 +506,7 @@ public override bool Equals (object obj)
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals (TorrentManager other)
public bool Equals (TorrentManager? other)
=> other != null && other.InfoHashes == InfoHashes;

/// <summary>
Expand Down Expand Up @@ -965,8 +965,10 @@ internal void RaiseConnectionAttemptFailed (ConnectionAttemptFailedEventArgs arg

internal void UpdateLimiters ()
{
DownloadLimiter.UpdateChunks (Settings.MaximumDownloadSpeed, Monitor.ReceiveRate, ClientEngine.PreferredChunkSize (Engine.Settings.MaximumDownloadSpeed, Settings.MaximumDownloadSpeed));
UploadLimiter.UpdateChunks (Settings.MaximumUploadSpeed, Monitor.SendRate, ClientEngine.PreferredChunkSize (Engine.Settings.MaximumUploadSpeed, Settings.MaximumUploadSpeed));
if (Engine != null) {
DownloadLimiter.UpdateChunks (Settings.MaximumDownloadSpeed, Monitor.ReceiveRate, ClientEngine.PreferredChunkSize (Engine.Settings.MaximumDownloadSpeed, Settings.MaximumDownloadSpeed));
UploadLimiter.UpdateChunks (Settings.MaximumUploadSpeed, Monitor.SendRate, ClientEngine.PreferredChunkSize (Engine.Settings.MaximumUploadSpeed, Settings.MaximumUploadSpeed));
}
}
#endregion Internal Methods

Expand Down Expand Up @@ -1048,7 +1050,7 @@ internal async ReusableTask MaybeWriteFastResumeAsync ()

await MainLoop.SwitchToThreadpool ();
var fastResumePath = Engine.Settings.GetFastResumePath (InfoHashes);
var parentDirectory = Path.GetDirectoryName (fastResumePath);
var parentDirectory = Path.GetDirectoryName (fastResumePath)!;
Directory.CreateDirectory (parentDirectory);
File.WriteAllBytes (fastResumePath, fastResumeData);
}
Expand All @@ -1066,7 +1068,7 @@ internal void SetTrackerManager (ITrackerManager manager)
}
}

async void HandleTrackerAnnounceComplete (object o, AnnounceResponseEventArgs e)
async void HandleTrackerAnnounceComplete (object? o, AnnounceResponseEventArgs e)
{
if (e.Successful) {
await ClientEngine.MainLoop;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,10 @@ public async ReusableTask ScrapeAsync (ITracker tracker, CancellationToken token
await trackerTier.ScrapeAsync (args, tracker, token);
}

void RaiseAnnounceComplete (object sender, AnnounceResponseEventArgs args)
void RaiseAnnounceComplete (object? sender, AnnounceResponseEventArgs args)
=> AnnounceComplete?.InvokeAsync (this, args);

void RaiseScrapeComplete (object sender, ScrapeResponseEventArgs args)
void RaiseScrapeComplete (object? sender, ScrapeResponseEventArgs args)
=> ScrapeComplete?.InvokeAsync (this, args);
}
}
Loading

0 comments on commit 9095e77

Please sign in to comment.