Challenge: write a reference counted slice that works as much as possible like a built-in slice

Andrei Alexandrescu SeeWebsiteForEmail at erdani.com
Mon Nov 8 22:38:27 UTC 2021


On 2021-11-08 17:15, deadalnix wrote:
> On Monday, 8 November 2021 at 21:42:12 UTC, Andrei Alexandrescu wrote:
>> 1. We could not make reference counting work properly in pure 
>> functions (a pure function does not mutate data, which goes against 
>> manipulating the reference count).
>>
> 
> I don't think this one is a real problem, as one can cast a function 
> call to pure and go through this. Dirty as hell, but done properly it 
> should work even in the face of compiler optimization based on purity. 
> GCC or LLVM would have no problem optimizing this scafolding away.

If you cast to pure then same compilers will be within their rights to 
optimize away calls - because they're pure.

>> 2. Qualifiers compound problems with interlocking: mutable data is 
>> known to be single-threaded, so no need for interlocking. Immutable 
>> data may be multi-threaded, meaning reference counting needs atomic 
>> operations. Const data has unknown origin, which means the information 
>> of how data originated (mutable or not) must be saved at runtime.
>>
> 
> shared_ptr does atomic operation all the time. The reality is that on 
> modern machines, atomic operation are cheap *granted there is no 
> contention*. It will certainly limit what the optimizer can do, but all 
> in all, it's almost certainly better than keeping the info around and 
> doing a runtime check.

In my measurements uncontested atomic increment are 2.5x or more slower 
than the equivalent increment.

>> 3. Safety forced the use of trusted blocks all over. Not a 
>> showstopper, but a complicating factor.
>>
>> So if there are any takers on getting RCSlice off the ground, it would 
>> be very interesting.
> 
> Yes, similar to pure, a bit anoying, but workable.
> 
> I think however, you missed several massive problems:
> 4. Type qualifier transitivity. const RCSlice!T -> const RCSlice!(const 
> T) conversion needs to happen transparently.
> 5. Head mutability. const RCSlice!(const T) -> RCSlice!(const T) 
> conversion needs to happen transparently.
> 6. Safety is impossible to ensure without a runtime check at every step, 
> because it is not possible to enforce construction in D at the moment, 
> so destrcutors and copy constructor/postblit always need to do a runtime 
> check for .init .
> 
> I believe 4 and 5 to be impossible in D right now, 6 can be solved using 
> a ton of runtime checks.

To which I say, stop posting, start coding.



More information about the Digitalmars-d mailing list