Quick Links: |
Provide fast repository for accessing weekend/holiday information. More...
Namespaces | |
namespace | bdlt |
bdlt::Calendar | fast repository for accessing weekend/holiday information |
bdlt::Calendar
, that represents weekend and holiday information over a valid range of dates. A bdlt::Calendar
is an approximation to the same mathematical type, and is capable of representing the same subset of mathematical values, as a bdlt::PackedCalendar
. A bdlt::Calendar
object (representing the same mathematical value) can be constructed directly from a reference to a non-modifiable bdlt::PackedCalendar
object, and a reference to a non-modifiable bdlt::PackedCalendar
is readily accessible from any bdlt::Calendar
object. bdlt::PackedCalendar
, which is optimized for spatial efficiency, bdlt::Calendar
is designed to be especially efficient at determining whether a given bdlt::Date
value (within the valid range for a particular bdlt::Calendar
object) is a business day -- i.e., not a weekend day or holiday (see "Usage" below). For example, the cost of determining whether a given bdlt::Date
is a business day, as opposed to a weekend or holiday, consists of only a few constant-time operations, compared to a binary search in a bdlt::PackedCalendar
representing the same calendar value. setValidRange
and addDay
methods modify the valid range of a calendar, and a suite of "add" methods can be used to populate a calendar with weekend days and holidays. addHolidayCode
method associates an integer "holiday code" with a specific date, and can be called repeatedly with different integers and the same date to build up a set of holiday codes for that date. Note that holiday codes are unique integers that, from the perspective of the calendar, have no particular meaning. Typically, the user will choose holiday code values that are indices into an auxiliary collection (such as a bsl::vector<bsl::string>
) to identify holiday names for end-user display. HolidayConstIterator
typedef
. The set of holiday codes associated with an arbitrary date in a bdlt::Calendar
(or the current holiday referred to by a HolidayConstIterator
) can be obtained in increasing (numerical) order using an iterator identified by the nested HolidayCodeConstIterator
typedef
(see below). addWeekendDay
and addWeekendDays
methods can be used to specify the weekend days for these calendars. addWeekendDaysTransition
method adds a new weekend-days transition or replaces an existing weekend-days transition. The addWeekendDay
and addWeekendDays
methods create a weekend-days transition at January 1, 0001, if one doesn't already exist, and update the set of weekend days for that transition. addWeekendDay
and addWeekendDays
should only be used for calendars having a consistent set of weekend days throughout their entire range. The use of addWeekendDay
and addWeekendDays
is intended to be mutually exclusive to the use of addWeekendDaysTransition
. As such, the behavior of using these two methods together with addWeekendDaysTransition
is undefined. const
bidirectional iterators accessible as nested typedef
s. HolidayConstIterator
, HolidayCodeConstIterator
, WeekendDaysTransitionConstIterator
, and BusinessDayConstIterator
, respectively, iterate over a chronologically ordered sequence of holidays, a numerically ordered sequence of holiday codes, a sequence of chronologically ordered weekend-days transitions, and a sequence of chronologically ordered business days. Reverse iterators are also provided for each of these (forward) iterators. As a general rule, calling a const
method will not invalidate any iterators, and calling a non-'const' method might invalidate all of them; it is, however, guaranteed that attempting to add duplicate holidays or holiday codes will have no effect, and therefore will not invalidate any iterators. It is also guaranteed that adding a new code for an existing holiday will not invalidate any HolidayConstIterator
objects. bsl::forward_iterator
and should not be used in standard algorithms (e.g., bsl::lower_bound
). bdlt::Calendar
will invalidate iterators referring to the calendar. The following table shows the relationship between a calendar manipulator and the types of iterators it will invalidate if the invocation of the manipulator modified the calendar (e.g., using addHoliday
with a date that is not currently a holiday in the calendar): Manipulator Invalidates -------------------------- -------------------- 'operator=' H HC WDT BD 'addHoliday' H HC BD 'addHolidayCode' HC 'addHolidayCodeIfInRange' HC 'addHolidayIfInRange' H HC BD 'addWeekendDay' WDT BD 'addWeekendDays' WDT BD 'addWeekendDaysTransition' WDT BD 'intersectBusinessDays' H HC WDT BD 'intersectNonBusinessDays' H HC WDT BD 'removeAll' H HC WDT BD 'removeHoliday' H HC BD 'removeHolidayCode' HC 'setValidRange' H HC BD 'unionBusinessDays' H HC WDT BD 'unionNonBusinessDays' H HC WDT BD where "H" represents the holiday iterators ('HolidayConstIterator' and 'HolidayConstReverseIterator'), "HC" represents the holiday code iterators ('HolidayCodeConstIterator' and 'HolidayCodeConstReverseIterator'), "WDT" represents the weekend-days transition iterators ('WeekendDaysTransitionConstIterator' and 'WeekendDaysTransitionConstReverseIterator'), and "BD" represents the business day iterators ('BusinessDayConstIterator' and 'BusinessDayConstReverseIterator').
bdlt::Calendar
supports O[1]
(i.e., constant-time) determination of whether a given bdlt::Date
value is or is not a business day, which is accomplished by augmenting the implementation of a packed calendar with a supplementary cache. The invariant that this cache and the data represented in the underlying bdlt::PackedCalendar
be maintained in a consistent state may add significantly to the cost of performing many manipulator operations, especially those that affect the calendar's valid range and add a new weekend-days transition. Moreover, the cost of many of these operations will now be proportional to the length(s) of the valid range(s), as well as their respective numbers of holidays and associated holiday codes and weekend-days transitions. Hence, when populating a calendar, it is recommended that the desired value be captured first as a bdlt::PackedCalendar
, which can then be used efficiently to value-construct the desired bdlt::Calendar
object. See the component-level doc for bdlt_packedcalendar
for its performance guarantees. bdlt::Calendar
are exception-safe, but in general provide only the basic guarantee (i.e., no guarantee of rollback): If an exception occurs (i.e., while attempting to allocate memory), the calendar object is left in a coherent state, but (unless otherwise specified) its value is undefined. bdlt::Calendars
can be populated directly, but are often more efficiently created by first creating a corresponding bdlt::PackedCalendar
, and then using that object to construct the calendar. As an example, suppose we want to provide efficient access to a (high-performance) bdlt::Calendar
for a variety of locales, whose raw information comes from, say, a database. The latency associated with fetching data for individual calendars on demand from a typical database can be prohibitively expensive, so it may make sense to acquire data for all calendars in a single query at start-up. MyPackedCalendarCache
that, internally, is just a mapping from (typically short) character string names (such as "NYB", representing New York Bank settlement days) to bdlt::PackedCalendar
objects, containing densely packed calendar data: class MyPackedCalendarCache { // This class maintains a space-efficient repository of calendar data // associated with a (typically short) name. // DATA bsl::unordered_map<bsl::string, bdlt::PackedCalendar> d_map; public: // CREATORS MyPackedCalendarCache(bslma::Allocator *basicAllocator = 0); // Create an empty 'MyPackedCalendarCache'. Optionally specify a // 'basicAllocator' used to supply memory. If 'basicAllocator' is // 0, the currently installed default allocator is used. // MANIPULATORS void assign(const bsl::string& name, const bdlt::PackedCalendar& calendar); // Associate the value of the specified 'calendar' with the // specified 'name'. // ACCESSORS const bdlt::PackedCalendar *lookup(const bsl::string& name) const; // Return the address of calendar data associated with the // specified 'name', or 0 if no such association exists. }; // CREATORS MyPackedCalendarCache::MyPackedCalendarCache( bslma::Allocator *basicAllocator) : d_map(basicAllocator) { } // MANIPULATORS void MyPackedCalendarCache::assign(const bsl::string& name, const bdlt::PackedCalendar& calendar) { d_map[name] = calendar; } // ACCESSORS const bdlt::PackedCalendar *MyPackedCalendarCache::lookup( const bsl::string& name) const { typedef bsl::unordered_map<bsl::string, bdlt::PackedCalendar> Cache; Cache::const_iterator iter = d_map.find(name); if (iter == d_map.end()) { return 0; // RETURN } return &iter->second; }
loadMyPackedCalendarCache
, that takes the address of a MyPackedCalendarCache
and populates it with up-to-date calendar data for all known locales (which, in the future, will be from a well-known database location): int loadMyPackedCalendarCache(MyPackedCalendarCache *result) // Load, into the specified 'result', up-to-date calendar information // for every known locale. Return 0 on success, and a non-zero value // otherwise. { bdlt::PackedCalendar calendar; calendar.setValidRange(bdlt::Date(2000, 1, 1), bdlt::Date(2020, 12, 31)); result->assign("NYB", calendar); return 0; }
MyCalendarCache
, that maintains a repository of the more runtime-efficient, but also more space-intensive, bdlt::Calendar
objects, which are instantiated on demand from a packed-calendar-based data source: class MyCalendarCache { // This class maintains a cache of runtime-efficient calendar objects // created on demand from a compact packed-calendar-based data source, // whose address is supplied at construction. // DATA MyPackedCalendarCache *d_datasource_p; bsl::unordered_map<bsl::string, bdlt::Calendar> d_map; public: // CREATORS MyCalendarCache(MyPackedCalendarCache *dataSource, bslma::Allocator *basicAllocator = 0); // Create an empty 'MyCalendarCache' associated with the specified // 'dataSource'. Optionally specify a 'basicAllocator' used to // supply memory. If 'basicAllocator' is 0, the currently // installed default allocator is used. // MANIPULATORS const bdlt::Calendar *lookup(const bsl::string& name); // Return the address of calendar data associated with the // specified 'name', or 0 if no such association exists in the data // source whose address was supplied at construction. Note that // this method may alter the physical state of this object (and is // therefore deliberately declared non-'const'). }; MyCalendarCache::MyCalendarCache(MyPackedCalendarCache *dataSource, bslma::Allocator *basicAllocator) : d_datasource_p(dataSource) , d_map(basicAllocator) { } const bdlt::Calendar *MyCalendarCache::lookup(const bsl::string& name) { typedef bsl::unordered_map<bsl::string, bdlt::Calendar> Cache; Cache::const_iterator iter = d_map.find(name); if (iter == d_map.end()) { const bdlt::PackedCalendar *pc = d_datasource_p->lookup(name); if (!pc) { // No such name in the data source. return 0; // RETURN } // Create new entry in calendar cache. iter = d_map.insert(bsl::make_pair(name, *pc)).first; } // An efficient calendar either already existed or was created. return &iter->second; }
MyPackedCalendarCache packedCalendarCache; MyCalendarCache calendarCache(&packedCalendarCache); loadMyPackedCalendarCache(&packedCalendarCache);
const bdlt::Calendar *calendarPtr = calendarCache.lookup("NYB"); assert(calendarPtr->firstDate() == bdlt::Date(2000, 1, 1)); assert(calendarPtr->lastDate() == bdlt::Date(2020, 12, 31));
bdlt::Calendar
substantially different from a bdlt::PackedCalendar
is the speed with which the bdlt::Calendar
can report whether a given date is or is not a business day. An important use of high-performance calendar objects in financial applications is to quickly determine the settlement date of a financial instrument. In some applications (e.g., those that explore the cross product of various portfolios over several horizons and scenarios), the settlement date may need to be calculated literally billions of times. The settlement date will often be determined from a periodic target date, such as the 15th or 30th of the month, which is then perturbed in some way to arrive at a valid settlement date. struct
, MyCalendarUtil
, that provides the modifiedFollowing
method: struct MyCalendarUtil { // CLASS METHODS static bdlt::Date modifiedFollowing(int targetDay, int month, int year, const bdlt::Calendar& calendar) // Return the date of the first business day at or after the // specified 'targetDay' in the specified 'month' and 'year' // according to the specified 'calendar', unless the resulting // date would not fall within 'month', in which case return // instead the date of the first business day before 'targetDay' // in 'month'. The behavior is undefined unless all candidate // dates applied to 'calendar' are within its valid range and // there exists at least one business day within 'month'. { BSLS_ASSERT(bdlt::Date::isValidYearMonthDay(year, month, targetDay)); // Efficiency is important so we will minimize the number of // conversions between year/month/day and 'bdlt::Date' objects. bdlt::Date date(year, month, targetDay); if (0 == calendar.getNextBusinessDay(&date, date - 1) && month == date.month()) { return date; // RETURN } while (calendar.isNonBusinessDay(--date)) { // empty } return date; } };
cal1
and cal2
, for testing the modifiedFollowing
method: bdlt::Calendar cal1(bdlt::Date(2015, 1, 1), bdlt::Date(2015,12, 31)); cal1.addWeekendDay(bdlt::DayOfWeek::e_SUN); cal1.addWeekendDay(bdlt::DayOfWeek::e_SAT); cal1.addHoliday(bdlt::Date(2015, 7, 3)); bdlt::Calendar cal2(cal1); cal2.addHoliday(bdlt::Date(2015, 7, 31));
modifiedFollowing
functionality: assert(bdlt::Date(2015, 7, 2) == MyCalendarUtil::modifiedFollowing( 2, 7, 2015, cal1)); assert(bdlt::Date(2015, 7, 6) == MyCalendarUtil::modifiedFollowing( 3, 7, 2015, cal1)); assert(bdlt::Date(2015, 7, 31) == MyCalendarUtil::modifiedFollowing(31, 7, 2015, cal1)); assert(bdlt::Date(2015, 7, 2) == MyCalendarUtil::modifiedFollowing( 2, 7, 2015, cal2)); assert(bdlt::Date(2015, 7, 6) == MyCalendarUtil::modifiedFollowing( 3, 7, 2015, cal2)); assert(bdlt::Date(2015, 7, 30) == MyCalendarUtil::modifiedFollowing(31, 7, 2015, cal2));