Skip to content

Commit

Permalink
Use ReadOnlySpan<byte> in netstd 2.1 to avoid locking
Browse files Browse the repository at this point in the history
  • Loading branch information
mattjohnsonpint committed Sep 17, 2020
1 parent 95243e4 commit 4b5a5d7
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/GeoTimeZone/GeoTimeZone.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Provides an IANA time zone identifier from latitude and longitude coordinates.</Description>
<Authors>Matt Johnson-Pint,Simon Bartlett</Authors>
<TargetFrameworks>netstandard2.0;netstandard1.1;net461;net45;net40</TargetFrameworks>
<TargetFrameworks>netstandard2.1;netstandard2.0;netstandard1.1;net461;net45;net40</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<PackageId>GeoTimeZone</PackageId>
<PackageTags>timezone;time;zone;geolocation;geo;latitude;longitude;coordinates;iana;tzdb</PackageTags>
Expand Down
11 changes: 10 additions & 1 deletion src/GeoTimeZone/TimezoneFileReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ internal static class TimezoneFileReader
private const int LineLength = 8;
private const int LineEndLength = 1;

#if !NETSTANDARD2_1
private static readonly object Locker = new object();
#endif

private static readonly Lazy<MemoryStream> LazyData = new Lazy<MemoryStream>(LoadData);
private static readonly Lazy<int> LazyCount = new Lazy<int>(GetCount);

Expand Down Expand Up @@ -47,16 +50,22 @@ public static string GetLine(int line)
{
int index = (LineLength + LineEndLength) * (line - 1);

MemoryStream stream = LazyData.Value;

#if NETSTANDARD2_1
var span = new ReadOnlySpan<byte>(stream.GetBuffer(), index, LineLength);
return Encoding.UTF8.GetString(span);
#else
var buffer = new byte[LineLength];

lock (Locker)
{
MemoryStream stream = LazyData.Value;
stream.Position = index;
stream.Read(buffer, 0, LineLength);
}

return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
#endif
}
}
}

0 comments on commit 4b5a5d7

Please sign in to comment.