xxxxxxxxxx
import std;
enum Currency : string
{
USD = "USD",
EUR = "EUR",
GBP = "GBP",
JPY = "JPY",
}
struct Instrument
{
Currency bid;
Currency ask;
static immutable USD_JPY = Instrument(Currency.USD, Currency.JPY);
}
struct Price
{
Instrument instrument;
ulong value;
}
class MinRecorder
{
nothrow pure :
// prices from local scoped array buffers.
// I want to restrict prices reference to scope.
void update(scope const(Price)[] prices) scope
{
foreach (price; prices)
{
update(price);
}
}
// I thought price parameter need `scope` when called by scoped array elements.
// But it can remove `scope` attribute currently.
void update( /* scope */ ref const(Price) price) scope
{
if (minPrice.isNull || price.value < minPrice.get.value)
{
minPrice = price;
}
}
Nullable!Price minPrice;
}
class MinPointerRecorder
{
nothrow pure :
void update(scope const(Price)[] prices) scope
{
foreach (price; prices)
{
update(price);
}
}
void update( /* scope */ ref const(Price) price) scope
{
if (!minPrice || price.value < minPrice.value)
{
// @safe BUG?
// compile error at dmd v2.093
// Error: cannot take address of parameter price
minPrice = &price;
}
}
const(Price)* minPrice;
}
void main()
{
scope recorder = new MinRecorder();
// received prices in local buffers.
scope prices = [
Price(Instrument.USD_JPY, 300), Price(Instrument.USD_JPY, 100),
Price(Instrument.USD_JPY, 200),
];
recorder.update(prices);
writefln("%s", recorder.minPrice);
}