diff --git a/Readme.md b/Readme.md index 6a9fb92..66ce691 100644 --- a/Readme.md +++ b/Readme.md @@ -26,7 +26,7 @@ This package currently supports: - **SignalR Extensions** for adding simple SignalR or distributed SignalR backed with Redis. - **OpenTelemetry**: Metrics, traces, and logs with Prometheus support. - **Health Checks**: Startup validation and endpoints for monitoring. -- Various **Extensions and Utilities**, including enumerable, string, and queryable extensions. +- Various **Extensions and Utilities**, including enumerable, string, dictionary and queryable extensions. ## Prerequisites @@ -613,6 +613,8 @@ This package includes various extensions and utilities to aid development: - **Enumerable Extensions:** Additional LINQ methods for collections. - **Host Environment Extensions:** Methods to simplify environment checks (e.g., `IsLocal()`, `IsQa()`). - **Queryable Extensions:** Extensions for IQueryable, such as conditional `WhereIf`. +- **Dictionary Extensions:** Utility methods for dictionary manipulation in a performant way like `GetOrAdd` and + `TryUpdate`. - **String Extensions:** Utility methods for string manipulation. - **Time Zone Extensions:** Methods to handle default time zones within your application. Use `.MapDefaultTimeZone()`, which diff --git a/src/SharedKernel/Extensions/DictionaryExtensions.cs b/src/SharedKernel/Extensions/DictionaryExtensions.cs new file mode 100644 index 0000000..4b0d920 --- /dev/null +++ b/src/SharedKernel/Extensions/DictionaryExtensions.cs @@ -0,0 +1,34 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace SharedKernel.Extensions; + +public static class DictionaryExtensions +{ + public static TValue? GetOrAdd(this Dictionary dict, TKey key, TValue? value) + where TKey : notnull + { + ref var val = ref CollectionsMarshal.GetValueRefOrAddDefault(dict, key, out var exists); + + if (exists) + { + return val; + } + + val = value; + return val; + } + + public static bool TryUpdate(this Dictionary dict, TKey key, TValue value) + where TKey : notnull + { + ref var val = ref CollectionsMarshal.GetValueRefOrNullRef(dict, key); + if (Unsafe.IsNullRef(ref val)) + { + return false; + } + + val = value; + return true; + } +} \ No newline at end of file diff --git a/src/SharedKernel/SharedKernel.csproj b/src/SharedKernel/SharedKernel.csproj index e6a3629..7111913 100644 --- a/src/SharedKernel/SharedKernel.csproj +++ b/src/SharedKernel/SharedKernel.csproj @@ -8,13 +8,13 @@ Readme.md Pandatech MIT - 1.1.1 + 1.1.2 Pandatech.SharedKernel Pandatech Shared Kernel Library Pandatech, shared kernel, library, OpenAPI, Swagger, utilities, scalar Pandatech.SharedKernel provides centralized configurations, utilities, and extensions for ASP.NET Core projects. For more information refere to readme.md document. https://github.com/PandaTechAM/be-lib-sharedkernel - Added signal r incomming and outgoing message logging + Added dictinory extensions