/*------------------------------------------------------------------------------ * Copyright (c) 2023 by Bai Bing (seread@163.com) * S++ COPYING file for copying and redistribution conditions. * * Alians IT Studio. *----------------------------------------------------------------------------*/ #include "ASSlice.h" namespace ais { bool Slice::operator==(const Slice &otherSlice) const noexcept { return start == otherSlice.start && stop == otherSlice.stop && step == otherSlice.step; } bool Slice::operator!=(const Slice &otherSlice) const noexcept { return !(*this == otherSlice); } std::string Slice::str() const { std::string out = "[" + std::to_string(start) + ":" + std::to_string(stop) + ":" + std::to_string(step) + "]\n"; return out; } void Slice::print() const { std::cout << *this; } void Slice::make_positive_and_validate(size_t arraySize) { /// convert the start value if (start < 0) { start += arraySize; } if (start > (arraySize - 1)) { throw std::invalid_argument("Invalid start value for array of size " + std::to_string(arraySize) + "."); } /// convert the stop value if (stop < 0) { stop += arraySize; } if (stop > (arraySize)) { throw std::invalid_argument("Invalid stop value for array of size " + std::to_string(arraySize) + "."); } /// do some error checking if (start < stop) { if (step < 0) { throw std::invalid_argument("Invalid slice values [" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + ']'); } } if (stop < start) { if (step > 0) { throw std::invalid_argument("Invalid slice values [" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + ']'); } /// otherwise flip things around for my own sanity std::swap(start, stop); step *= -1; } } size_t Slice::element_number(size_t arraySize) { make_positive_and_validate(arraySize); size_t num = 0; for (size_t i = start; i < stop; i += step) { ++num; } return num; } } // namespace ais