Newtonsoft.Json.JsonWriter.AutoCompleteClose C# (CSharp) Method

AutoCompleteClose() private method

private AutoCompleteClose ( JsonContainerType type ) : void
type JsonContainerType
return void
        private void AutoCompleteClose(JsonContainerType type)
        {
            // write closing symbol and calculate new state
            int levelsToComplete = 0;

            if (_currentPosition.Type == type)
            {
                levelsToComplete = 1;
            }
            else
            {
                int top = Top - 2;
                for (int i = top; i >= 0; i--)
                {
                    int currentLevel = top - i;

                    if (_stack[currentLevel].Type == type)
                    {
                        levelsToComplete = i + 2;
                        break;
                    }
                }
            }

            if (levelsToComplete == 0)
            {
                throw JsonWriterException.Create(this, "No token to close.", null);
            }

            for (int i = 0; i < levelsToComplete; i++)
            {
                JsonToken token = GetCloseTokenForType(Pop());

                if (_currentState == State.Property)
                {
                    WriteNull();
                }

                if (_formatting == Formatting.Indented)
                {
                    if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
                    {
                        WriteIndent();
                    }
                }

                WriteEnd(token);

                JsonContainerType currentLevelType = Peek();

                switch (currentLevelType)
                {
                    case JsonContainerType.Object:
                        _currentState = State.Object;
                        break;
                    case JsonContainerType.Array:
                        _currentState = State.Array;
                        break;
                    case JsonContainerType.Constructor:
                        _currentState = State.Array;
                        break;
                    case JsonContainerType.None:
                        _currentState = State.Start;
                        break;
                    default:
                        throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
                }
            }
        }