public void TestAllocateAndFree() { var pool = new StringBuilderPool(); pool.Initialize(); Assert.IsTrue(pool.UsedListSize == 0 && pool.FreeListSize == 0); // allocate some instances var sb1 = pool.Allocate(); var sb2 = pool.Allocate(); Assert.IsTrue(pool.UsedListSize == 2 && pool.FreeListSize == 0); Assert.IsTrue(sb1 != sb2); Assert.IsTrue(sb1.Length == 0); // free both and then allocate two more again - we should get both back Assert.IsTrue(pool.ProduceValueAndFree(sb1) == ""); Assert.IsTrue(pool.ProduceValueAndFree(sb2) == ""); Assert.IsTrue(pool.UsedListSize == 0 && pool.FreeListSize == 2); var sb3 = pool.Allocate(); var sb4 = pool.Allocate(); Assert.IsTrue(pool.UsedListSize == 2 && pool.FreeListSize == 0); Assert.IsTrue(sb3 == sb2); Assert.IsTrue(sb4 == sb1); }
/// <summary> /// 组合路径,并标准化 /// </summary> public static string CombinePath(params string[] paths) { var builder = StringBuilderPool.Alloc(); for (int i = 0, iMax = paths.Length; i < iMax; i++) { builder.Append(paths[i].GetStandardPath().TrimStart('/')); if (i != iMax - 1) { builder.Append("/"); } } string result = builder.ToString(); builder.Recycle(); return(result); }
public void RecycleStringBuilderGetStringReturned() { var str = "Test"; var sb1 = StringBuilderPool.Obtain(); sb1.Append(str); Assert.AreEqual(str, sb1.ToPool()); var sb2 = StringBuilderPool.Obtain(); Assert.AreSame(sb1, sb2); sb2.Append(str); Assert.AreEqual(str, sb2.ToString()); var sb3 = StringBuilderPool.Obtain(); Assert.AreNotEqual(sb1, sb3); Assert.AreEqual(String.Empty, sb3.ToPool()); sb2.ToPool(); }
public async ValueTask <BungieResponse <ContentItemPublicContract> > GetContentByTagAndType( string tag, string type, string locale, CancellationToken cancellationToken = default) { var url = StringBuilderPool .GetBuilder(cancellationToken) .Append("/Content/GetContentByTagAndType/") .AddUrlParam(tag) .AddUrlParam(type) .AddUrlParam(locale) .Build(); return(await _dotNetBungieApiHttpClient .GetFromBungieNetPlatform <ContentItemPublicContract>(url, cancellationToken) .ConfigureAwait(false)); }
public async ValueTask <BungieResponse <ContentItemPublicContract> > GetContentById( long id, string locale, bool head = false, CancellationToken cancellationToken = default) { var url = StringBuilderPool .GetBuilder(cancellationToken) .Append("/Content/GetContentById/") .AddUrlParam(id.ToString()) .AddUrlParam(locale) .AddQueryParam("head", head.ToString()) .Build(); return(await _dotNetBungieApiHttpClient .GetFromBungieNetPlatform <ContentItemPublicContract>(url, cancellationToken) .ConfigureAwait(false)); }
public override String ToString() { var sb = StringBuilderPool.Obtain().Append(Symbols.SquareBracketOpen); var needsComma = false; foreach (var element in _elements) { if (needsComma) { sb.Append(Symbols.Comma); } sb.Append(element?.ToString() ?? "null"); needsComma = true; } return(sb.Append(Symbols.SquareBracketClose).ToPool()); }
private int SubstituteTag(string text, StringBuilderPool sb, int start, int modifierIndex, int end) { var url = text.Substring(start + 7, end - start - 7); // substitute [thetag] with <img> sb.Builder.Remove(start + modifierIndex, end - start + 8); var publicUrl = _mediaFileStore.MapPathToPublicUrl(url); var tag = "<img src=\"" + publicUrl + "\">"; tag = _htmlSanitizerService.Sanitize(tag); sb.Builder.Insert(start + modifierIndex, tag); // Return the value the stringbuilder start index has been modified for recursion. return(publicUrl.Length - url.Length - 3); }
/// <summary> /// Escapes the given text by replacing special characters with their /// XML entity (only applies to ampersands and opening angle brackets). /// </summary> /// <param name="content">The string to alter.</param> /// <returns>The altered string.</returns> public static String EscapeText(String content) { var temp = StringBuilderPool.Obtain(); for (var i = 0; i < content.Length; i++) { switch (content[i]) { case Symbols.Ampersand: temp.Append("&"); break; case Symbols.LessThan: temp.Append("<"); break; default: temp.Append(content[i]); break; } } return(temp.ToPool()); }
public async ValueTask <BungieResponse <CredentialTypeForAccount[]> > GetCredentialTypesForTargetAccount( long id, AuthorizationTokenData authorizationToken, CancellationToken cancellationToken = default) { var url = StringBuilderPool .GetBuilder(cancellationToken) .Append("/User/GetCredentialTypesForTargetAccount/") .AddUrlParam(id.ToString()) .Build(); return(await _dotNetBungieApiHttpClient .GetFromBungieNetPlatform <CredentialTypeForAccount[]>( url, cancellationToken, authorizationToken.AccessToken) .ConfigureAwait(false)); }
public async ValueTask <BungieResponse <SearchResultOfGroupMember> > GetMembersOfGroup( long groupId, int currentpage = 1, RuntimeGroupMemberType memberType = RuntimeGroupMemberType.None, string nameSearch = null, CancellationToken token = default) { var url = StringBuilderPool.GetBuilder(token) .Append("/GroupV2/") .AddUrlParam(groupId.ToString()) .Append("Members/") .AddQueryParam("currentpage", currentpage.ToString()) .AddQueryParam("memberType", ((int)memberType).ToString()) .AddQueryParam("nameSearch", nameSearch, () => !string.IsNullOrWhiteSpace(nameSearch)) .Build(); return(await _httpClient.GetFromBungieNetPlatform <SearchResultOfGroupMember>(url, token)); }
private static string ComputeEquivalenceKey(ImmutableArray <CodeAction> nestedActions) { var equivalenceKey = StringBuilderPool.Allocate(); try { foreach (var action in nestedActions) { equivalenceKey.Append((action.EquivalenceKey ?? action.GetHashCode().ToString()) + ";"); } return(equivalenceKey.Length > 0 ? equivalenceKey.ToString() : null); } finally { StringBuilderPool.ReturnAndFree(equivalenceKey); } }
public async ValueTask <BungieResponse <SearchResultOfContentItemPublicContract> > SearchContentByTagAndType( string locale, string tag, string type, int currentpage = 1, CancellationToken token = default) { var url = StringBuilderPool .GetBuilder(token) .Append("/Content/SearchContentByTagAndType/") .AddUrlParam(tag) .AddUrlParam(type) .AddUrlParam(locale) .AddQueryParam("currentpage", currentpage.ToString()) .Build(); return(await _httpClient.GetFromBungieNetPlatform <SearchResultOfContentItemPublicContract>(url, token)); }
/// <summary> /// Converts the <seealso cref="OriginateOptions"/> instance into an originate string. /// </summary> /// <returns>An originate string.</returns> public override string ToString() { var sb = StringBuilderPool.Allocate(); sb.Append("{"); sb.Append(parameters.ToOriginateString()); sb.Append(ChannelVariables.ToOriginateString()); if (sb.Length > 1) { sb.Remove(sb.Length - 1, 1); } sb.Append("}"); return(StringBuilderPool.ReturnAndFree(sb)); }
public async ValueTask <BungieResponse <DestinyEntitySearchResult> > SearchDestinyEntities( DefinitionsEnum type, string searchTerm, int page = 0, CancellationToken cancellationToken = default) { var url = StringBuilderPool .GetBuilder(cancellationToken) .Append("/Destiny2/Armory/Search/") .AddUrlParam(type.ToString()) .AddUrlParam(searchTerm) .AddQueryParam("page", page.ToString()) .Build(); return(await _dotNetBungieApiHttpClient .GetFromBungieNetPlatform <DestinyEntitySearchResult>(url, cancellationToken) .ConfigureAwait(false)); }
public static string CreateQuotedPrintableMIMEString(string charset, string text) { StringBuilder builder = StringBuilderPool.Alloc(); try { builder.Append(_mimeBegin); builder.Append(charset); builder.Append("?Q?"); EncodeQuotedPrintable(GetEncodingExceptionSafe(charset).GetBytes(text), builder); builder.Append("?="); return(builder.ToString()); } finally { StringBuilderPool.Dispose(builder); } }
/// <summary> /// 4.4.3. Single quoted string state /// </summary> private CssSelectorToken StringSQ() { var buffer = StringBuilderPool.Obtain(); while (true) { var current = _source.Next(); switch (current) { case Symbols.SingleQuote: case Symbols.EndOfFile: _source.Next(); return(NewString(buffer.ToPool())); case Symbols.FormFeed: case Symbols.LineFeed: return(NewString(buffer.ToPool())); case Symbols.ReverseSolidus: current = _source.Next(); if (current.IsLineBreak()) { buffer.AppendLine(); } else if (current != Symbols.EndOfFile) { _source.Back(); buffer.Append(_source.ConsumeEscape()); } else { return(NewString(buffer.ToPool())); } break; default: buffer.Append(current); break; } } }
public string GetPreviewText(IResource res, int lines) { StringBuilder builder = StringBuilderPool.Alloc(); try { builder.Append("<conversation>"); IStringList convsList = res.GetStringListProp(_manager._propConversationList); if (!_manager._reverseMode) { for (int i = 0; i < convsList.Count && lines-- > 0; ++i) { builder.Append(convsList[i]); } } else { for (int i = convsList.Count - 1; i >= 0 && lines-- > 0; --i) { builder.Append(convsList[i]); } } convsList.Dispose(); builder.Append("</conversation>"); XmlTextReader reader = new XmlTextReader(new StringReader(builder.ToString())); builder.Length = 0; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.MoveToAttribute("body")) { builder.AppendFormat("{0}\r\n", reader.Value); } reader.MoveToElement(); } } return(builder.ToString()); } finally { StringBuilderPool.Dispose(builder); } }
/** * returns the index of last processed line in the array */ private int ProcessBody(string[] lines, int fisrtLine, string boundary, MessagePartEncoding MIME_encoding, string bodyCharset) { int i = fisrtLine; if (MIME_encoding == MessagePartEncoding.Base64) { StringBuilder builder = StringBuilderPool.Alloc(); try { for ( ; i < lines.Length; ++i) { string line = lines[i].TrimEnd('\r'); if (line.StartsWith(boundary)) { break; } builder.Append(line); } _bodyBuilder.Append(DecodeLine(builder.ToString(), MIME_encoding, bodyCharset)); } finally { StringBuilderPool.Dispose(builder); } } else { for ( ; i < lines.Length; ++i) { string line = lines[i].TrimEnd('\r'); if (line.StartsWith(boundary)) { break; } _bodyBuilder.Append(DecodeLine(line, MIME_encoding, bodyCharset)); if (MIME_encoding != MessagePartEncoding.QuotedPrintable || !line.EndsWith("=")) { _bodyBuilder.Append("\r\n"); } } } return(i); }
private static UrlReference SingleQuoted(StringSource source) { var buffer = StringBuilderPool.Obtain(); while (true) { var current = source.Next(); if (current.IsLineBreak()) { return(Bad(source, buffer)); } else if (current == Symbols.EndOfFile) { return(new UrlReference(buffer.ToPool())); } else if (current == Symbols.SingleQuote) { return(End(source, buffer)); } else if (current != Symbols.ReverseSolidus) { buffer.Append(current); } else { current = source.Next(); if (current == Symbols.EndOfFile) { source.Back(); return(new UrlReference(buffer.ToPool())); } else if (current.IsLineBreak()) { buffer.AppendLine(); } else { buffer.Append(source.ConsumeEscape()); } } } }
/// <summary> /// Gets the trimmed content until either '}' or ';' is hit. /// </summary> /// <returns>The trimmed string.</returns> public String ContentFrom(Int32 position) { var sb = StringBuilderPool.Obtain(); Back(Position - position); var current = Current; var spaced = 0; while (!current.IsOneOf(Symbols.EndOfFile, Symbols.Semicolon, Symbols.CurlyBracketOpen, Symbols.CurlyBracketClose)) { var token = Data(current); if (token.Type == CssTokenType.Whitespace) { spaced++; sb.Append(current); current = GetNext(); } else { var length = Position - position; Back(length++); current = Current; spaced = 0; while (length > 0) { sb.Append(current); --length; current = GetNext(); } } position = Position; } if (spaced > 0) { sb.Remove(sb.Length - spaced, spaced); } Back(); return(sb.ToPool()); }
public TracePayload GetSerializedPayload(object source, TraceRecord traceRecord, Exception exception, bool getServiceReference) { string eventSource = null; string extendedData = null; string serializedException = null; if (source != null) { eventSource = CreateSourceString(source); } if (traceRecord != null) { StringBuilder sb = StringBuilderPool.Take(); try { using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture)) { using (XmlWriter writer = XmlWriter.Create(stringWriter)) { writer.WriteStartElement(DiagnosticStrings.ExtendedDataTag); traceRecord.WriteTo(writer); writer.WriteEndElement(); writer.Flush(); stringWriter.Flush(); extendedData = sb.ToString(); } } } finally { StringBuilderPool.Return(sb); } } if (exception != null) { // We want to keep the ETW trace message to under 32k. So we keep the serialized exception to under 28k bytes. serializedException = ExceptionToTraceString(exception, MaxExceptionStringLength); } return(new TracePayload(serializedException, eventSource, DiagnosticTraceBase.AppDomainFriendlyName, extendedData, string.Empty)); }
private static TextChange FixDiagnostic(IndentationOptions indentationOptions, SourceText sourceText, Diagnostic diagnostic) { TextSpan span = diagnostic.Location.SourceSpan; TextLine startLine = sourceText.Lines.GetLineFromPosition(span.Start); string text = sourceText.ToString(TextSpan.FromBounds(startLine.Start, span.End)); StringBuilder replacement = StringBuilderPool.Allocate(); int column = 0; for (int i = 0; i < text.Length; i++) { char c = text[i]; if (c == '\t') { var offsetWithinTabColumn = column % indentationOptions.TabSize; var spaceCount = indentationOptions.TabSize - offsetWithinTabColumn; if (i >= span.Start - startLine.Start) { replacement.Append(' ', spaceCount); } column += spaceCount; } else { if (i >= span.Start - startLine.Start) { replacement.Append(c); } if (c == '\n') { column = 0; } else { column++; } } } return(new TextChange(span, StringBuilderPool.ReturnAndFree(replacement))); }
private static Color?Literal(StringSource source) { var current = source.Next(); var result = default(Color); var buffer = StringBuilderPool.Obtain(); while (current.IsHex()) { buffer.Append(current); current = source.Next(); } if (Color.TryFromHex(buffer.ToPool(), out result)) { return(result); } return(null); }
/// <summary> /// 4.4.12. Number state /// </summary> private CssSelectorToken NumberStart(Char current) { while (true) { if (current is Symbols.Plus or Symbols.Minus) { var buffer = StringBuilderPool.Obtain(); buffer.Append(current); current = _source.Next(); if (current == Symbols.Dot) { buffer.Append(current).Append(_source.Next()); return(NumberFraction(buffer)); } buffer.Append(current); return(NumberRest(buffer)); }
/// <summary> /// Provides a string representation of the <see cref="EventMessage"/> instance for debugging. /// </summary> public override string ToString() { var sb = StringBuilderPool.Allocate(); sb.AppendLine("Event Headers:"); foreach (var h in Headers.OrderBy(x => x.Key)) { sb.AppendLine("\t" + h.Key + " : " + h.Value); } if (!string.IsNullOrEmpty(BodyText)) { sb.AppendLine("Body:"); sb.AppendLine(BodyText); } return(StringBuilderPool.ReturnAndFree(sb)); }
public Task Play(IEnumerable <string> files, Leg leg = Leg.ALeg, string terminator = null) { var sb = StringBuilderPool.Allocate(); var first = true; sb.Append("file_string://"); foreach (var file in files) { if (!first) { sb.Append("!"); } sb.Append(file); first = false; } return(Play(StringBuilderPool.ReturnAndFree(sb), leg, terminator)); }
String IStyleFormatter.BlockRules(IEnumerable <IStyleFormattable> rules) { if (ShouldKeepEmptyRules || IsNotEmpty(rules)) { var sb = StringBuilderPool.Obtain().Append(Symbols.CurlyBracketOpen); using (var writer = new StringWriter(sb)) { foreach (var rule in rules) { rule.ToCss(writer, this); } } return(sb.Append(Symbols.CurlyBracketClose).ToPool()); } return(String.Empty); }
String IStyleFormatter.Sheet(IEnumerable <IStyleFormattable> rules) { if (ShouldKeepEmptyRules || IsNotEmpty(rules)) { var sb = StringBuilderPool.Obtain(); using (var writer = new StringWriter(sb)) { foreach (var rule in rules) { rule.ToCss(writer, this); } } return(sb.ToPool()); } return(String.Empty); }
public static string Select(this ISqlDialect d, string table, string schema, List <string> columns, List <string> keys) { return(StringBuilderPool.Scoped(sb => { sb.Append("SELECT "); for (var i = 0; i < columns.Count; i++) { sb.AppendName(d, columns[i]); if (i < columns.Count - 1) { sb.Append(", "); } } sb.Append(" FROM ").AppendTable(d, table, schema).AppendWhereClause(d, keys); })); }
/** * Adds a pending paragraph (possibly quoted) to the paragraph list. */ private void AddTextPara(ArrayList lines, bool beforeEmptyLine) { if (lines.Count > 0) { PlainTextParaType paraType = IsPlainTextPara(lines); if (paraType == PlainTextParaType.Plain) { StringBuilder bodyBuilder = StringBuilderPool.Alloc(); try { for (int i = 0; i < lines.Count - 1; i++) { string line = (string)lines [i]; bodyBuilder.Append(line); if (!line.EndsWith(" ")) { bodyBuilder.Append(" "); } } bodyBuilder.Append(lines [lines.Count - 1]); _paragraphs.Add(new Paragraph(bodyBuilder.ToString(), ParagraphType.Plain, _lastQuoteLevel, _lastQuotePrefix, _foundOutlookQuote)); } finally { StringBuilderPool.Dispose(bodyBuilder); } } else if (paraType == PlainTextParaType.Fixed) { AddFixedParas(lines, beforeEmptyLine); } else { foreach (string line in lines) { _paragraphs.Add(new Paragraph(line, ParagraphType.Plain, _lastQuoteLevel, _lastQuotePrefix, _foundOutlookQuote)); } } } }
public override String ToString() { var sb = StringBuilderPool.Obtain().Append(Symbols.CurlyBracketOpen); var needsComma = false; foreach (var property in _properties) { if (needsComma) { sb.Append(Symbols.Comma); } sb.Append(Symbols.DoubleQuote).Append(property.Key).Append(Symbols.DoubleQuote); sb.Append(Symbols.Colon).Append(property.Value.ToString()); needsComma = true; } return(sb.Append(Symbols.CurlyBracketClose).ToPool()); }
public void TestReset() { var pool = new StringBuilderPool(); pool.Initialize(); // allocate a new string builder and make sure we use it var sb1 = pool.Allocate(); Assert.IsTrue(sb1.Length == 0); sb1.Append("abc"); Assert.IsTrue(sb1.Length == 3); // finalize it, and make sure it got reset Assert.IsTrue(pool.ProduceValueAndFree(sb1) == "abc"); Assert.IsTrue(sb1.Length == 0); // now allocate again, this time since it's coming from the object pool, // we'll get back the same instance var sb2 = pool.Allocate(); Assert.IsTrue(sb1 == sb2); Assert.IsTrue(sb2.Length == 0); // and it's been reset }
public void TestPoolRelease() { var pool = new StringBuilderPool(); pool.Initialize(); // allocate a new instance using this custom factory, make sure the factory code got called var sb1 = pool.Allocate(); sb1.Append("abc"); Assert.IsTrue(pool.UsedListSize == 1); Assert.IsTrue(pool.FreeListSize == 0); // allocate and free an instance. this will grow the pool to size one Assert.IsTrue(pool.ProduceValueAndFree(pool.Allocate()) == ""); Assert.IsTrue(pool.UsedListSize == 1); Assert.IsTrue(pool.FreeListSize == 1); // now release the entire object pool. this will clear out the free list, but will not // affect the object already in circulation, since we're not tracking them. pool.Release(); Assert.IsTrue(sb1.Length == 3); Assert.IsTrue(pool.UsedListSize == 1); Assert.IsTrue(pool.FreeListSize == -1); }