Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: syntactic sugar for initializing Span<char> by stackalloc with string literal #1947

Open
acid-chicken opened this issue Oct 22, 2018 · 5 comments

Comments

@acid-chicken
Copy link

Summary

Provide a syntactic sugar which initializes Span and ReadOnlySpan with stackalloc keyword by string literal.

Design

Span<char> span = stackalloc [] "initial characters";

will be converted to

Span<char> span = stackalloc [] { 'i', 'n', 'i', 't', 'i', 'a', 'l', ' ', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's' };

Choices

Syntax Style

Span<char> span = stackalloc [] "initial characters";

or

Span<char> span = stackalloc "initial characters";

or

Span<char> span = stackalloc char[] "initial characters";
/* NEED TO SPECIFY TYPE STRICTLY */

or other?

Also Support char[]

Also adding syntactic suger for char[] initializer?

@svick
Copy link
Contributor

svick commented Oct 22, 2018

Why? Are there any cases where memory consumed by string literals is an issue?

@jnm2
Copy link
Contributor

jnm2 commented Oct 22, 2018

@svick I read this as wanting to initialize the space from a string literal but then using it as scratch space.

@svick
Copy link
Contributor

svick commented Oct 22, 2018

@jnm2

Oh, so the equivalent of the following code?

string s = "initial characters";
Span<char> span = stackalloc char[s.Length];
s.AsSpan().CopyTo(span);

Is that actually so common that it needs syntactic sugar?

@AraHaan
Copy link
Member

AraHaan commented Oct 22, 2018

I do not think so. I did not even know about Span in c#.

@jnm2
Copy link
Contributor

jnm2 commented Oct 22, 2018

@svick That's what I understood @acid-chicken to mean. I haven't run into this pattern before, though I have been in situations where I'd copy a literal to the beginning of a longer buffer.

If the stack space isn't going to be mutated after copying the literal into it, I'd just get the pointer to the literal directly without allocating stack space and doing the copy (or use ReadOnlySpan).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants