             
         } else {
             
-            let attributes = self._attributes
-            
-            self._attributes = attributes.filter { $0.index <= range.lowerBound }
-            
-            if self._attributes[self._attributes.count - 1].index == range.lowerBound {
-                
-                self._attributes[self._attributes.count - 1].attribute[keyPath: keyPath] = value
-                
-            } else {
-                
-                var attribute = self._attributes[self._attributes.count - 1].attribute
-                attribute[keyPath: keyPath] = value
-                self._attributes.append(_Attribute(index: range.lowerBound, attribute: attribute))
+            var attributes = _attributes_slice(from: 0..<range.lowerBound)
+            
+            for var attribute in _attributes_slice(from: range) {
+                attribute.attribute[keyPath: keyPath] = value
+                attributes.append(attribute)
             }
             
-            let attributes_in_range = attributes.lazy.filter { $0.index != range.lowerBound && range ~= $0.index }
-            
-            for var attribute in attributes_in_range {
-                attribute.attribute[keyPath: keyPath] = value
-                self._attributes.append(attribute)
-            }
-            
-            if var attribute = attributes_in_range.max(by: { $0.index }) {
-                attribute.attribute[keyPath: keyPath] = value
-                self._attributes.append(_Attribute(index: range.upperBound, attribute: attribute.attribute))
-            }
-            
-            self._attributes.append(contentsOf: attributes.lazy.filter { $0.index > range.upperBound })
-            
+            attributes.append(contentsOf: _attributes_slice(from: range.upperBound..<_string.count))
+            
+            self._attributes = attributes
             self._fix_attributes()
         }
     }

extension AttributedString {
    
    @inlinable
    public func attributedSubstring(from range: Range<Int>) -> AttributedString {
        
        precondition(range.clamped(to: 0..<_string.count) == range, "Index out of range.")

        let endIndex = _string.index(_string.startIndex, offsetBy: range.upperBound)
        
        let substring = _string[startIndex..<endIndex]
        let attributes = _attributes_slice(from: range).map { _Attribute(index: $0.index - range.lowerBound, attribute: $0.attribute) }
        
        return AttributedString(string: substring, attributes: attributes)
    }
