errors.go
changeset 9 4b3436c03726
child 10 8dc05ff5dbe2
equal deleted inserted replaced
8:955d3add9426 9:4b3436c03726
       
     1 package takuzu
       
     2 
       
     3 import "fmt"
       
     4 
       
     5 // This file contains the takuzu validation error type.
       
     6 
       
     7 const (
       
     8 	ErrorNil = iota
       
     9 	ErrorDuplicate
       
    10 	ErrorTooManyValues
       
    11 	ErrorTooManyAdjacentValues
       
    12 )
       
    13 
       
    14 type validationError struct {
       
    15 	ErrorType    int
       
    16 	LineNumber   *int
       
    17 	ColumnNumber *int
       
    18 	CellValue    *int
       
    19 }
       
    20 
       
    21 func (e validationError) Error() string {
       
    22 	var axis string
       
    23 	var n int
       
    24 
       
    25 	// Currently we don't have validation errors with both
       
    26 	// line and column so we can get the axis:
       
    27 	if e.LineNumber != nil {
       
    28 		axis = "line"
       
    29 		n = *e.LineNumber
       
    30 	} else if e.ColumnNumber != nil {
       
    31 		axis = "column"
       
    32 		n = *e.ColumnNumber
       
    33 	}
       
    34 
       
    35 	switch e.ErrorType {
       
    36 	case ErrorNil:
       
    37 		return ""
       
    38 	case ErrorDuplicate:
       
    39 		if axis == "" {
       
    40 			return "internal validation error"
       
    41 		}
       
    42 		return fmt.Sprintf("duplicate %ss (%d)", axis, n)
       
    43 	case ErrorTooManyValues:
       
    44 		if axis == "" || e.CellValue == nil {
       
    45 			return "internal validation error"
       
    46 		}
       
    47 		var numberStr string
       
    48 		if *e.CellValue == 0 {
       
    49 			numberStr = "zeroes"
       
    50 		} else if *e.CellValue == 1 {
       
    51 			numberStr = "ones"
       
    52 		} else {
       
    53 			return "internal validation error"
       
    54 		}
       
    55 		return fmt.Sprintf("%s %d: too many %s", axis, n, numberStr)
       
    56 	case ErrorTooManyAdjacentValues:
       
    57 		if axis == "" || e.CellValue == nil {
       
    58 			return "internal validation error"
       
    59 		}
       
    60 		return fmt.Sprintf("%s %d: 3+ same values %d", axis, n, *e.CellValue)
       
    61 	}
       
    62 	return "internal validation error"
       
    63 }