Here are the examples of the csharp api System.Collections.Generic.HashSet.Add(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3552 Examples
19
Source : CachingAsyncInterceptor.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
private (List<string> cacheKeys, DateTime expireDt) ProcessEvictBefore(IInvocation invocation, CachingEvictAttribute attribute)
{
var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget;
var needRemovedKeys = new HashSet<string>();
if (!string.IsNullOrEmpty(attribute.CacheKey))
{
needRemovedKeys.Add(attribute.CacheKey);
}
if (attribute.CacheKeys?.Length > 0)
{
needRemovedKeys.UnionWith(attribute.CacheKeys);
}
if (!string.IsNullOrWhiteSpace(attribute.CacheKeyPrefix))
{
var cacheKeys = _keyGenerator.GetCacheKeys(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix);
needRemovedKeys.UnionWith(cacheKeys);
}
var keyExpireSeconds = _cacheProvider.CacheOptions.PollyTimeoutSeconds + 1;
_cacheProvider.KeyExpireAsync(needRemovedKeys, keyExpireSeconds).GetAwaiter().GetResult();
return (needRemovedKeys.ToList(), DateTime.Now.AddSeconds(keyExpireSeconds));
}
19
Source : GuidObjectFolder.cs
with MIT License
from Alprog
with MIT License
from Alprog
private HashSet<string> GetCurrentFileSet(string folderPath)
{
var set = new HashSet<string>();
foreach (var filePath in Directory.GetFiles(folderPath, "*.sav", SearchOption.AllDirectories))
{
set.Add(filePath.Replace('\\', '/').ToLowerInvariant());
}
return set;
}
19
Source : PolicyHelper.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static List<string> GetRolesWithAccess(XacmlPolicy policy)
{
HashSet<string> roleCodes = new HashSet<string>();
foreach (XacmlRule rule in policy.Rules)
{
if (rule.Effect.Equals(XacmlEffectType.Permit) && rule.Target != null)
{
foreach (XacmlAnyOf anyOf in rule.Target.AnyOf)
{
foreach (XacmlAllOf allOf in anyOf.AllOf)
{
foreach (XacmlMatch xacmlMatch in allOf.Matches)
{
if (xacmlMatch.AttributeDesignator.AttributeId.Equals(AltinnXacmlConstants.MatchAttributeIdentifiers.RoleAttribute))
{
roleCodes.Add(xacmlMatch.AttributeValue.Value);
}
}
}
}
}
}
return roleCodes.ToList();
}
19
Source : JsonSchemaAnalyzer.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
protected bool IsValidSimpleContentRestriction(JsonSchema schema)
{
if (!HreplacedingleAllOf(schema))
{
return false;
}
var allOf = schema.GetKeyword<AllOfKeyword>();
var baseReferenceSchemas = allOf.Schemas.Where(s => s.HasKeyword<RefKeyword>()).ToList();
if (baseReferenceSchemas.Count != 1)
{
return false;
}
var baseReferenceSchema = baseReferenceSchemas[0];
var baseSchema = FollowReference(baseReferenceSchema.GetKeyword<RefKeyword>());
// Make sure base is valid for SimpleContent restriction
if (!IsValidSimpleContentExtension(baseSchema) && !IsValidSimpleContentRestriction(baseSchema))
{
return false;
}
var propertiesSchemas = allOf.Schemas.Where(s => s.HasKeyword<PropertiesKeyword>()).ToList();
// Don't allow extra subschemas not used in the pattern
if (propertiesSchemas.Count + 1 != allOf.Schemas.Count)
{
return false;
}
// All restriction properties must match properties from base type(s)
var basePropertyNames = new HashSet<string>();
while (!IsValidSimpleType(baseSchema))
{
foreach (var (propertyName, _) in FindSimpleContentProperties(baseSchema))
{
basePropertyNames.Add(propertyName);
}
if (!baseSchema.TryGetKeyword(out AllOfKeyword baseAllOf))
{
break;
}
var baseRefSchema = baseAllOf.Schemas
.SingleOrDefault(s => s.HasKeyword<RefKeyword>())
?.GetKeyword<RefKeyword>();
if (baseRefSchema == null)
{
break;
}
baseSchema = FollowReference(baseRefSchema);
}
var hasValueProperty = false;
foreach (var (propertyName, propertySchema) in propertiesSchemas.SelectMany(ps => ps.GetKeyword<PropertiesKeyword>().Properties.Select(prop => (prop.Key, prop.Value))))
{
if (!basePropertyNames.Contains(propertyName))
{
// Can't restrict a property that is not present in base types, this is not a valid simple content restriction
return false;
}
var propertyTargetSchema = FollowReferencesIfAny(propertySchema);
if (!hasValueProperty && propertyName == "value")
{
// "value" property
hasValueProperty = true;
// "value" property cannot be an attribute
if (propertySchema.HasKeyword<XsdAttributeKeyword>())
{
return false;
}
}
else
{
// restriction property must be an attribute
if (!propertySchema.HasKeyword<XsdAttributeKeyword>())
{
return false;
}
}
if (!IsValidSimpleTypeOrSimpleTypeRestriction(propertyTargetSchema) && !IsPlainRestrictionSchema(propertyTargetSchema))
{
return false;
}
}
return hasValueProperty;
}
19
Source : SyncBookmarkJob.cs
with GNU General Public License v3.0
from Amazing-Favorites
with GNU General Public License v3.0
from Amazing-Favorites
public async ValueTask StartAsync()
{
await _bookmarksApi.OnRemoved.AddListener(async (s, info) =>
{
var nodes = GetAllChildren(new[] { info.Node });
foreach (var bookmarkTreeNode in nodes)
{
await _bkManager.DeleteAsync(bookmarkTreeNode.Url);
}
_logger.LogInformation("Bookmark data reload since item removed");
});
await _bookmarksApi.OnChanged.AddListener(async (s, info) =>
{
if (!string.IsNullOrWhiteSpace(info.Url) &&
!string.IsNullOrWhiteSpace(info.replacedle))
{
await _bkManager.UpdatereplacedleAsync(info.Url, info.replacedle);
}
_logger.LogInformation("Bookmark data reload since item changed");
});
await _bookmarksApi.OnCreated.AddListener(async (s, node) =>
{
if (!string.IsNullOrWhiteSpace(node.Url) &&
!string.IsNullOrWhiteSpace(node.replacedle))
{
var tags = new HashSet<string>();
var nodes = _bookmarksApi.GetAllParentAsync(node.ParentId);
await foreach (var parentNode in nodes)
{
if (!string.IsNullOrWhiteSpace(parentNode.replacedle)
&& !Consts.IsReservedBookmarkFolder(parentNode.replacedle))
{
tags.Add(parentNode.replacedle);
}
}
await _bkManager.AppendBookmarksAsync(new[] {new BookmarkNode(node)
{
Tags = tags.ToList()
}});
}
_logger.LogInformation("Bookmark data reload since item added");
});
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1));
var all = await GetAllBookmarkAsync();
_logger.LogInformation("Found {Count} bookmarks, try to load them", all.Count);
// make init order look like bookmarks tree
await _bkManager.AppendBookmarksAsync(all.OrderByDescending(x => x.DateAdded));
});
}
19
Source : IndexedBkManager.cs
with GNU General Public License v3.0
from Amazing-Favorites
with GNU General Public License v3.0
from Amazing-Favorites
public async Task<bool> AppendTagAsync(string url, params string[]? tags)
{
if (tags == null)
{
return false;
}
foreach (var tag in tags)
{
if (string.IsNullOrWhiteSpace(tag))
{
return false;
}
}
_logger.LogInformation("New tags {Tag} add to {Url}", tags, url);
var bk = await _bkRepo.GetAsync(url);
if (bk != null)
{
var newTagList = tags.Select(x => x.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToArray();
var tagList = bk.Tags ?? new List<string>();
var set = new HashSet<string>(tagList);
var oldTagCount = tagList.Count;
foreach (var tag in newTagList)
{
set.Add(tag);
}
tagList = set.ToList();
tagList.Sort();
bk.Tags = tagList;
if (oldTagCount == tagList.Count)
{
return false;
}
foreach (var tag in newTagList)
{
await AppendTagsAsync(tag);
}
await _bkRepo.UpsertAsync(bk);
await UpdateMetadataAsync();
_logger.LogInformation("Tags {Tag} added for {Url}", newTagList, url);
}
return true;
}
19
Source : ModSorter.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private static List<string> TopologicalSort(HashSet<string> nodes, HashSet<Edge> edges)
{
var sortedList = new List<string>();
var nodesWithNoEdges = new HashSet<string>(nodes.Where(node => edges.All(edge => edge.Second.Equals(node) == false)));
while (nodesWithNoEdges.Any())
{
var firstNode = nodesWithNoEdges.First();
nodesWithNoEdges.Remove(firstNode);
sortedList.Add(firstNode);
foreach (var edge in edges.Where(e => e.First.Equals(firstNode)).ToList())
{
var secondNode = edge.Second;
edges.Remove(edge);
if (edges.All(mEdge => mEdge.Second.Equals(secondNode) == false))
{
nodesWithNoEdges.Add(secondNode);
}
}
}
return edges.Any() ? null : sortedList;
}
19
Source : InstituteAccessServer.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public override void Load(object obj)
{
if (!(obj is Dictionary<string, object> obj2))
throw new eduJSON.InvalidParameterTypeException(nameof(obj), typeof(Dictionary<string, object>), obj.GetType());
base.Load(obj);
// Set display name.
eduJSON.Parser.GetDictionary(obj2, "display_name", LocalizedDisplayNames);
// Set keyword list.
LocalizedKeywordSets.Clear();
var keywordList = new Dictionary<string, string>();
if (eduJSON.Parser.GetDictionary(obj2, "keyword_list", keywordList))
foreach (var keywords in keywordList)
{
var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var keyword in keywords.Value.Split())
hash.Add(keyword);
LocalizedKeywordSets.Add(keywords.Key, hash);
}
}
19
Source : Organization.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public virtual void Load(object obj)
{
if (!(obj is Dictionary<string, object> obj2))
throw new eduJSON.InvalidParameterTypeException(nameof(obj), typeof(Dictionary<string, object>), obj.GetType());
// Set organization identifier.
Id = eduJSON.Parser.GetValue<string>(obj2, "org_id");
// Set secure internet home server base URI.
SecureInternetBase = new Uri(eduJSON.Parser.GetValue<string>(obj2, "secure_internet_home"));
// Set display name.
eduJSON.Parser.GetDictionary(obj2, "display_name", LocalizedDisplayNames);
// Set keyword list.
LocalizedKeywordSets.Clear();
var keywordList = new Dictionary<string, string>();
if (eduJSON.Parser.GetDictionary(obj2, "keyword_list", keywordList))
foreach (var keywords in keywordList)
{
var hash = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var keyword in keywords.Value.Split())
hash.Add(keyword);
LocalizedKeywordSets.Add(keywords.Key, hash);
}
}
19
Source : Map.cs
with MIT License
from amidos2006
with MIT License
from amidos2006
public List<int[]> getDungeonPath(Cell from, Cell to, int accessLevel){
List<TreeNode> queue = new List<TreeNode>();
queue.Add(new TreeNode(from.x, from.y, null, to.x, to.y));
HashSet<string> visited = new HashSet<string>();
while (queue.Count > 0)
{
queue.Sort();
TreeNode current = queue[0];
queue.Remove(current);
if (current.x == to.x && current.y == to.y)
{
return current.getPath();
}
if (from.parent != null && current.x == from.parent.x && current.y == from.parent.y){
continue;
}
if (visited.Contains(current.x + "," + current.y))
{
continue;
}
if (!this.usedSpaces.ContainsKey(current.x + "," + current.y)){
continue;
}
if(this.usedSpaces[current.x + "," + current.y].type == CellType.Connection){
continue;
}
if (this.usedSpaces[current.x + "," + current.y].node.accessLevel != accessLevel)
{
continue;
}
visited.Add(current.x + "," + current.y);
foreach (int[] dir in directions)
{
if(this.usedSpaces[current.x + "," + current.y].getDoor(-dir[0], -dir[1]) != 0){
int newX = current.x + dir[0];
int newY = current.y + dir[1];
queue.Add(new TreeNode(newX, newY, current, to.x, to.y));
}
}
}
return new List<int[]>();
}
19
Source : Map.cs
with MIT License
from amidos2006
with MIT License
from amidos2006
private List<int[]> getConnectionPoints(Cell from, Cell to, int maxIterations){
int accessLevel = Math.Min(from.node.accessLevel, to.node.accessLevel);
List<TreeNode> queue = new List<TreeNode>();
foreach (int[] dir in directions)
{
int newX = from.x + dir[0];
int newY = from.y + dir[1];
queue.Add(new TreeNode(newX, newY, new TreeNode(from.x, from.y, null, to.x, to.y), to.x, to.y));
}
HashSet<string> visited = new HashSet<string>();
visited.Add(from.x + "," + from.y);
while (queue.Count > 0)
{
queue.Sort();
TreeNode current = queue[0];
queue.Remove(current);
if (current.x == to.x && current.y == to.y){
return current.getPath();
}
if(this.usedSpaces.ContainsKey(current.x + "," + current.y) &&
this.usedSpaces[current.x + "," + current.y].type == CellType.Normal){
if(this.usedSpaces[current.x + "," + current.y].node.accessLevel > accessLevel){
continue;
}
List<int[]> dungeonPath = this.getDungeonPath(this.usedSpaces[current.x + "," + current.y], to, accessLevel);
if(dungeonPath.Count > 0){
return current.getPath();
}
}
if(from.parent != null && current.x == from.parent.x && current.y == from.parent.y){
continue;
}
if (visited.Contains(current.x + "," + current.y)){
continue;
}
if(visited.Count > maxIterations){
return new List<int[]>();
}
visited.Add(current.x + "," + current.y);
foreach (int[] dir in directions)
{
int newX = current.x + dir[0];
int newY = current.y + dir[1];
queue.Add(new TreeNode(newX, newY, current, to.x, to.y));
}
}
return new List<int[]>();
}
19
Source : SceneEditorViewFactory.cs
with MIT License
from Aminator
with MIT License
from Aminator
private static async Task LoadreplacedemblyAsync(IStorageFolder folder, string replacedemblyName)
{
try
{
StorageFile replacedemblyFile = await folder.GetFileAsync(Path.Combine(@"bin\Debug\netstandard2.0", replacedemblyName + ".dll"));
string replacedemblyCopyPath = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, replacedemblyFile.Name);
if (!dynamicallyLoadedreplacedemblyPaths.Contains(replacedemblyCopyPath))
{
dynamicallyLoadedreplacedemblyPaths.Add(replacedemblyCopyPath);
StorageFile replacedemblyFileCopy = await replacedemblyFile.CopyAsync(ApplicationData.Current.TemporaryFolder, replacedemblyFile.Name, NameCollisionOption.ReplaceExisting);
replacedembly.LoadFrom(replacedemblyFileCopy.Path);
}
}
catch
{
}
}
19
Source : SfuConferenceInfoUpdateAggregator.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public void Append(SfuConferenceInfoUpdate update)
{
foreach (var participant in update.RemovedParticipants)
{
_participantToRoom.Remove(participant);
_removedParticipants.Add(participant);
}
foreach (var (participant, roomId) in update.ParticipantToRoom)
{
_participantToRoom[participant] = roomId;
_removedParticipants.Remove(participant);
}
foreach (var (participant, permission) in update.ParticipantPermissions)
{
_permissions[participant] = permission;
}
}
19
Source : Util.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
public static IList<C.Function> find_function_with_input(C.Function root, C.Function inputFunction) {
var list = new List<C.Function>();
root = root.RootFunction;
inputFunction = inputFunction.RootFunction;
var root_uid = root.Uid;
var stack = new Stack<object>();
stack.Push(root);
var visited_uids = new HashSet<string>();
while (stack.Count > 0) {
var popped = stack.Pop();
if (popped is C.Variable) {
var v = (C.Variable)popped;
if (v.IsOutput) {
stack.Push(v.Owner);
}
continue;
}
if (popped is IList<C.Variable>) {
foreach (var pv in (IList<C.Variable>)popped) {
stack.Push(pv);
}
continue;
}
var node = (C.Function)popped;
if (visited_uids.Contains(node.Uid)) { continue; }
node = node.RootFunction;
stack.Push(node.RootFunction.Inputs);
for (int i = 0; i < node.Inputs.Count; i++) {
var input = node.Inputs[i];
if (input.Uid == inputFunction.Output.Uid) {
list.Add(node);
}
}
visited_uids.Add(node.Uid);
}
return list;
}
19
Source : Util.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
public static List<string> detailed_summary(C.Function root, bool print = true) {
// This is based on the C.logging.graph.plot, but without the actual plotting part
// Walks through every node of the graph starting at ``root``, creates a network graph, and returns a network description
var model = new List<string>();
root = root.RootFunction;
var root_uid = root.Uid;
var stack = new Stack<object>();
stack.Push(root);
var visited_uids = new HashSet<string>();
while (stack.Count > 0) {
var popped = stack.Pop();
if (popped is C.Variable) {
var v = (C.Variable)popped;
if (v.IsOutput) {
stack.Push(v.Owner);
}
else if (v.IsInput) {
model.Add(v.replacedtring());
}
continue;
}
if (popped is IList<C.Variable>) {
foreach (var pv in (IList<C.Variable>)popped) {
stack.Push(pv);
}
continue;
}
var node = (C.Function)popped;
if (visited_uids.Contains(node.Uid)) { continue; }
node = node.RootFunction;
stack.Push(node.RootFunction.Inputs);
var line = new System.Text.StringBuilder($"{node.Name} : {node.OpName} ({node.Uid}) :");
line.Append("(");
for (int i = 0; i < node.Inputs.Count; i++) {
var input = node.Inputs[i];
if (node.IsBlock && input.IsConstant) { continue; }
line.Append(input.Uid);
if (i != (node.Inputs.Count - 1)) {
line.Append(", ");
}
}
line.Append(") -> ");
foreach (var v in node.Outputs) {
model.Add(line.ToString() + "\t" + shape_desc(v));
}
visited_uids.Add(node.Uid);
}
model.Reverse();
if (print) {
for (int i = 0; i < model.Count; i++) {
Console.WriteLine(model[i]);
}
}
return model;
}
19
Source : InMemoryDatabaseActions.cs
with Apache License 2.0
from Anapher
with Apache License 2.0
from Anapher
public virtual ValueTask<bool> SetAddAsync(string key, string value)
{
using (Lock())
{
if (!_data.TryGetValue(key, out var setObj))
_data[key] = setObj = new HashSet<string>();
var set = (HashSet<string>) setObj;
var added = set.Add(value);
return new ValueTask<bool>(added);
}
}
19
Source : UAudioManagerBaseEditor.cs
with MIT License
from anderm
with MIT License
from anderm
private void UpdateEventNames(TEvent[] EditorEvents)
{
HashSet<string> previousEventNames = new HashSet<string>();
for (int i = 0; i < EditorEvents.Length; i++)
{
if (string.IsNullOrEmpty(EditorEvents[i].name))
{
EditorEvents[i].name = "_NewEvent" + i.ToString();
}
while (previousEventNames.Contains(EditorEvents[i].name))
{
EditorEvents[i].name = "_" + EditorEvents[i].name;
}
this.eventNames[i] = EditorEvents[i].name;
previousEventNames.Add(this.eventNames[i]);
}
}
19
Source : DesignerContextMenuAddIn.cs
with GNU General Public License v3.0
from anderson-joyle
with GNU General Public License v3.0
from anderson-joyle
private StringBuilder GenerateFromTableExtension(Tables.ITableExtension selectedExtensionTable, bool addGroupBy)
{
var result = new StringBuilder();
bool first = true;
result.AppendLine(string.Format(CultureInfo.InvariantCulture, "USE {0}", BusinessDatabaseName));
result.AppendLine("GO");
result.AppendLine();
Metadata.MetaModel.AxTableExtension extension = this.MetadataProvider.TableExtensions.Read(selectedExtensionTable.Name);
var baseTableName = selectedExtensionTable.Name.Split('.').First();
var tables = this.SuperTables(baseTableName);
tableName = baseTableName;
HashSet<string> extendedFields = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var extendedField in extension.Fields)
{
extendedFields.Add(extendedField.Name);
}
if (tables.First().SaveDataPerCompany == Metadata.Core.MetaModel.NoYes.Yes)
{
result.AppendLine($"SELECT {SqlNameMangling.GetSqlTableName(tables.First().Name)}.DATAAREAID, COUNT(*) AS COUNTER");
}
else
{
result.AppendLine("SELECT COUNT(*) AS COUNTER");
}
result.AppendLine("FROM " + SqlNameMangling.GetSqlTableName(tables.First().Name));
if (tables.First().SaveDataPerCompany == Metadata.Core.MetaModel.NoYes.Yes && addGroupBy)
{
result.AppendLine($"GROUP BY {SqlNameMangling.GetSqlTableName(tables.First().Name)}.{SqlNameMangling.GetValidSqlNameForField("DATAAREAID")}");
}
return result;
}
19
Source : FileObserver.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private static void Run()
{
var addresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.Address.MapToIPv4())
.Where(x => x.ToString() != "127.0.0.1")
.ToArray();
var ip = addresses.FirstOrDefault()?.ToString() ?? "127.0.0.1";
var args = Environment.GetCommandLineArgs();
var path = RetrieveCommandLineArgument("p=", Environment.CurrentDirectory, args);
var url = RetrieveCommandLineArgument("u=", $"http://{ip}:8000", args);
var autoDiscoveryPort = RetrieveCommandLineArgument("a=", "15000", args);
try
{
Directory.GetDirectories(path);
}
catch
{
Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT PATH TO PROJECT DIRECTORY AS 'P={PATH}' ARGUMENT.");
Console.ReadKey();
return;
}
foreach (var addr in url.Split(new char[] { ',', ';' }))
{
if (!Uri.IsWellFormedUriString(addr, UriKind.Absolute))
{
Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT DEVICE URL AS 'U={DEVICE_URL}' OR AS 'U={DEVICE_URL,DEVICE_URL2,...}' ARGUMENT.");
Console.ReadKey();
return;
}
_addresses.Add(addr);
}
UdpReceiver receiver = null;
try
{
receiver = new UdpReceiver(int.Parse(autoDiscoveryPort));
receiver.Received += (addressMsg) =>
{
//TODO: pick needed address
var address = addressMsg.Split(';').FirstOrDefault();
if (address != null)
{
if (!_addresses.Contains(address))
{
Console.WriteLine($"ADDRESS IS DETECTED: {address}");
_addresses.Add(address);
}
}
};
receiver.StartAsync();
}
catch
{
Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT AUTO DISCOVERY RECEIVER PORT AS 'A={PORT}' ARGUMENT.");
Console.ReadKey();
return;
}
Console.WriteLine($"\n\n> HOTRELOADER STARTED AT {DateTime.Now}");
Console.WriteLine($"\n> PATH: {path}");
Console.WriteLine($"\n> AUTO DISCOVERY PORT: {autoDiscoveryPort}");
foreach (var addr in _addresses)
{
Console.WriteLine($"\n> URL: {addr}\n");
}
_client = new HttpClient();
foreach (var fileExtension in _supportedFileExtensions)
{
var observer = new FileSystemWatcher
{
Path = path,
NotifyFilter = NotifyFilters.LastWrite |
NotifyFilters.Attributes |
NotifyFilters.Size |
NotifyFilters.CreationTime |
NotifyFilters.FileName,
Filter = $"*{fileExtension}",
EnableRaisingEvents = true,
IncludeSubdirectories = true
};
observer.Changed += OnFileChanged;
observer.Created += OnFileChanged;
observer.Renamed += OnFileChanged;
}
do
{
Console.WriteLine("\nPRESS \'ESC\' TO STOP.");
} while (Console.ReadKey().Key != ConsoleKey.Escape);
receiver.Stop();
}
19
Source : HotReloadClientsHolder.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private void OnMessageReceived(string addressMsg)
{
var address = addressMsg.Split(';').FirstOrDefault();
if (address != null && !_addresses.Contains(address))
{
_addresses.Add(address);
OnNewAddressAdded(address);
}
}
19
Source : CloudbleedSiteChecker.cs
with MIT License
from andrew-schofield
with MIT License
from andrew-schofield
private async Task<HashSet<string>> ExtractBreachesFromStream(Stream stream, IProgress<ProgressItem> progressIndicator)
{
var breaches = new HashSet<string>();
using (var rd = new StreamReader(stream))
{
while (true)
{
var line = await rd.ReadLineAsync();
if (line == null)
break;
if (!string.IsNullOrWhiteSpace(line))
{
breaches.Add(line.ToLower().Trim());
}
}
}
return breaches;
}
19
Source : ServerHubFlowCoordinator.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public void UpdateRoomsList()
{
Plugin.log.Info("Updating rooms list...");
_serverHubClients.ForEach(x =>
{
if (x != null)
{
x.Abort();
x.ReceivedRoomsList -= ReceivedRoomsList;
x.ServerHubException -= ServerHubException;
}
});
_serverHubClients.Clear();
_roomsList.Clear();
// Store server addresses so duplicates aren't added.
HashSet<string> serverAddresses = new HashSet<string>();
if ((RepositoryServers?.Length ?? 0) > 0)
{
for (int i = 0; i < RepositoryServers.Length; i++)
{
RepositoryServer repositoryServer = RepositoryServers[i];
string fullAddress = repositoryServer.ServerAddress + ":" + repositoryServer.ServerPort.ToString();
if (repositoryServer == null || !repositoryServer.IsValid)
continue;
if (serverAddresses.Contains(repositoryServer.ServerAddress))
continue;
serverAddresses.Add(fullAddress);
ServerHubClient client = repositoryServer.ToServerHubClient();
if (client != null)
{
client.ReceivedRoomsList += ReceivedRoomsList;
client.ServerHubException += ServerHubException;
_serverHubClients.Add(client);
}
}
}
for (int i = 0; i < Config.Instance.ServerHubIPs.Length ; i++)
{
string ip = Config.Instance.ServerHubIPs[i];
int port = 3700;
if (Config.Instance.ServerHubPorts.Length > i)
{
port = Config.Instance.ServerHubPorts[i];
}
string fullAddress = ip + ":" + port.ToString();
if (serverAddresses.Contains(fullAddress) || port < 1 || port > 65535)
continue;
serverAddresses.Add(fullAddress);
ServerHubClient client = new GameObject("ServerHubClient").AddComponent<ServerHubClient>();
client.ip = ip;
client.port = port;
client.ReceivedRoomsList += ReceivedRoomsList;
client.ServerHubException += ServerHubException;
_serverHubClients.Add(client);
}
_roomListViewController.SetRooms(null);
_roomListViewController.SetServerHubsCount(0, _serverHubClients.Count);
_roomListViewController.SetRefreshButtonState(false);
_serverHubClients.ForEach(x => x.GetRooms());
Plugin.log.Info("Requested rooms lists from ServerHubs...");
}
19
Source : FakeObservableConsul.cs
with MIT License
from andyalm
with MIT License
from andyalm
public IObservable<ServiceObservation> ObserveService(string serviceName)
{
ServiceObservations = new Subject<ServiceObservation>();
ObservingServices.Add(serviceName);
return ServiceObservations;
}
19
Source : FakeObservableConsul.cs
with MIT License
from andyalm
with MIT License
from andyalm
public IObservable<KeyObservation> ObserveKey(string key)
{
KeyObservations = new Subject<KeyObservation>();
ObservingKeys.Add(key);
return KeyObservations;
}
19
Source : FakeObservableConsul.cs
with MIT License
from andyalm
with MIT License
from andyalm
public IObservable<KeyRecursiveObservation> ObserveKeyRecursive(string prefix)
{
KeyRecursiveObservations = new Subject<KeyRecursiveObservation>();
ObservingKeyPrefixes.Add(prefix);
return KeyRecursiveObservations;
}
19
Source : SourceMap.cs
with MIT License
from AngleSharp
with MIT License
from AngleSharp
public void MarkAsMatched(in AttributeComparisonSource source)
{
_matched.Add(source.Attribute.Name);
}
19
Source : SPOIndex.cs
with MIT License
from angshuman
with MIT License
from angshuman
public JObject ToJson(string id, HashSet<string> seen = null)
{
if (seen == null) {
seen = new HashSet<string>();
}
var po = GetSubjectGroupings(id);
var rsp = new JObject { [Constants.ID] = id };
if (!po.Any()) {
return rsp;
}
if (seen.Contains(id)) {
return rsp;
}
seen.Add(id);
foreach (var p in po) {
List<JToken> toList = null;
foreach (var o in p) {
if (o.Index == -1) {
if (o.IsID) {
var obj = ToJson(o.ToValue(), seen);
rsp[p.Key] = obj;
} else {
rsp[p.Key] = o.ToTypedJSON();
}
} else {
if (toList == null) {
toList = new List<JToken>();
}
if (o.IsID) {
var obj = ToJson(o.ToValue(), seen);
toList.Add(obj);
} else {
toList.Add(o.ToTypedJSON());
}
}
}
if (toList != null) {
rsp[p.Key] = new JArray(toList);
}
}
return rsp;
}
19
Source : TripleConverter.cs
with MIT License
from angshuman
with MIT License
from angshuman
public static JObject ToJson(string id, IGraph graph, HashSet<string> seen = null)
{
if (seen == null) {
seen = new HashSet<string>();
}
var po = graph.GetSubjectGroupings(id);
var rsp = new JObject { [Constants.ID] = id };
if (!po.Any()) {
return rsp;
}
if (seen.Contains(id)) {
return rsp;
}
seen.Add(id);
foreach (var p in po) {
var toList = new List<JToken>();
foreach (var o in p) {
if (o.IsID) {
var obj = ToJson(o.ToValue(), graph, seen);
toList.Add(obj);
} else {
toList.Add(o.ToTypedJSON());
}
}
if (toList.Count == 1) {
rsp[p.Key] = toList.First();
} else {
rsp[p.Key] = new JArray(toList);
}
}
return rsp;
}
19
Source : GeolocationSingleListener.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
public void OnProviderEnabled(string provider)
{
lock (_activeProviders)
_activeProviders.Add(provider);
}
19
Source : PatriciaTrie.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
private void KeysR(PatriciaNode<V> node, int bit, HashSet<string> keys)
{
if (node.Bit <= bit)
{
return;
}
else
{
KeysR(node.Left, node.Bit, keys);
KeysR(node.Right, node.Bit, keys);
keys.Add(node.Key);
}
}
19
Source : ScriptContext.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
internal void WarnFormatIncompatible(string name)
{
if (features_warning == null)
{
features_warning = new HashSet<string>();
}
features_warning.Add(name);
}
19
Source : ScriptContext.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
internal void Warn(string name)
{
if (general_warnings == null)
{
general_warnings = new HashSet<string>();
}
general_warnings.Add(name);
}
19
Source : OpenMapOptionsForm.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private int MatchConfiguration(ConfigurationInfo configinfo, WAD wadfile)
{
string configfile = configinfo.Filename;
int score = 0;
// prefer configs that have a location set
if (configinfo.Resources.Count <= 0)
{
score -= 2;
}
// prefer configs that have a port of choice set
if (string.IsNullOrEmpty(configinfo.TestProgram))
{
score -= 1;
}
Configuration cfg = General.LoadGameConfiguration(configfile);
// Get the map lump names
IDictionary maplumpnames = cfg.ReadSetting("maplumpnames", new Hashtable());
HashSet<string> required_map_lump_names = new HashSet<string>();
int map_lumps_required = 0;
// Count how many required lumps we have to find
foreach (DictionaryEntry ml in maplumpnames)
{
string name = ml.Key.ToString();
// Ignore the map header (it will not be found because the name is different)
if (name != MapManager.CONFIG_MAP_HEADER && ml.Value is IDictionary)
{
// Read lump setting and count it
//if (cfg.ReadSetting("maplumpnames." + name + ".required", false))
// ano - for the love of god why isnt any of this typed properly
IDictionary hml = (IDictionary)ml.Value;
if (hml.Contains("required"))
{
if (Convert.ToBoolean(hml["required"]))
{
required_map_lump_names.Add(name.ToString());
map_lumps_required++;
}
}
}
}
// Get the lumps to detect just for game
IDictionary detectlumps = cfg.ReadSetting("gamedetect", new Hashtable());
HashSet<string> found_lumps = new HashSet<string>();
bool b_found_map = false;
int lump_count = wadfile.Lumps.Count;
int map_lumps_found = 0;
for (int lump_index = 0; lump_index < lump_count; lump_index++)
{
string lumpname = wadfile.Lumps[lump_index].Name;
if (detectlumps.Contains(lumpname))
{
found_lumps.Add(lumpname);
}
if (!b_found_map)
{
if (maplumpnames.Contains(lumpname))
{
if (required_map_lump_names.Contains(lumpname))
{
map_lumps_found++;
if (map_lumps_found >= map_lumps_required)
b_found_map = true;
}
}
else
{
map_lumps_found = 0;
}
}
}
if (!b_found_map)
{
score -= 100;
}
foreach (DictionaryEntry lmp in detectlumps)
{
// Setting not broken?
if ((lmp.Value is int) && (lmp.Key is string))
{
// ano - lmp.Value == 1 and 3 are ones we want
// If this lumps may not exist, and it is found
if ((int)lmp.Value == 2 && found_lumps.Contains((string)lmp.Key))
{
score -= 3;
}
// If this lumps must exist, and it is missing
else if (((int)lmp.Value == 3) && !found_lumps.Contains((string)lmp.Key))
{
score -= 7;
}
}
}
return score;
}
19
Source : Program.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
static void ExportSheetClreplaced(ExcelWorksheet worksheet, List<HeadInfo> clreplacedField, HashSet<string> uniqeField, ConfigType configType)
{
const int row = 2;
for (int col = 3; col <= worksheet.Dimension.End.Column; ++col)
{
string fieldName = worksheet.Cells[row + 2, col].Text.Trim();
if (fieldName == "")
{
continue;
}
if (!uniqeField.Add(fieldName))
{
continue;
}
string fieldCS = worksheet.Cells[row, col].Text.Trim();
string fieldDesc = worksheet.Cells[row + 1, col].Text.Trim();
string fieldType = worksheet.Cells[row + 3, col].Text.Trim();
clreplacedField.Add(new HeadInfo(fieldCS, fieldDesc, fieldName, fieldType));
}
}
19
Source : StringExtensions.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static object Eval(
this string text,
params object[] args)
{
text = string.Format(text, args);
try
{
if (syntaxErrorStrings.Contains(text))
{
return null;
}
return dataTable.Compute(text, string.Empty);
}
catch (SyntaxErrorException)
{
syntaxErrorStrings.Add(text);
throw;
}
}
19
Source : ChatLogModel.cs
with MIT License
from anoyetta
with MIT License
from anoyetta
public static ChatLogModel FromXIVLog(
ChatLogItem xivLog,
string[] currentPlayerNames)
{
var match = default(Match);
var log = new ChatLogModel()
{
XIVLog = xivLog,
SpeakerType = SpeakerTypes.XIVPlayer,
};
log.ChatCode = xivLog.Code;
var currentProfName = Config.Instance.ActiveProfile?.CharacterName;
var chatLogLine = RemoveSpecialChar(xivLog.Line);
var chatLogLineRaw = RemoveSpecialChar(xivLog.Raw);
var delimiterIndex = chatLogLineRaw.LastIndexOf("\u001f");
if (delimiterIndex > -1)
{
var message = chatLogLineRaw.Substring(delimiterIndex + 1);
chatLogLine = chatLogLine.Replace(message, $":{message}");
}
// メッセージを置換できていなければ話者辞書による置換を試みる
var i = chatLogLine.IndexOf(":");
if (i < 0)
{
var speaker = SpeakerHashes.FirstOrDefault(x => chatLogLine.StartsWith(x));
if (!string.IsNullOrEmpty(speaker))
{
if (chatLogLine.Length > speaker.Length)
{
chatLogLine = $"{speaker}:{chatLogLine.Substring(speaker.Length)}";
}
else
{
chatLogLine = $"{speaker}:";
}
}
}
i = chatLogLine.IndexOf(":");
if (i >= 0)
{
// 話者の部分を取り出す
var speakerPart = chatLogLine.Substring(0, i);
// ハッシュセットに記録する
SpeakerHashes.Add(speakerPart);
// サーバ名部分を取り出して書式を整える
match = CharacterNameWithServerRegex.Match(speakerPart);
if (match.Success)
{
var server = match.Groups["server"];
log.SpeakerServer = server.ToString();
log.SpeakerCharacterName = speakerPart.Remove(server.Index, server.Length);
speakerPart = $"{log.SpeakerCharacterName}@{log.SpeakerServer}";
}
else
{
log.SpeakerServer = string.Empty;
log.SpeakerCharacterName = speakerPart;
}
log.OriginalSpeaker = speakerPart;
log.Message = chatLogLine.Substring(i + 1);
}
else
{
log.OriginalSpeaker = string.Empty;
log.Message = chatLogLine;
}
if (currentPlayerNames != null)
{
log.IsMe = currentPlayerNames.Any(x =>
log.OriginalSpeaker.ContainsIgnoreCase(x));
}
else
{
if (!string.IsNullOrEmpty(currentProfName))
{
log.IsMe = log.OriginalSpeaker.ContainsIgnoreCase(currentProfName);
}
}
log.Message = FomartCharacterNames(log.message);
return log;
}
19
Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private HashSet<string> LoadFilenames()
{
var dir = string.IsNullOrEmpty(_directory) ? "." : _directory;
var set = new HashSet<string>();
foreach (var file in Directory.EnumerateFiles(dir))
{
set.Add(file);
}
return set;
}
19
Source : RabbitMessageQueue.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private void AddPublishExchange(string exchange)
{
if(_publishChannel == null)
{
CreatePublishChannel();
}
if (!_publishExchanges.Contains(exchange))
{
Dictionary<string, object>? args = null;
if (_options.Exchange.BradcastAlternateExchange != null)
{
args = new Dictionary<string, object>
{
["alternate-exchange"] = _options.Exchange.BradcastAlternateExchange
};
}
_publishChannel!.ExchangeDeclare(exchange, type: _options.ExchangeType, durable: _options.Exchange.Durable, autoDelete: _options.Exchange.AutoDelete ,arguments: args);
_publishExchanges.Add(exchange);
}
}
19
Source : RabbitMessageQueue.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
private void AddSubscriptionExchange(string exchange)
{
if(_consumerChannel == null)
{
CreateConsumerChannel();
}
if (_queueLocked)
return;
if (!_consumeExchanges.Contains(exchange))
{
_consumerChannel!.ExchangeDeclare(exchange,
type: _options.ExchangeType,
durable: _options.Exchange.Durable,
autoDelete: _options.Exchange.AutoDelete);
_consumeExchanges.Add(exchange);
}
}
19
Source : FrozenVideosService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Init(IEnumerable<MediaItem> items)
{
foreach (var item in items)
{
if (item.FilePath != null)
{
if (item.PauseOnLastFrame)
{
_frozenItems.Add(item.FilePath);
}
else if (_frozenItems.Contains(item.FilePath))
{
item.PauseOnLastFrame = true;
}
}
}
}
19
Source : FrozenVideosService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Add(string path)
{
_frozenItems.Add(path);
}
19
Source : HiddenMediaItemsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Init(IEnumerable<MediaItem> items)
{
_hiddenItemsInCurrentMediaFolder.Clear();
foreach (var item in items)
{
if (item.FilePath == null)
{
continue;
}
if (!item.IsVisible)
{
_hiddenItemsInCurrentMediaFolder.Add(item.FilePath);
_allHiddenItems.Add(item.FilePath);
}
else if (_allHiddenItems.Contains(item.FilePath))
{
_hiddenItemsInCurrentMediaFolder.Add(item.FilePath);
item.IsVisible = false;
}
}
OnHiddenItemsChangedEvent();
}
19
Source : HiddenMediaItemsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void Add(string path)
{
_hiddenItemsInCurrentMediaFolder.Add(path);
_allHiddenItems.Add(path);
OnHiddenItemsChangedEvent();
}
19
Source : Database.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private int FixupLocationValidity()
{
var fixupCount = 0;
// there is a unique index on the following Location table columns:
// KeySymbol, IssueTagNumber, MepsLanguage, DoreplacedentId, Track, Type
// Some Locations may have been stored in the db before this constraint
// was added, so identify them here and remove the duplicate entries.
// Note that null is treated as a unique value in SQLite
var keys = new HashSet<string>();
for (var n = Locations.Count - 1; n >= 0; --n)
{
var loc = Locations[n];
if (loc.Track == null || loc.DoreplacedentId == null)
{
continue;
}
var key = $"{loc.KeySymbol}|{loc.IssueTagNumber}|{loc.MepsLanguage}|{loc.DoreplacedentId.Value}|{loc.Track.Value}|{loc.Type}";
if (keys.Contains(key))
{
// found a duplicate that will cause a constraint exception.
++fixupCount;
Locations.RemoveAt(n);
Log.Logger.Error($"Removed duplicate location {loc.LocationId}");
}
else
{
keys.Add(key);
}
}
return fixupCount;
}
19
Source : OperatorViewModel.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void LoadMediaItemsInternal()
{
var files = _mediaProviderService.GetMediaFiles();
var sourceFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var destFilePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var file in files)
{
if (file.FullPath != null)
{
sourceFilePaths.Add(file.FullPath);
}
}
var itemsToRemove = new List<MediaItem>();
foreach (var item in MediaItems)
{
if (item.FilePath != null)
{
if (!sourceFilePaths.Contains(item.FilePath))
{
// remove this item.
itemsToRemove.Add(item);
}
else
{
// perhaps the item has been changed or swapped for another media file of the same name!
var file = files.SingleOrDefault(x => x.FullPath == item.FilePath);
if (file != null && file.LastChanged != item.LastChanged)
{
// remove this item.
itemsToRemove.Add(item);
}
else
{
destFilePaths.Add(item.FilePath);
}
}
}
}
var currenreplacedems = GetCurrentMediaItems(); // currently playing
var deletedCurrenreplacedems = currenreplacedems?.Intersect(itemsToRemove).ToArray();
var count = deletedCurrenreplacedems?.Length ?? 0;
if (count > 0)
{
// we have deleted one or more items that are currently being displayed!
Log.Logger.Warning($"User deleted {count} active items");
ForciblyStopAllPlayback(currenreplacedems);
_snackbarService.EnqueueWithOk(Properties.Resources.ACTIVE_ITEM_DELETED, Properties.Resources.OK);
}
// remove old items.
foreach (var item in itemsToRemove)
{
MediaItems.Remove(item);
}
// add new items.
foreach (var file in files)
{
if (file.FullPath != null && !destFilePaths.Contains(file.FullPath))
{
var item = CreateNewMediaItem(file);
MediaItems.Add(item);
_metaDataProducer.Add(item);
}
}
TruncateMediaItemsToMaxCount();
_hiddenMediaItemsService.Init(MediaItems);
_frozenVideosService.Init(MediaItems);
_pdfOptionsService.Init(MediaItems);
SortMediaItems();
InsertBlankMediaItem();
}
19
Source : Program.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
private void AddCompileUnit(
Dictionary<string, CompileUnit> unitMap,
HashSet<string> objSet,
string srcFile,
string cflags)
{
string outFile = Path.Combine(OutDir, EscapePath(srcFile) + ".bc");
objSet.Add(outFile);
CompileUnit compUnit = new CompileUnit(
string.Format("clang {0} -o {1} {2} -MD -c -flto " + cflags,
srcFile,
outFile,
OptLevel),
WorkDir,
OutDir,
outFile,
new HashSet<string> { srcFile });
compUnit.OnOutput = Console.WriteLine;
compUnit.OnError = Console.Error.WriteLine;
unitMap.Add(srcFile, compUnit);
}
19
Source : TypeGenerator.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
private TypeCppCode GenDeclCode(TypeX currType)
{
CodePrinter prt = new CodePrinter();
// 构造类型注释
prt.AppendFormatLine("// {0}",
currType.PrettyName());
// 构造类型结构体代码
string typeName;
string baseTypeName = null;
if (currType.BaseType != null &&
!currType.Def.IsValueType)
{
baseTypeName = currType.BaseType.GetCppName();
typeName = currType.GetCppName();
prt.AppendFormatLine("struct {0} : {1}\n{{",
typeName,
baseTypeName);
}
else if (currType.Def.ToTypeSig().IsObjectSig())
{
typeName = currType.GetCppName();
prt.AppendFormatLine("struct {0} : il2cppObject\n{{",
typeName);
}
else
{
Debug.replacedert(
currType.Def.IsValueType ||
currType.Def.IsInterface);
typeName = currType.GetCppName();
prt.AppendFormatLine("struct {0}\n{{",
typeName);
}
// 添加代码映射
TypeCppCode cppCode = new TypeCppCode(typeName);
CodeMap.Add(typeName, cppCode);
// 添加基类型依赖
if (baseTypeName != null)
cppCode.DeclDependNames.Add(baseTypeName);
++prt.Indents;
// 构造结构体成员
List<FieldX> staticFields = new List<FieldX>();
foreach (var fldX in currType.Fields)
{
if (fldX.Def.IsStatic)
{
staticFields.Add(fldX);
continue;
}
string fieldTypeName = fldX.FieldType.GetCppName(TypeMgr);
prt.AppendFormatLine("// {0}\n{1} {2};",
fldX.PrettyName(),
fieldTypeName,
fldX.GetCppName());
// 添加字段类型依赖
if (fldX.FieldType.IsValueType)
cppCode.DeclDependNames.Add(fieldTypeName);
}
--prt.Indents;
prt.AppendLine("};");
// 构造装箱类型
if (currType.Def.IsValueType)
{
prt.AppendFormatLine("struct box_{0} : il2cppObject\n{{",
typeName);
++prt.Indents;
prt.AppendFormatLine("{0} value;",
currType.ToTypeSig().GetCppName(TypeMgr));
--prt.Indents;
prt.AppendLine("};");
}
// 构造静态字段全局变量
StringBuilder sbImpl = new StringBuilder();
foreach (var sfldX in staticFields)
{
string sfldTypeName = sfldX.FieldType.GetCppName(TypeMgr);
string sfldCppName = sfldX.GetCppName();
string sfldPrettyName = sfldX.PrettyName(true);
string sfldDef = string.Format("{0} {1};\n",
sfldTypeName,
sfldCppName);
prt.AppendFormat("// {0}\nextern {1}",
sfldPrettyName,
sfldDef);
sbImpl.AppendFormat("// {0}\n{1}",
sfldPrettyName,
sfldDef);
StaticInitDecl.Append("extern " + sfldDef);
StaticInitBody.AppendFormat("{0} = {1};\n",
sfldCppName,
sfldX.FieldType.GetInitValue(TypeMgr));
// 添加字段类型依赖
if (sfldX.FieldType.IsValueType)
{
cppCode.DeclDependNames.Add(sfldTypeName);
cppCode.ImplDependNames.Add(sfldTypeName);
}
}
// 静态构造函数防止多次调用的标记
if (currType.CctorMethod != null)
{
string onceName = string.Format("onceflag_{0}",
typeName);
string onceDef = string.Format("int8_t {0};\n",
onceName);
string locktidName = string.Format("locktid_{0}",
typeName);
string locktidDef = string.Format("uintptr_t {0};\n",
locktidName);
prt.Append("extern " + onceDef);
prt.Append("extern " + locktidDef);
sbImpl.Append(onceDef);
sbImpl.Append(locktidDef);
StaticInitDecl.Append("extern " + onceDef);
StaticInitDecl.Append("extern " + locktidDef);
StaticInitBody.AppendFormat("{0} = 0;\n",
onceName);
StaticInitBody.AppendFormat("{0} = 0;\n",
locktidName);
}
cppCode.DeclCode.Append(prt);
cppCode.ImplCode.Append(sbImpl);
return cppCode;
}
19
Source : TypeGenerator.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
private void GenerateCompileUnits()
{
List<TypeCppCode> codeSorter = new List<TypeCppCode>(CodeMap.Values);
// 构建类型代码依赖关联
foreach (var cppCode in codeSorter)
{
foreach (string typeName in cppCode.DeclDependNames)
{
if (GetCodeFromMap(typeName, out var typeCode))
cppCode.DeclDependTypes.Add(typeCode);
}
cppCode.DeclDependNames = null;
foreach (string typeName in cppCode.ImplDependNames)
{
if (GetCodeFromMap(typeName, out var typeCode))
cppCode.ImplDependTypes.Add(typeCode);
}
cppCode.ImplDependNames = null;
}
CodeMap.Clear();
// 统计依赖计数
foreach (var cppCode in codeSorter)
{
// 预生成排序索引
cppCode.GetSortedID();
foreach (var typeCode in cppCode.DeclDependTypes)
++typeCode.DependCounter;
foreach (var typeCode in cppCode.ImplDependTypes)
++typeCode.DependCounter;
}
// 排序代码
codeSorter.Sort((x, y) =>
{
int cmp = x.GetSortedID().CompareTo(y.GetSortedID());
if (cmp == 0)
cmp = y.DependCounter.CompareTo(x.DependCounter);
return cmp;
});
// 划分编译单元
foreach (var cppCode in codeSorter)
{
var unit = GetCompileUnit();
unit.AddCode(cppCode);
cppCode.CompileUnit = unit;
}
StringGen.GenDefineCode(
100,
out var strSplitMap,
out var strCodeMap,
out string strTypeDefs);
// 生成代码
HashSet<string> dependSet = new HashSet<string>();
foreach (var unit in CompileUnits)
{
// 防止包含自身
dependSet.Add(unit.Name);
unit.DeclCode.Append("#pragma once\n");
unit.DeclCode.Append("#include \"il2cpp.h\"\n");
foreach (var cppCode in unit.CodeList)
{
// 生成头文件依赖包含
foreach (var typeCode in cppCode.DeclDependTypes)
{
string unitName = typeCode.CompileUnit.Name;
if (!dependSet.Contains(unitName))
{
dependSet.Add(unitName);
unit.DeclCode.AppendFormat("#include \"{0}.h\"\n",
unitName);
}
}
}
foreach (var cppCode in unit.CodeList)
{
// 拼接声明代码
unit.DeclCode.Append(cppCode.DeclCode);
cppCode.DeclCode = null;
cppCode.DeclDependTypes = null;
}
foreach (var cppCode in unit.CodeList)
{
// 生成源文件依赖包含
foreach (var typeCode in cppCode.ImplDependTypes)
{
string unitName = typeCode.CompileUnit.Name;
if (!dependSet.Contains(unitName))
{
dependSet.Add(unitName);
unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
unitName);
}
}
// 生成字符串包含
if (strSplitMap != null &&
cppCode.DependStrings.Count > 0)
{
HashSet<int> strUnitSet = new HashSet<int>();
foreach (string str in cppCode.DependStrings)
strUnitSet.Add(strSplitMap[str]);
cppCode.DependStrings = null;
foreach (var strUnitId in strUnitSet)
{
string strUnit = "StringUnit_" + strUnitId;
unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
strUnit);
}
}
}
foreach (var cppCode in unit.CodeList)
{
// 拼接实现代码
unit.ImplCode.Append(cppCode.ImplCode);
cppCode.ImplCode = null;
cppCode.ImplDependTypes = null;
}
// 如果包含内容则追加头文件
if (unit.ImplCode.Length > 0)
unit.ImplCode.Insert(0, string.Format("#include \"{0}.h\"\n", unit.Name));
unit.CodeList = null;
dependSet.Clear();
}
if (strTypeDefs.Length > 0)
{
foreach (var item in strCodeMap)
{
var strUnit = new CppCompileUnit("StringUnit_" + item.Key);
CompileUnits.Add(strUnit);
strUnit.DeclCode.Append("#pragma once\n");
strUnit.DeclCode.Append("#include \"StringTypes.h\"\n");
strUnit.DeclCode.Append(item.Value);
}
var strTypeDefUnit = new CppCompileUnit("StringTypes");
CompileUnits.Add(strTypeDefUnit);
strTypeDefUnit.DeclCode.Append("#pragma once\n");
strTypeDefUnit.DeclCode.Append("#include \"il2cpp.h\"\n");
strTypeDefUnit.DeclCode.Append(strTypeDefs);
}
// 添加初始化静态变量的函数
if (StaticInitBody.Length > 0)
{
var firstUnit = CompileUnits[0];
string initDecl = "void il2cpp_InitStaticVars()";
firstUnit.DeclCode.Append(initDecl + ";\n");
CodePrinter staticInitPrt = new CodePrinter();
staticInitPrt.Append(StaticInitDecl.ToString());
staticInitPrt.Append(initDecl);
staticInitPrt.AppendLine("\n{");
++staticInitPrt.Indents;
staticInitPrt.Append(StaticInitBody.ToString());
--staticInitPrt.Indents;
staticInitPrt.AppendLine("}");
firstUnit.ImplCode.Append(staticInitPrt);
}
}
19
Source : TypeResolver.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public void ReuseSlot(MethodSignature sig, MethodImpl impl)
{
bool result = VMap.TryGetValue(sig, out var layer);
Debug.replacedert(result);
layer.EntryTypes.Add(impl.DeclType.FullName);
layer.ImplMethod = impl;
}
19
Source : TypeResolver.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public void MergeSlot(TypeX currType, string typeName, MethodSignature sig)
{
var entry = new VirtualEntry(typeName, sig);
// 当前类定义了显式覆盖, 跳过
if (CurrExplicitMap.ContainsKey(entry))
return;
bool result = VMap.TryGetValue(sig, out var layer);
if (!result)
{
// 找不到且存在继承的显式覆盖, 跳过
if (DerivedExplicitMap.ContainsKey(entry))
return;
throw new NotSupportedException("MergeSlot " + entry);
}
if (layer.ImplMethod.DeclType.Equals(currType))
{
// 当前类型存在相同签名的实现, 删除并合并
DerivedExplicitMap.Remove(entry);
layer.EntryTypes.Add(typeName);
}
else if (!DerivedExplicitMap.ContainsKey(entry))
{
// 当前类型不存在实现且不存在显式覆盖, 合并
layer.EntryTypes.Add(typeName);
}
}
See More Examples