// Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Google Mock - a framework for writing C++ mock classes. // // This file tests the internal utilities. #include "gmock/internal/gmock-internal-utils.h" #include #include #include #include #include #include #include #include "gmock/gmock.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest-spi.h" #include "gtest/gtest.h" // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // their code. #define GTEST_IMPLEMENTATION_ 1 #include "src/gtest-internal-inl.h" #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_CYGWIN # include // For ssize_t. NOLINT #endif namespace proto2 { class Message; } // namespace proto2 namespace testing { namespace internal { namespace { TEST(JoinAsTupleTest, JoinsEmptyTuple) { EXPECT_EQ("", JoinAsTuple(Strings())); } TEST(JoinAsTupleTest, JoinsOneTuple) { const char* fields[] = {"1"}; EXPECT_EQ("1", JoinAsTuple(Strings(fields, fields + 1))); } TEST(JoinAsTupleTest, JoinsTwoTuple) { const char* fields[] = {"1", "a"}; EXPECT_EQ("(1, a)", JoinAsTuple(Strings(fields, fields + 2))); } TEST(JoinAsTupleTest, JoinsTenTuple) { const char* fields[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"}; EXPECT_EQ("(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)", JoinAsTuple(Strings(fields, fields + 10))); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) { EXPECT_EQ("", ConvertIdentifierNameToWords("")); EXPECT_EQ("", ConvertIdentifierNameToWords("_")); EXPECT_EQ("", ConvertIdentifierNameToWords("__")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) { EXPECT_EQ("1", ConvertIdentifierNameToWords("_1")); EXPECT_EQ("2", ConvertIdentifierNameToWords("2_")); EXPECT_EQ("34", ConvertIdentifierNameToWords("_34_")); EXPECT_EQ("34 56", ConvertIdentifierNameToWords("_34_56")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) { EXPECT_EQ("a big word", ConvertIdentifierNameToWords("ABigWord")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("FooBar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("Foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_Foo_Bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_Foo__And_Bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) { EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("foo_bar")); EXPECT_EQ("foo", ConvertIdentifierNameToWords("_foo_")); EXPECT_EQ("foo bar", ConvertIdentifierNameToWords("_foo_bar_")); EXPECT_EQ("foo and bar", ConvertIdentifierNameToWords("_foo__and_bar")); } TEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) { EXPECT_EQ("foo bar 123", ConvertIdentifierNameToWords("Foo_bar123")); EXPECT_EQ("chapter 11 section 1", ConvertIdentifierNameToWords("_Chapter11Section_1_")); } TEST(PointeeOfTest, WorksForSmartPointers) { EXPECT_TRUE( (std::is_same>::type>::value)); EXPECT_TRUE( (std::is_same>::type>::value)); } TEST(PointeeOfTest, WorksForRawPointers) { EXPECT_TRUE((std::is_same::type>::value)); EXPECT_TRUE((std::is_same::type>::value)); EXPECT_TRUE((std::is_void::type>::value)); } TEST(GetRawPointerTest, WorksForSmartPointers) { const char* const raw_p1 = new const char('a'); // NOLINT const std::unique_ptr p1(raw_p1); EXPECT_EQ(raw_p1, GetRawPointer(p1)); double* const raw_p2 = new double(2.5); // NOLINT const std::shared_ptr p2(raw_p2); EXPECT_EQ(raw_p2, GetRawPointer(p2)); } TEST(GetRawPointerTest, WorksForRawPointers) { int* p = nullptr; EXPECT_TRUE(nullptr == GetRawPointer(p)); int n = 1; EXPECT_EQ(&n, GetRawPointer(&n)); } // Tests KindOf. class Base {}; class Derived : public Base {}; TEST(KindOfTest, Bool) { EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool)); // NOLINT } TEST(KindOfTest, Integer) { EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t)); // NOLINT EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t)); // NOLINT #if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN // ssize_t is not defined on Windows and possibly some other OSes. EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t)); // NOLINT #endif } TEST(KindOfTest, FloatingPoint) { EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double)); // NOLINT EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double)); // NOLINT } TEST(KindOfTest, Other) { EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*)); // NOLINT EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**)); // NOLINT EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base)); // NOLINT } // Tests LosslessArithmeticConvertible. TEST(LosslessArithmeticConvertibleTest, BoolToBool) { EXPECT_TRUE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, BoolToInteger) { EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE( (LosslessArithmeticConvertible::value)); // NOLINT } TEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) { EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToBool) { EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToInteger) { // Unsigned => larger signed is fine. EXPECT_TRUE((LosslessArithmeticConvertible::value)); // Unsigned => larger unsigned is fine. EXPECT_TRUE((LosslessArithmeticConvertible< unsigned short, uint64_t>::value)); // NOLINT // Signed => unsigned is not fine. EXPECT_FALSE((LosslessArithmeticConvertible< short, uint64_t>::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible< signed char, unsigned int>::value)); // NOLINT // Same size and same signedness: fine too. EXPECT_TRUE((LosslessArithmeticConvertible< unsigned char, unsigned char>::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible< unsigned long, unsigned long>::value)); // NOLINT // Same size, different signedness: not fine. EXPECT_FALSE((LosslessArithmeticConvertible< unsigned char, signed char>::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); // Larger size => smaller size is not fine. EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) { // Integers cannot be losslessly converted to floating-points, as // the format of the latter is implementation-defined. EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible< short, long double>::value)); // NOLINT } TEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) { EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) { EXPECT_FALSE((LosslessArithmeticConvertible::value)); // NOLINT EXPECT_FALSE((LosslessArithmeticConvertible::value)); EXPECT_FALSE((LosslessArithmeticConvertible::value)); } TEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) { // Smaller size => larger size is fine. EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); // Same size: fine. EXPECT_TRUE((LosslessArithmeticConvertible::value)); EXPECT_TRUE((LosslessArithmeticConvertible::value)); // Larger size => smaller size is not fine. EXPECT_FALSE((LosslessArithmeticConvertible::value)); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (sizeof(double) == sizeof(long double)) { // NOLINT GTEST_INTENTIONAL_CONST_COND_POP_() // In some implementations (e.g. MSVC), double and long double // have the same size. EXPECT_TRUE((LosslessArithmeticConvertible::value)); } else { EXPECT_FALSE((LosslessArithmeticConvertible::value)); } } // Tests the TupleMatches() template function. TEST(TupleMatchesTest, WorksForSize0) { std::tuple<> matchers; std::tuple<> values; EXPECT_TRUE(TupleMatches(matchers, values)); } TEST(TupleMatchesTest, WorksForSize1) { std::tuple > matchers(Eq(1)); std::tuple values1(1), values2(2); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); } TEST(TupleMatchesTest, WorksForSize2) { std::tuple, Matcher > matchers(Eq(1), Eq('a')); std::tuple values1(1, 'a'), values2(1, 'b'), values3(2, 'a'), values4(2, 'b'); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); EXPECT_FALSE(TupleMatches(matchers, values4)); } TEST(TupleMatchesTest, WorksForSize5) { std::tuple, Matcher, Matcher, Matcher, // NOLINT Matcher > matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq("hi")); std::tuple // NOLINT values1(1, 'a', true, 2L, "hi"), values2(1, 'a', true, 2L, "hello"), values3(2, 'a', true, 2L, "hi"); EXPECT_TRUE(TupleMatches(matchers, values1)); EXPECT_FALSE(TupleMatches(matchers, values2)); EXPECT_FALSE(TupleMatches(matchers, values3)); } // Tests that Assert(true, ...) succeeds. TEST(AssertTest, SucceedsOnTrue) { Assert(true, __FILE__, __LINE__, "This should succeed."); Assert(true, __FILE__, __LINE__); // This should succeed too. } // Tests that Assert(false, ...) generates a fatal failure. TEST(AssertTest, FailsFatallyOnFalse) { EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__, "This should fail."); }, ""); EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, ""); } // Tests that Expect(true, ...) succeeds. TEST(ExpectTest, SucceedsOnTrue) { Expect(true, __FILE__, __LINE__, "This should succeed."); Expect(true, __FILE__, __LINE__); // This should succeed too. } // Tests that Expect(false, ...) generates a non-fatal failure. TEST(ExpectTest, FailsNonfatallyOnFalse) { EXPECT_NONFATAL_FAILURE({ // NOLINT Expect(false, __FILE__, __LINE__, "This should fail."); }, "This should fail"); EXPECT_NONFATAL_FAILURE({ // NOLINT Expect(false, __FILE__, __LINE__); }, "Expectation failed"); } // Tests LogIsVisible(). class LogIsVisibleTest : public ::testing::Test { protected: void SetUp() override { original_verbose_ = GMOCK_FLAG(verbose); } void TearDown() override { GMOCK_FLAG(verbose) = original_verbose_; } std::string original_verbose_; }; TEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) { GMOCK_FLAG(verbose) = kInfoVerbosity; EXPECT_TRUE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) { GMOCK_FLAG(verbose) = kErrorVerbosity; EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_FALSE(LogIsVisible(kWarning)); } TEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) { GMOCK_FLAG(verbose) = kWarningVerbosity; EXPECT_FALSE(LogIsVisible(kInfo)); EXPECT_TRUE(LogIsVisible(kWarning)); } #if GTEST_HAS_STREAM_REDIRECTION // Tests the Log() function. // Verifies that Log() behaves correctly for the given verbosity level // and log severity. void TestLogWithSeverity(const std::string& verbosity, LogSeverity severity, bool should_print) { const std::string old_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); Log(severity, "Test log.\n", 0); if (should_print) { EXPECT_THAT(GetCapturedStdout().c_str(), ContainsRegex( severity == kWarning ? "^\nGMOCK WARNING:\nTest log\\.\nStack trace:\n" : "^\nTest log\\.\nStack trace:\n")); } else { EXPECT_STREQ("", GetCapturedStdout().c_str()); } GMOCK_FLAG(verbose) = old_flag; } // Tests that when the stack_frames_to_skip parameter is negative, // Log() doesn't include the stack trace in the output. TEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = kInfoVerbosity; CaptureStdout(); Log(kInfo, "Test log.\n", -1); EXPECT_STREQ("\nTest log.\n", GetCapturedStdout().c_str()); GMOCK_FLAG(verbose) = saved_flag; } struct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface { std::string CurrentStackTrace(int max_depth, int skip_count) override { return (testing::Message() << max_depth << "::" << skip_count << "\n") .GetString(); } void UponLeavingGTest() override {} }; // Tests that in opt mode, a positive stack_frames_to_skip argument is // treated as 0. TEST(LogTest, NoSkippingStackFrameInOptMode) { MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter; GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter); CaptureStdout(); Log(kWarning, "Test log.\n", 100); const std::string log = GetCapturedStdout(); std::string expected_trace = (testing::Message() << GTEST_FLAG(stack_trace_depth) << "::").GetString(); std::string expected_message = "\nGMOCK WARNING:\n" "Test log.\n" "Stack trace:\n" + expected_trace; EXPECT_THAT(log, HasSubstr(expected_message)); int skip_count = atoi(log.substr(expected_message.size()).c_str()); # if defined(NDEBUG) // In opt mode, no stack frame should be skipped. const int expected_skip_count = 0; # else // In dbg mode, the stack frames should be skipped. const int expected_skip_count = 100; # endif // Note that each inner implementation layer will +1 the number to remove // itself from the trace. This means that the value is a little higher than // expected, but close enough. EXPECT_THAT(skip_count, AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10))); // Restores the default OS stack trace getter. GetUnitTestImpl()->set_os_stack_trace_getter(nullptr); } // Tests that all logs are printed when the value of the // --gmock_verbose flag is "info". TEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) { TestLogWithSeverity(kInfoVerbosity, kInfo, true); TestLogWithSeverity(kInfoVerbosity, kWarning, true); } // Tests that only warnings are printed when the value of the // --gmock_verbose flag is "warning". TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) { TestLogWithSeverity(kWarningVerbosity, kInfo, false); TestLogWithSeverity(kWarningVerbosity, kWarning, true); } // Tests that no logs are printed when the value of the // --gmock_verbose flag is "error". TEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) { TestLogWithSeverity(kErrorVerbosity, kInfo, false); TestLogWithSeverity(kErrorVerbosity, kWarning, false); } // Tests that only warnings are printed when the value of the // --gmock_verbose flag is invalid. TEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) { TestLogWithSeverity("invalid", kInfo, false); TestLogWithSeverity("invalid", kWarning, true); } // Verifies that Log() behaves correctly for the given verbosity level // and log severity. std::string GrabOutput(void(*logger)(), const char* verbosity) { const std::string saved_flag = GMOCK_FLAG(verbose); GMOCK_FLAG(verbose) = verbosity; CaptureStdout(); logger(); GMOCK_FLAG(verbose) = saved_flag; return GetCapturedStdout(); } class DummyMock { public: MOCK_METHOD0(TestMethod, void()); MOCK_METHOD1(TestMethodArg, void(int dummy)); }; void ExpectCallLogger() { DummyMock mock; EXPECT_CALL(mock, TestMethod()); mock.TestMethod(); } // Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to "info". TEST(ExpectCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)), HasSubstr("EXPECT_CALL(mock, TestMethod())")); } // Verifies that EXPECT_CALL doesn't log // if the --gmock_verbose flag is set to "warning". TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str()); } // Verifies that EXPECT_CALL doesn't log // if the --gmock_verbose flag is set to "error". TEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str()); } void OnCallLogger() { DummyMock mock; ON_CALL(mock, TestMethod()); } // Verifies that ON_CALL logs if the --gmock_verbose flag is set to "info". TEST(OnCallTest, LogsWhenVerbosityIsInfo) { EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethod())")); } // Verifies that ON_CALL doesn't log // if the --gmock_verbose flag is set to "warning". TEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kWarningVerbosity).c_str()); } // Verifies that ON_CALL doesn't log if // the --gmock_verbose flag is set to "error". TEST(OnCallTest, DoesNotLogWhenVerbosityIsError) { EXPECT_STREQ("", GrabOutput(OnCallLogger, kErrorVerbosity).c_str()); } void OnCallAnyArgumentLogger() { DummyMock mock; ON_CALL(mock, TestMethodArg(_)); } // Verifies that ON_CALL prints provided _ argument. TEST(OnCallTest, LogsAnythingArgument) { EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)), HasSubstr("ON_CALL(mock, TestMethodArg(_)")); } #endif // GTEST_HAS_STREAM_REDIRECTION // Tests StlContainerView. TEST(StlContainerViewTest, WorksForStlContainer) { StaticAssertTypeEq, StlContainerView >::type>(); StaticAssertTypeEq&, StlContainerView >::const_reference>(); typedef std::vector Chars; Chars v1; const Chars& v2(StlContainerView::ConstReference(v1)); EXPECT_EQ(&v1, &v2); v1.push_back('a'); Chars v3 = StlContainerView::Copy(v1); EXPECT_THAT(v3, Eq(
/*
             LUFA Library
     Copyright (C) Dean Camera, 2017.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/

/*
  Copyright 2017  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaims all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Functions to manage the physical Dataflash media, including reading and writing of
 *  blocks of data. These functions are called by the SCSI layer when data must be stored
 *  or retrieved to/from the physical storage media. If a different media is used (such
 *  as a SD card or EEPROM), functions similar to these will need to be generated.
 */

#define  INCLUDE_FROM_DATAFLASHMANAGER_C
#include "DataflashManager.h"

/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
 *  the pre-selected data OUT endpoint. This routine reads in OS sized blocks from the endpoint and writes
 *  them to the Dataflash in Dataflash page sized blocks.
 *
 *  \param[in] MSInterfaceInfo  Pointer to a structure containing a Mass Storage Class configuration and state
 *  \param[in] BlockAddress  Data block starting address for the write sequence
 *  \param[in] TotalBlocks   Number of blocks of data to write
 */
void DataflashManager_WriteBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo,
                                  const uint32_t BlockAddress,
                                  uint16_t TotalBlocks)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
	bool     UsingSecondBuffer   = false;

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
	/* Copy selected dataflash's current page contents to the Dataflash buffer */
	Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
	Dataflash_SendAddressBytes(CurrDFPage, 0);
	Dataflash_WaitWhileBusy();
#endif

	/* Send the Dataflash buffer write command */
	Dataflash_SendByte(DF_CMD_BUFF1WRITE);
	Dataflash_SendAddressBytes(0, CurrDFPageByte);

	/* Wait until endpoint is ready before continuing */
	if (Endpoint_WaitUntilReady())
	  return;

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if the endpoint is currently empty */
			if (!(Endpoint_IsReadWriteAllowed()))
			{
				/* Clear the current endpoint bank */
				Endpoint_ClearOUT();

				/* Wait until the host has sent another packet */
				if (Endpoint_WaitUntilReady())
				  return;
			}

			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Write the Dataflash buffer contents back to the Dataflash page */
				Dataflash_WaitWhileBusy();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
				Dataflash_SendAddressBytes(CurrDFPage, 0);

				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
				if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
				  UsingSecondBuffer = !(UsingSecondBuffer);

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
				/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
				if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
				{
					/* Copy selected dataflash's current page contents to the Dataflash buffer */
					Dataflash_WaitWhileBusy();
					Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
					Dataflash_SendAddressBytes(CurrDFPage, 0);
					Dataflash_WaitWhileBusy();
				}
#endif

				/* Send the Dataflash buffer write command */
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
				Dataflash_SendAddressBytes(0, 0);
			}

			/* Write one 16-byte chunk of data to the Dataflash */
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());
			Dataflash_SendByte(Endpoint_Read_8());

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;

			/* Check if the current command is being aborted by the host */
			if (MSInterfaceInfo->State.IsMassStoreReset)
			  return;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Write the Dataflash buffer contents back to the Dataflash page */
	Dataflash_WaitWhileBusy();
	Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
	Dataflash_SendAddressBytes(CurrDFPage, 0x00);
	Dataflash_WaitWhileBusy();

	/* If the endpoint is empty, clear it ready for the next packet from the host */
	if (!(Endpoint_IsReadWriteAllowed()))
	  Endpoint_ClearOUT();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
 *  the pre-selected data IN endpoint. This routine reads in Dataflash page sized blocks from the Dataflash
 *  and writes them in OS sized blocks to the endpoint.
 *
 *  \param[in] MSInterfaceInfo  Pointer to a structure containing a Mass Storage Class configuration and state
 *  \param[in] BlockAddress  Data block starting address for the read sequence
 *  \param[in] TotalBlocks   Number of blocks of data to read
 */
void DataflashManager_ReadBlocks(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo,
                                 const uint32_t BlockAddress,
                                 uint16_t TotalBlocks)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

	/* Send the Dataflash main memory page read command */
	Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
	Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);

	/* Wait until endpoint is ready before continuing */
	if (Endpoint_WaitUntilReady())
	  return;

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Read an endpoint packet sized data block from the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if the endpoint is currently full */
			if (!(Endpoint_IsReadWriteAllowed()))
			{
				/* Clear the endpoint bank to send its contents to the host */
				Endpoint_ClearIN();

				/* Wait until the endpoint is ready for more data */
				if (Endpoint_WaitUntilReady())
				  return;
			}

			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

				/* Send the Dataflash main memory page read command */
				Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
				Dataflash_SendAddressBytes(CurrDFPage, 0);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
			}

			/* Read one 16-byte chunk of data from the Dataflash */
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());
			Endpoint_Write_8(Dataflash_ReceiveByte());

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;

			/* Check if the current command is being aborted by the host */
			if (MSInterfaceInfo->State.IsMassStoreReset)
			  return;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* If the endpoint is full, send its contents to the host */
	if (!(Endpoint_IsReadWriteAllowed()))
	  Endpoint_ClearIN();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Writes blocks (OS blocks, not Dataflash pages) to the storage medium, the board Dataflash IC(s), from
 *  the given RAM buffer. This routine reads in OS sized blocks from the buffer and writes them to the
 *  Dataflash in Dataflash page sized blocks. This can be linked to FAT libraries to write files to the
 *  Dataflash.
 *
 *  \param[in] BlockAddress  Data block starting address for the write sequence
 *  \param[in] TotalBlocks   Number of blocks of data to write
 *  \param[in] BufferPtr     Pointer to the data source RAM buffer
 */
void DataflashManager_WriteBlocks_RAM(const uint32_t BlockAddress,
                                      uint16_t TotalBlocks,
                                      const uint8_t* BufferPtr)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);
	bool     UsingSecondBuffer   = false;

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
	/* Copy selected dataflash's current page contents to the Dataflash buffer */
	Dataflash_SendByte(DF_CMD_MAINMEMTOBUFF1);
	Dataflash_SendAddressBytes(CurrDFPage, 0);
	Dataflash_WaitWhileBusy();
#endif

	/* Send the Dataflash buffer write command */
	Dataflash_SendByte(DF_CMD_BUFF1WRITE);
	Dataflash_SendAddressBytes(0, CurrDFPageByte);

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Write an endpoint packet sized data block to the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Write the Dataflash buffer contents back to the Dataflash page */
				Dataflash_WaitWhileBusy();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
				Dataflash_SendAddressBytes(CurrDFPage, 0);

				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Once all the Dataflash ICs have had their first buffers filled, switch buffers to maintain throughput */
				if (Dataflash_GetSelectedChip() == DATAFLASH_CHIP_MASK(DATAFLASH_TOTALCHIPS))
				  UsingSecondBuffer = !(UsingSecondBuffer);

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

#if (DATAFLASH_PAGE_SIZE > VIRTUAL_MEMORY_BLOCK_SIZE)
				/* If less than one Dataflash page remaining, copy over the existing page to preserve trailing data */
				if ((TotalBlocks * (VIRTUAL_MEMORY_BLOCK_SIZE >> 4)) < (DATAFLASH_PAGE_SIZE >> 4))
				{
					/* Copy selected dataflash's current page contents to the Dataflash buffer */
					Dataflash_WaitWhileBusy();
					Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_MAINMEMTOBUFF2 : DF_CMD_MAINMEMTOBUFF1);
					Dataflash_SendAddressBytes(CurrDFPage, 0);
					Dataflash_WaitWhileBusy();
				}
#endif

				/* Send the Dataflash buffer write command */
				Dataflash_ToggleSelectedChipCS();
				Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2WRITE : DF_CMD_BUFF1WRITE);
				Dataflash_SendAddressBytes(0, 0);
			}

			/* Write one 16-byte chunk of data to the Dataflash */
			for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
			  Dataflash_SendByte(*(BufferPtr++));

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Write the Dataflash buffer contents back to the Dataflash page */
	Dataflash_WaitWhileBusy();
	Dataflash_SendByte(UsingSecondBuffer ? DF_CMD_BUFF2TOMAINMEMWITHERASE : DF_CMD_BUFF1TOMAINMEMWITHERASE);
	Dataflash_SendAddressBytes(CurrDFPage, 0x00);
	Dataflash_WaitWhileBusy();

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Reads blocks (OS blocks, not Dataflash pages) from the storage medium, the board Dataflash IC(s), into
 *  the preallocated RAM buffer. This routine reads in Dataflash page sized blocks from the Dataflash
 *  and writes them in OS sized blocks to the given buffer. This can be linked to FAT libraries to read
 *  the files stored on the Dataflash.
 *
 *  \param[in] BlockAddress  Data block starting address for the read sequence
 *  \param[in] TotalBlocks   Number of blocks of data to read
 *  \param[out] BufferPtr    Pointer to the data destination RAM buffer
 */
void DataflashManager_ReadBlocks_RAM(const uint32_t BlockAddress,
                                     uint16_t TotalBlocks,
                                     uint8_t* BufferPtr)
{
	uint16_t CurrDFPage          = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) / DATAFLASH_PAGE_SIZE);
	uint16_t CurrDFPageByte      = ((BlockAddress * VIRTUAL_MEMORY_BLOCK_SIZE) % DATAFLASH_PAGE_SIZE);
	uint8_t  CurrDFPageByteDiv16 = (CurrDFPageByte >> 4);

	/* Select the correct starting Dataflash IC for the block requested */
	Dataflash_SelectChipFromPage(CurrDFPage);

	/* Send the Dataflash main memory page read command */
	Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
	Dataflash_SendAddressBytes(CurrDFPage, CurrDFPageByte);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);
	Dataflash_SendByte(0x00);

	while (TotalBlocks)
	{
		uint8_t BytesInBlockDiv16 = 0;

		/* Read an endpoint packet sized data block from the Dataflash */
		while (BytesInBlockDiv16 < (VIRTUAL_MEMORY_BLOCK_SIZE >> 4))
		{
			/* Check if end of Dataflash page reached */
			if (CurrDFPageByteDiv16 == (DATAFLASH_PAGE_SIZE >> 4))
			{
				/* Reset the Dataflash buffer counter, increment the page counter */
				CurrDFPageByteDiv16 = 0;
				CurrDFPage++;

				/* Select the next Dataflash chip based on the new Dataflash page index */
				Dataflash_SelectChipFromPage(CurrDFPage);

				/* Send the Dataflash main memory page read command */
				Dataflash_SendByte(DF_CMD_MAINMEMPAGEREAD);
				Dataflash_SendAddressBytes(CurrDFPage, 0);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
				Dataflash_SendByte(0x00);
			}

			/* Read one 16-byte chunk of data from the Dataflash */
			for (uint8_t ByteNum = 0; ByteNum < 16; ByteNum++)
			  *(BufferPtr++) = Dataflash_ReceiveByte();

			/* Increment the Dataflash page 16 byte block counter */
			CurrDFPageByteDiv16++;

			/* Increment the block 16 byte block counter */
			BytesInBlockDiv16++;
		}

		/* Decrement the blocks remaining counter */
		TotalBlocks--;
	}

	/* Deselect all Dataflash chips */
	Dataflash_DeselectChip();
}

/** Disables the Dataflash memory write protection bits on the board Dataflash ICs, if enabled. */
void DataflashManager_ResetDataflashProtections(void)
{
	/* Select first Dataflash chip, send the read status register command */
	Dataflash_SelectChip(DATAFLASH_CHIP1);
	Dataflash_SendByte(DF_CMD_GETSTATUS);

	/* Check if sector protection is enabled */
	if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
	{
		Dataflash_ToggleSelectedChipCS();

		/* Send the commands to disable sector protection */
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
	}

	/* Select second Dataflash chip (if present on selected board), send read status register command */
	#if (DATAFLASH_TOTALCHIPS == 2)
	Dataflash_SelectChip(DATAFLASH_CHIP2);
	Dataflash_SendByte(DF_CMD_GETSTATUS);

	/* Check if sector protection is enabled */
	if (Dataflash_ReceiveByte() & DF_STATUS_SECTORPROTECTION_ON)
	{
		Dataflash_ToggleSelectedChipCS();

		/* Send the commands to disable sector protection */
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[0]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[1]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[2]);
		Dataflash_SendByte(DF_CMD_SECTORPROTECTIONOFF[3]);
	}
	#endif

	/* Deselect current Dataflash chip */
	Dataflash_DeselectChip();
}

/** Performs a simple test on the attached Dataflash IC(s) to ensure that they are working.
 *
 *  \return Boolean \c true if all media chips are working, \c false otherwise
 */
bool DataflashManager_CheckDataflashOperation(void)
{
	uint8_t ReturnByte;

	/* Test first Dataflash IC is present and responding to commands */
	Dataflash_SelectChip(DATAFLASH_CHIP1);
	Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
	ReturnByte = Dataflash_ReceiveByte();
	Dataflash_DeselectChip();

	/* If returned data is invalid, fail the command */
	if (ReturnByte != DF_MANUFACTURER_ATMEL)
	  return false;

	#if (DATAFLASH_TOTALCHIPS == 2)
	/* Test second Dataflash IC is present and responding to commands */
	Dataflash_SelectChip(DATAFLASH_CHIP2);
	Dataflash_SendByte(DF_CMD_READMANUFACTURERDEVICEINFO);
	ReturnByte = Dataflash_ReceiveByte();
	Dataflash_DeselectChip();

	/* If returned data is invalid, fail the command */
	if (ReturnByte != DF_MANUFACTURER_ATMEL)
	  return false;
	#endif

	return true;
}