public static RegisterAllocator Create() { return(new RegisterAllocator { registers = PooledArray <LocalValueRegister> .Empty(), regCount = 0 }); }
public override async Task <string> OnGetEvaluatedPropertyValueAsync(string propertyName, string evaluatedPropertyValue, IProjectProperties defaultProperties) { ActiveConfiguredObjects <ConfiguredProject>?configuredProjects = await _projectProvider.GetActiveConfiguredProjectsAsync(); if (configuredProjects == null) { return(""); } var builder = PooledArray <string> .GetInstance(capacity : configuredProjects.Objects.Length); foreach (ConfiguredProject configuredProject in configuredProjects.Objects) { ProjectProperties projectProperties = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>(); ConfigurationGeneral configuration = await projectProperties.GetConfigurationGeneralPropertiesAsync(); string?currentPlatformMoniker = (string?)await configuration.TargetPlatformIdentifier.GetValueAsync(); string?currentPlatformVersion = (string?)await configuration.TargetPlatformVersion.GetValueAsync(); Assumes.NotNull(currentPlatformMoniker); builder.Add($"{ currentPlatformMoniker }, Version={ currentPlatformVersion }"); } return(string.Join(";", builder.ToArrayAndFree())); }
public async Task <ActiveConfiguredObjects <ProjectConfiguration>?> GetActiveProjectConfigurationsAsync() { ProjectConfiguration?activeSolutionConfiguration = _services.ActiveConfiguredProjectProvider?.ActiveProjectConfiguration; if (activeSolutionConfiguration == null) { return(null); } IProjectConfigurationsService?projectConfigurationsService = _services.ProjectConfigurationsService; Assumes.Present(projectConfigurationsService); IImmutableSet <ProjectConfiguration> configurations = await projectConfigurationsService.GetKnownProjectConfigurationsAsync(); var builder = PooledArray <ProjectConfiguration> .GetInstance(); IImmutableSet <string> dimensionNames = GetDimensionNames(); foreach (ProjectConfiguration configuration in configurations) { if (IsActiveConfigurationCandidate(activeSolutionConfiguration, configuration, dimensionNames)) { builder.Add(configuration); } } Assumes.True(builder.Count > 0, "We have an active configuration that isn't one of the known configurations"); return(new ActiveConfiguredObjects <ProjectConfiguration>(builder.ToImmutableAndFree(), dimensionNames)); }
/// <summary> /// Returns the export T of the startup projects if those projects support the specified capabilities /// </summary> public ImmutableArray <T> GetExportFromDotNetStartupProjects <T>(string capabilityMatch) where T : class { #pragma warning disable RS0030 // Do not used banned APIs EnvDTE.DTE dte = ServiceProvider.GetService <EnvDTE.DTE, EnvDTE.DTE>(); #pragma warning restore RS0030 // Do not used banned APIs if (dte != null) { if (dte.Solution.SolutionBuild.StartupProjects is Array startupProjects && startupProjects.Length > 0) { #pragma warning disable RS0030 // Do not used banned APIs IVsSolution sln = ServiceProvider.GetService <IVsSolution, SVsSolution>(); #pragma warning restore RS0030 // Do not used banned APIs var results = PooledArray <T> .GetInstance(); foreach (string projectName in startupProjects) { sln.GetProjectOfUniqueName(projectName, out IVsHierarchy hier); if (hier != null && hier.IsCapabilityMatch(capabilityMatch)) { string projectPath = hier.GetProjectFilePath(); results.Add(ProjectExportProvider.GetExport <T>(projectPath)); } } return(results.ToImmutableAndFree()); } } return(ImmutableArray <T> .Empty); }
private Handlers CreateHandlers(IWorkspaceProjectContext context) { var evaluationHandlers = PooledArray <(IProjectEvaluationHandler handler, string evaluationRuleName)> .GetInstance(); var commandLineHandlers = PooledArray <ICommandLineHandler> .GetInstance(); foreach ((HandlerFactory factory, string evaluationRuleName)factory in s_handlerFactories) { IWorkspaceContextHandler handler = factory.factory(_project); handler.Initialize(context); // NOTE: Handlers can be both IEvaluationHandler and ICommandLineHandler if (handler is IProjectEvaluationHandler evaluationHandler) { evaluationHandlers.Add((evaluationHandler, factory.evaluationRuleName)); } if (handler is ICommandLineHandler commandLineHandler) { commandLineHandlers.Add(commandLineHandler); } } return(new Handlers(evaluationHandlers.ToImmutableAndFree(), commandLineHandlers.ToImmutableAndFree())); }
public StatementData(bool alwaysReturns) { AlwaysReturns = alwaysReturns; Statements = PooledArray <StatementSyntax> .Empty(); Registers = PooledArray <int> .Empty(); }
public static Dictionary <string, ResourceObject> CreateDictionary(string filePath) { using var stream = File.OpenRead(filePath); using var pooledArray = new PooledArray <byte>(2048); var reader = new Reader(stream, pooledArray.InnerArray); if (!reader.ReadAndEqual(FormatVersion())) { throw new FormatException(); } if (!reader.ReadAndEqual(MagicWord())) { throw new FormatException(); } var fileCount = reader.ReadInt32(); reader.Skip(sizeof(long)); // hash sum var utf8 = Encoding.UTF8; var dic = new Dictionary <string, ResourceObject>(fileCount); while (!reader.IsEndOfStream) { var name = reader.ReadString(reader.ReadInt32(), utf8); reader.Skip(sizeof(long)); // time stamp var len = reader.ReadInt64(); var pos = reader.StreamPosition; var res = new ResourceObject(len, pos); dic.Add(name, res); reader.Skip(res.Length); // data } return(dic); }
/// <summary> /// Returns the export T of the startup projects if those projects support the specified capabilities /// </summary> public ImmutableArray <T> GetExportFromDotNetStartupProjects <T>(string capabilityMatch) where T : class { if (_dte.Value.Solution.SolutionBuild.StartupProjects is Array { Length : > 0 } startupProjects) { var results = PooledArray <T> .GetInstance(); foreach (string projectName in startupProjects) { _solution.Value.GetProjectOfUniqueName(projectName, out IVsHierarchy hier); if (hier?.IsCapabilityMatch(capabilityMatch) == true) { string?projectPath = hier.GetProjectFilePath(); if (projectPath != null) { T?export = _projectExportProvider.GetExport <T>(projectPath); if (export != null) { results.Add(export); } } } } return(results.ToImmutableAndFree()); } return(ImmutableArray <T> .Empty); }
public ImmutableArray <string> GetFullPathsOfStartupProjects() { if (_dte.Value.Solution.SolutionBuild.StartupProjects is Array { Length : > 0 } startupProjects) { var results = PooledArray <string> .GetInstance(startupProjects.Length); foreach (string projectName in startupProjects) { _solution.Value.GetProjectOfUniqueName(projectName, out IVsHierarchy hier); string?projectPath = hier?.GetProjectFilePath(); if (projectPath != null) { results.Add(projectPath); } } return(results.ToImmutableAndFree()); } return(ImmutableArray <string> .Empty); }
public StatementData(ReadOnlySpan <StatementSyntax> statements, bool alwaysReturns = false) { AlwaysReturns = alwaysReturns; Statements = PooledArray <StatementSyntax> .GetArray(statements.Length); statements.CopyTo(Statements.Span); Registers = PooledArray <int> .Empty(); }
public StatementData(StatementSyntax statement, bool alwaysReturns = false) { AlwaysReturns = alwaysReturns; Statements = PooledArray <StatementSyntax> .GetArray(1); Statements.Span [0] = statement; Registers = PooledArray <int> .Empty(); }
public int ECS_PooledArray() { int l; using (PooledArray <int> array = PooledArray <int> .Rent(ArrSize)) { l = array.array.Length; } return(l); }
/// <summary> /// <see cref="ArrayPool{T}"/> から借り出した配列を返す。 /// 頻繁に呼んでもヒープ利用量は増えない。 /// /// でも、プール管理自体が結構重いので、本当は今回みたいな「小さいオブジェクトを頻繁に作る」みたいなのには向かない。遅い。 /// /// あと、Dispose (<see cref="ArrayPool{T}.Return(T[], bool)"/> を忘れるとメモリリーク。 /// </summary> private static PooledArray <byte> B(byte x) { var a = new PooledArray <byte>(8); for (int i = 0; i < 8; i++) { a[i] = x; } return(a); }
// This callback holds the reference to PooledArray, so it must be decremented to free it (eventually) after it's consumed. private Task OnReceiveBinary(RGWebSocket rgws, PooledArray msg) { msg.IncRef(); // bump the refcount since we aren't done with it yet, and RGWebSocket can decrement it without freeing the buffer _incomingMessages.Add(new wsMessage() { stringMsg = string.Empty, binMsg = msg }); _logger($"UWS Recv {msg.Length} bytes bin", 3); return(Task.CompletedTask); }
// Returns false if data could not be sent (eg. you aren't connected or in a good status to do so) public bool Send(PooledArray msg) { if (_status == Status.Connected && _rgws != null && _rgws.ReadyToSend) { _rgws.Send(msg); _logger($"UWS Sent {msg.Length} bytes", 3); return(true); } return(false); }
public byte[] GetPooledArray(int size) { var pooledArray = new PooledArray(size); var random = new Random(); random.NextBytes(pooledArray.Array); HttpContext.Response.RegisterForDispose(pooledArray); return(pooledArray.Array); }
public StatementData(StatementSyntax statement, ReadOnlySpan <int> registers, bool alwaysReturns = false) { AlwaysReturns = alwaysReturns; Statements = PooledArray <StatementSyntax> .GetArray(1); Statements.Span [0] = statement; Registers = PooledArray <int> .GetArray(registers.Length); registers.CopyTo(Registers.Span); }
public BMFontInfo Parse(ReadOnlySpan <char> text) { genInfo = new BMFontGenerationInfo(); commonInfo = new BMFontCommonInfo(); charData = new Dictionary <RehashedValue <int>, BMFontCharacterData> (); kernPairs = new Dictionary <RehashedValue <long>, BMFontKerningData> (); parsedGenInfo = false; parsedCommonInfo = false; parsedCharsTag = false; parsedKerningsTag = false; pages = null; pagesParsed.Dispose(); pagesParsed = PooledArray <bool> .Empty(); int lineEnd; int lineCount = 1; while ((lineEnd = text.IndexOf('\n')) != -1 || (lineEnd = text.Length) != 0) { ReadOnlySpan <char> line; if (lineEnd != 0 && text [lineEnd - 1] == '\r') { line = text.Slice(0, lineEnd - 1); } else { line = text.Slice(0, lineEnd); } Process(line, lineCount); text = text.Slice(lineEnd + 1); lineCount++; } var ret = new BMFontInfo(charData, kernPairs, pages, genInfo, commonInfo); pagesParsed.Dispose(); charData = null; pages = null; kernPairs = null; genInfo = new BMFontGenerationInfo(); commonInfo = new BMFontCommonInfo(); return(ret); }
public Task <IReadOnlyCollection <IPageMetadata> > GetPagesAsync() { var builder = PooledArray <IPageMetadata> .GetInstance(capacity : 6); builder.Add(XSharpProjectDesignerPage.General); builder.Add(XSharpProjectDesignerPage.Language); builder.Add(XSharpProjectDesignerPage.Dialect); builder.Add(XSharpProjectDesignerPage.Build); builder.Add(XSharpProjectDesignerPage.BuildEvents); builder.Add(XSharpProjectDesignerPage.Debug); return(Task.FromResult <IReadOnlyCollection <IPageMetadata> >(builder.ToImmutableAndFree())); }
static private ConcurrentDictionary <long, int> liveArrays = new ConcurrentDictionary <long, int>(); // this counts the number that are allocated but not yet returned (if this grows, there's a leak!) static public PooledArray BorrowFromPool(int length) { // Round up to powers of two, so we don't have too many different categories, but none smaller than 128 bytes. int roundedLength = 128; while (roundedLength < length) { roundedLength *= 2; } // Create the list the first time we need it List <PooledArray> poolList; if (!pooledArrays.TryGetValue(roundedLength, out poolList)) { poolList = new List <PooledArray>(); if (!pooledArrays.TryAdd(roundedLength, poolList)) { pooledArrays.TryGetValue(roundedLength, out poolList); // always succeeds } liveArrays.TryAdd(roundedLength, 0); } lock (poolList) // ConcurrentQueue has memory leaks--do not change List to that just to avoid the lock. { if (poolList.Count == 0) { poolList.Add(new PooledArray(roundedLength)); // create a new record if we're ever out of them } PooledArray ret = poolList[poolList.Count - 1]; ret.Length = length; ret.IncRef(); poolList.RemoveAt(poolList.Count - 1); for (;;) // atomic increment is complicated due to the concurrent dictionary { int value = liveArrays[roundedLength]; // only fetch once, otherwise race conditions if (liveArrays.TryUpdate(roundedLength, value + 1, value)) { //***** I don't think 10,000 of anything is really a very conservative value, but if this trips and you DON'T have a leak, bump it up. if (value > 10000) { throw new Exception($"Leak detected in PooledArray. {value} buffers live of size {length}"); } break; } } return(ret); } }
internal static string MangleStaticVariable([DisallowNull] ESIR_StaticVariable staticVar) { const string prefix = "StaticVar_"; var enc = ES_Encodings.Identifier; var varName = staticVar.Name; var prefixLen = enc.GetByteCount(prefix); using var chars = PooledArray <byte> .GetArray(prefixLen + varName.Length); var writtenPrefixLen = enc.GetBytes(prefix, chars); Debug.Assert(writtenPrefixLen == prefixLen); varName.Span.CopyTo(chars.Span [prefixLen..]);
// Thread-friendly way to send any message to the remote client. // Note, this does pin the incoming msg until it's sent, which is why it's pooled. public void Send(PooledArray msg) { if (msg == null) { _lastError = $"{_displayId} Send byte[] is null"; _logger(_lastError, 0); } else if (ReadyToSend) { SendInternal(new QueuedSendMsg() { textMsg = string.Empty, binMsg = msg, enqueuedTick = DateTime.UtcNow.Ticks }); } }
public void NotSame() { PooledArray <int> arr1 = PooledArray <int> .Rent(10); PooledArray <int> arr2 = PooledArray <int> .Rent(10); Assert.NotEqual(arr1.array.GetHashCode(), arr2.array.GetHashCode()); arr1.Dispose(); PooledArray <int> arr3 = PooledArray <int> .Rent(10); Assert.NotEqual(arr2.array.GetHashCode(), arr3.array.GetHashCode()); arr2.Dispose(); arr3.Dispose(); }
public void RentReturnRent() { PooledArray <int> arr1 = PooledArray <int> .Rent(10); int hash = arr1.GetHashCode(); arr1.Dispose(); PooledArray <int> arr2 = PooledArray <int> .Rent(10); int hash2 = arr2.GetHashCode(); Assert.Equal(hash, hash2); arr2.Dispose(); }
public override async Task <string> OnGetEvaluatedPropertyValueAsync(string evaluatedPropertyValue, IProjectProperties defaultProperties) { ActiveConfiguredObjects <ConfiguredProject> configuredProjects = await _projectProvider.GetActiveConfiguredProjectsAsync(); var builder = PooledArray <string> .GetInstance(); foreach (ConfiguredProject configuredProject in configuredProjects.Objects) { ProjectProperties projectProperties = configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>(); ConfigurationGeneral configuration = await projectProperties.GetConfigurationGeneralPropertiesAsync(); string currentTargetFrameworkMoniker = (string)await configuration.TargetFrameworkMoniker.GetValueAsync(); builder.Add(currentTargetFrameworkMoniker); } return(string.Join(";", builder.ToArrayAndFree())); }
/// <summary> /// Gets the project configuration dimension and values represented by this provider for the given unconfigured project. /// </summary> /// <param name="project">Unconfigured project.</param> /// <returns>Collection of key/value pairs for the current values for the configuration dimensions of this provider for given project.</returns> /// <remarks> /// From <see cref="IProjectConfigurationDimensionsProvider"/>. /// The interface expects a collection of key/value pairs containing one or more dimensions along with the values for each /// dimension. In this implementation each provider is representing a single dimension with one or more values. /// </remarks> public virtual async Task <IEnumerable <KeyValuePair <string, IEnumerable <string> > > > GetProjectConfigurationDimensionsAsync(UnconfiguredProject project) { Requires.NotNull(project, nameof(project)); ImmutableArray <string> values = await GetOrderedPropertyValuesAsync(project); if (values.IsEmpty) { return(ImmutableArray <KeyValuePair <string, IEnumerable <string> > > .Empty); } else { var dimensionValues = PooledArray <KeyValuePair <string, IEnumerable <string> > > .GetInstance(); dimensionValues.Add(new KeyValuePair <string, IEnumerable <string> >(DimensionName, values)); return(dimensionValues.ToImmutableAndFree()); } }
/// <summary> /// Gets the defaults values for project configuration dimensions for the given unconfigured project. /// </summary> /// <param name="project">Unconfigured project.</param> /// <returns>Collection of key/value pairs for the defaults values for the configuration dimensions of this provider for given project.</returns> /// <remarks> /// From <see cref="IProjectConfigurationDimensionsProvider"/>. /// The interface expects a collection of key/value pairs containing one or more dimensions along with a single values for each /// dimension. In this implementation each provider is representing a single dimension. /// </remarks> public virtual async Task <IEnumerable <KeyValuePair <string, string> > > GetDefaultValuesForDimensionsAsync(UnconfiguredProject project) { Requires.NotNull(project, nameof(project)); ImmutableArray <string> values = await GetOrderedPropertyValuesAsync(project); if (values.IsEmpty) { return(ImmutableArray <KeyValuePair <string, string> > .Empty); } else { // First value is the default one. var defaultValues = PooledArray <KeyValuePair <string, string> > .GetInstance(); defaultValues.Add(new KeyValuePair <string, string>(DimensionName, values.First())); return(defaultValues.ToImmutableAndFree()); } }
private static ImmutableArray <ProjectItemElement> GetItemElements(Project project, ImmutableArray <string> includes) { var elements = PooledArray <ProjectItemElement> .GetInstance(); foreach (string include in includes) { // GetItemsByEvaluatedInclude is efficient and uses a MultiDictionary underneath. // It uses this: new MultiDictionary<string, ProjectItem>(StringComparer.OrdinalIgnoreCase); ProjectItem item = project.GetItemsByEvaluatedInclude(include).FirstOrDefault(); // We only care about adding one item associated with the evaluated include. if (item?.Xml is ProjectItemElement element && !item.IsImported) { elements.Add(element); } } return(elements.ToImmutableAndFree()); }
public void SwitchAllocate2_2(int size) { var allocSizeMax = 128 * 1024; // 1MByte最大っぽいので控えめに128KByte if (size > allocSizeMax) { throw new ArgumentException(); } // 自作クラスで ArrayPool を管理 using var bytes = new PooledArray <byte>(size); for (var i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)(i % 0xff); } var answer = Enumerable.Range(0, size).Select(x => x % 0xff); bytes.RoSpan.ToArray().Should().BeEquivalentTo(answer); }
private ImmutableArray <string> CalculateBuiltInImplicitlyActiveDimensions() { var implicitlyActiveDimensions = PooledArray <string> .GetInstance(); foreach (Lazy <IProjectConfigurationDimensionsProvider, IConfigurationDimensionDescriptionMetadataView> provider in DimensionProviders) { for (int i = 0; i < provider.Metadata.IsVariantDimension.Length; i++) { if (provider.Metadata.IsVariantDimension[i]) { if (!implicitlyActiveDimensions.Contains(provider.Metadata.DimensionName[i], StringComparers.ConfigurationDimensionNames)) { implicitlyActiveDimensions.Add(provider.Metadata.DimensionName[i]); } } } } return(implicitlyActiveDimensions.ToImmutableAndFree()); }