Skip to content

Commit

Permalink
removing IByteBuffer
Browse files Browse the repository at this point in the history
  • Loading branch information
antonfirsov committed Aug 9, 2018
1 parent f37bfd0 commit 79f6e50
Show file tree
Hide file tree
Showing 12 changed files with 44 additions and 97 deletions.
2 changes: 2 additions & 0 deletions ImageSharp.Web.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" /&gt;</s:String></wpf:ResourceDictionary>
5 changes: 3 additions & 2 deletions src/ImageSharp.Web/Caching/IImageCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.Memory;

// TODO: Do we add cleanup to this? Scalable caches probably shouldn't do so.
namespace SixLabors.ImageSharp.Web.Caching
Expand All @@ -25,7 +26,7 @@ public interface IImageCache
/// </summary>
/// <param name="key">The cache key.</param>
/// <returns>The <see cref="Task{IByteBuffer}"/>.</returns>
Task<IByteBuffer> GetAsync(string key);
Task<IManagedByteBuffer> GetAsync(string key);

/// <summary>
/// Returns a value indicating whether the current cached item is expired.
Expand All @@ -46,6 +47,6 @@ public interface IImageCache
/// <param name="key">The cache key.</param>
/// <param name="value">The value to store.</param>
/// <returns>The <see cref="Task{DateTimeOffset}"/>.</returns>
Task<DateTimeOffset> SetAsync(string key, IByteBuffer value);
Task<DateTimeOffset> SetAsync(string key, IManagedByteBuffer value);
}
}
10 changes: 6 additions & 4 deletions src/ImageSharp.Web/Caching/PhysicalFileSystemCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Microsoft.Extensions.Options;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.ImageSharp.Web.Middleware;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Caching
{
Expand Down Expand Up @@ -91,11 +92,11 @@ public PhysicalFileSystemCache(IHostingEnvironment environment, IBufferManager b
};

/// <inheritdoc/>
public async Task<IByteBuffer> GetAsync(string key)
public async Task<IManagedByteBuffer> GetAsync(string key)
{
IFileInfo fileInfo = this.fileProvider.GetFileInfo(this.ToFilePath(key));

IByteBuffer buffer;
IManagedByteBuffer buffer;

// Check to see if the file exists.
if (!fileInfo.Exists)
Expand Down Expand Up @@ -158,7 +159,7 @@ public Task<CachedInfo> IsExpiredAsync(HttpContext context, string key, DateTime
}

/// <inheritdoc/>
public async Task<DateTimeOffset> SetAsync(string key, IByteBuffer value)
public async Task<DateTimeOffset> SetAsync(string key, IManagedByteBuffer value)
{
string path = Path.Combine(this.environment.WebRootPath, this.ToFilePath(key));
string directory = Path.GetDirectoryName(path);
Expand All @@ -170,7 +171,8 @@ public async Task<DateTimeOffset> SetAsync(string key, IByteBuffer value)

using (FileStream fileStream = File.Create(path))
{
await fileStream.WriteAsync(value.Array, 0, value.Length);
// TODO: Do buffered write here!
await fileStream.WriteAsync(value.Array, 0, value.Memory.Length);
}

return File.GetLastWriteTimeUtc(path);
Expand Down
4 changes: 3 additions & 1 deletion src/ImageSharp.Web/Memory/IBufferManager.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.

using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Memory
{
/// <summary>
Expand All @@ -13,6 +15,6 @@ public interface IBufferManager
/// </summary>
/// <param name="length">The minimum length of the array to return.</param>
/// <returns>The <see cref="IByteBuffer"/>.</returns>
IByteBuffer Allocate(int length);
IManagedByteBuffer Allocate(int length);
}
}
20 changes: 0 additions & 20 deletions src/ImageSharp.Web/Memory/IByteBuffer.cs

This file was deleted.

19 changes: 5 additions & 14 deletions src/ImageSharp.Web/Memory/PooledBufferManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0.

using System.Buffers;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Memory
{
Expand All @@ -10,6 +11,8 @@ namespace SixLabors.ImageSharp.Web.Memory
/// </summary>
public class PooledBufferManager : IBufferManager
{
private readonly MemoryAllocator allocator = ArrayPoolMemoryAllocator.CreateDefault();

/// <summary>
/// The maximum length of each array in the pool (2^21).
/// </summary>
Expand Down Expand Up @@ -49,21 +52,9 @@ public PooledBufferManager(int maxLength, int maxArraysPerBucket)
}

/// <inheritdoc />
public IByteBuffer Allocate(int minimumLength)
{
return new PooledByteBuffer(this, this.arrayPool.Rent(minimumLength), minimumLength);
}

/// <summary>
/// Returns the rented array back to the pool.
/// </summary>
/// <param name="array">The array to return to the buffer pool.</param>
internal void Return(byte[] array)
public IManagedByteBuffer Allocate(int minimumLength)
{
if (array != null)
{
this.arrayPool.Return(array);
}
return this.allocator.AllocateManagedByteBuffer(minimumLength);
}
}
}
42 changes: 0 additions & 42 deletions src/ImageSharp.Web/Memory/PooledByteBuffer.cs

This file was deleted.

3 changes: 2 additions & 1 deletion src/ImageSharp.Web/Middleware/ImageContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using Microsoft.AspNetCore.Http.Headers;
using Microsoft.Net.Http.Headers;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Middleware
{
Expand Down Expand Up @@ -148,7 +149,7 @@ public Task SendStatusAsync(int statusCode, string contentType)
/// <param name="buffer">The cached image buffer.</param>
/// <param name="length">The The length, in bytes, of the cached image buffer.</param>
/// <returns>The <see cref="Task"/>.</returns>
public async Task SendAsync(string contentType, IByteBuffer buffer, long length)
public async Task SendAsync(string contentType, IManagedByteBuffer buffer, long length)
{
this.ApplyResponseHeaders(ResponseConstants.Status200Ok, contentType);

Expand Down
20 changes: 13 additions & 7 deletions src/ImageSharp.Web/Middleware/ImageSharpMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.ImageSharp.Web.Processors;
using SixLabors.ImageSharp.Web.Resolvers;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Middleware
{
Expand Down Expand Up @@ -157,7 +158,7 @@ public async Task Invoke(HttpContext context)
}

// Create a cache key based on all the components of the requested url
string uri = $"{context.Request.Host.ToString().ToLowerInvariant()}/{context.Request.PathBase.ToString().ToLowerInvariant()}/{context.Request.Path}{QueryString.Create(commands)}";
string uri = GetUri(context, commands);
string key = this.cacheHash.Create(uri, this.options.CachedNameLength);

// Prevent identical requests from running at the same time
Expand Down Expand Up @@ -193,7 +194,7 @@ public async Task Invoke(HttpContext context)
if (!info.Expired)
{
// We're pulling the buffer from the cache. This should be cleaned up after.
using (IByteBuffer cachedBuffer = await this.cache.GetAsync(key))
using (IManagedByteBuffer cachedBuffer = await this.cache.GetAsync(key))
{
// Image is a cached image. Return the correct response now.
await this.SendResponse(imageContext, key, info.LastModifiedUtc, cachedBuffer);
Expand All @@ -203,8 +204,8 @@ public async Task Invoke(HttpContext context)
}

// Not cached? Let's get it from the image resolver.
IByteBuffer inBuffer = null;
IByteBuffer outBuffer = null;
IManagedByteBuffer inBuffer = null;
IManagedByteBuffer outBuffer = null;
MemoryStream outStream = null;
try
{
Expand Down Expand Up @@ -266,9 +267,9 @@ public async Task Invoke(HttpContext context)
}
}

private async Task SendResponse(ImageContext imageContext, string key, DateTimeOffset lastModified, IByteBuffer buffer)
private async Task SendResponse(ImageContext imageContext, string key, DateTimeOffset lastModified, IManagedByteBuffer buffer)
{
imageContext.ComprehendRequestHeaders(lastModified, buffer.Length);
imageContext.ComprehendRequestHeaders(lastModified, buffer.Memory.Length);

string contentType = FormatHelpers.GetContentType(this.options.Configuration, key);

Expand All @@ -282,7 +283,7 @@ private async Task SendResponse(ImageContext imageContext, string key, DateTimeO
}

this.logger.LogImageServed(imageContext.GetDisplayUrl(), key);
await imageContext.SendAsync(contentType, buffer, buffer.Length);
await imageContext.SendAsync(contentType, buffer, buffer.Memory.Length);

break;

Expand All @@ -300,5 +301,10 @@ private async Task SendResponse(ImageContext imageContext, string key, DateTimeO
throw exception;
}
}

private static string GetUri(HttpContext context, IDictionary<string, string> commands)
{
return $"{context.Request.Host.ToString().ToLowerInvariant()}/{context.Request.PathBase.ToString().ToLowerInvariant()}/{context.Request.Path}{QueryString.Create(commands)}";
}
}
}
3 changes: 2 additions & 1 deletion src/ImageSharp.Web/Resolvers/IImageResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Resolvers
{
Expand Down Expand Up @@ -39,6 +40,6 @@ public interface IImageResolver
/// </summary>
/// <param name="context">The current HTTP request context.</param>
/// <returns>The <see cref="T:Task{IByteBuffer}"/>.</returns>
Task<IByteBuffer> ResolveImageAsync(HttpContext context);
Task<IManagedByteBuffer> ResolveImageAsync(HttpContext context);
}
}
5 changes: 3 additions & 2 deletions src/ImageSharp.Web/Resolvers/PhysicalFileSystemResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using SixLabors.ImageSharp.Web.Helpers;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.ImageSharp.Web.Middleware;
using SixLabors.Memory;

namespace SixLabors.ImageSharp.Web.Resolvers
{
Expand Down Expand Up @@ -67,11 +68,11 @@ public Task<bool> IsValidRequestAsync(HttpContext context)
}

/// <inheritdoc/>
public async Task<IByteBuffer> ResolveImageAsync(HttpContext context)
public async Task<IManagedByteBuffer> ResolveImageAsync(HttpContext context)
{
// Path has already been correctly parsed before here.
IFileInfo fileInfo = this.fileProvider.GetFileInfo(context.Request.Path.Value);
IByteBuffer buffer;
IManagedByteBuffer buffer;

// Check to see if the file exists.
if (!fileInfo.Exists)
Expand Down
8 changes: 5 additions & 3 deletions tests/ImageSharp.Web.Tests/Memory/PooledBufferManagerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SixLabors.ImageSharp.Web.Memory;
using SixLabors.Memory;
using Xunit;

namespace SixLabors.ImageSharp.Web.Tests.Memory
Expand Down Expand Up @@ -36,12 +37,13 @@ public void PooledBufferManagerThrowsWhenParamsAreInvalid(int maxLength, int max
[Theory]
[InlineData(32)]
[InlineData(512)]
[InlineData(123)]
[InlineData(PooledBufferManager.DefaultMaxLength - 1)]
public void BufferLengthIsCorrect(int size)
{
using (IByteBuffer buffer = this.manager.Allocate(size))
using (IManagedByteBuffer buffer = this.manager.Allocate(size))
{
Assert.Equal(size, buffer.Length);
Assert.Equal(size, buffer.Memory.Length);
}
}

Expand All @@ -51,7 +53,7 @@ public void BufferLengthIsCorrect(int size)
private bool CheckIsRentingPooledBuffer<T>(int length)
where T : struct
{
IByteBuffer buffer = this.manager.Allocate(length);
IManagedByteBuffer buffer = this.manager.Allocate(length);
ref byte ptrToPreviousPosition0 = ref MemoryMarshal.GetReference<byte>(buffer.Array);
buffer.Dispose();

Expand Down

0 comments on commit 79f6e50

Please sign in to comment.