I wrote an AR archive (.a files) parser in D

IchorDev zxinsworld at gmail.com
Thu Aug 8 11:54:48 UTC 2024


On Thursday, 8 August 2024 at 10:55:49 UTC, Renato Athaydes wrote:
> I supposed this is the code bothering you?
>
>     auto file = (cast(string) input[0 .. 16]).strip;
>
> I do want a `string` there, but I think you're saying that 
> because `input` had a `in` attribute, it "may" be mutable via 
> another reference.
> I agree with that, specially when the "default" implementation 
> get the bytes from a memory-mapped file. What's the best 
> solution in this case, to dup the bytes and then cast to 
> `string`?

For `file` you should probably use `.idup` since your struct 
requires a `string`, but for `sizeStr` you can just cast to 
`const(char)[]`.

> Or you mean I can't even use `string` at all in this case, and 
> therefore can't use functions like `std.string : strip, 
> startsWith`?

That is plainly ridiculous. Read the documentation for these 
functions below and take note of how neither of them take 
`immutable(char)[]` (AKA `string`) as parameters:
- [`strip`](https://dlang.org/phobos/std_string.html#.strip) 
takes an array of any `const` char (`char`, `wchar`, or `dchar`). 
As a reminder, mutable and immutable both implicitly convert to 
`const`.
- 
[`startsWith`](https://dlang.org/phobos/std_algorithm_searching.html#startsWith) takes **any** kind of input range.

Also about why you should never cast to `immutable`:
The reason we have `immutable` is that while `const` may be 
useful, it doesn’t guarantee anything:
- mutable: this data can be modified here
- `const`: this data can’t be modified here
- `immutable`: this data will NEVER be modified after 
initialisation

The guarantee that `immutable` data is *actually* immutable is 
important. Casting the contents of an array to `immutable` 
completely nullifies this guarantee, and might cause problems 
with code that is optimised around that guarantee. Is this likely 
to affect your small case? Technically no, but it’s the first 
step down the dangerous path of lying to the compiler, which 
might end up causing you a lot of headaches when everything 
breaks later. Sometimes violating D’s type system is necessary or 
even desirable (see: `shared` w/ mutexes), but I wouldn’t 
recommend it for a beginner or even an intermediate D user.


More information about the Digitalmars-d mailing list